1 //===- BasicTTIImpl.h -------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// This file provides a helper that implements much of the TTI interface in
11 /// terms of the target-independent code generator and TargetLowering
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_CODEGEN_BASICTTIIMPL_H
17 #define LLVM_CODEGEN_BASICTTIIMPL_H
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/Analysis/TargetTransformInfoImpl.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Target/TargetLowering.h"
23 #include "llvm/Target/TargetSubtargetInfo.h"
27 extern cl::opt<unsigned> PartialUnrollingThreshold;
29 /// \brief Base class which can be used to help build a TTI implementation.
31 /// This class provides as much implementation of the TTI interface as is
32 /// possible using the target independent parts of the code generator.
34 /// In order to subclass it, your class must implement a getST() method to
35 /// return the subtarget, and a getTLI() method to return the target lowering.
36 /// We need these methods implemented in the derived class so that this class
37 /// doesn't have to duplicate storage for them.
39 class BasicTTIImplBase : public TargetTransformInfoImplCRTPBase<T> {
41 typedef TargetTransformInfoImplCRTPBase<T> BaseT;
42 typedef TargetTransformInfo TTI;
44 /// Estimate the overhead of scalarizing an instruction. Insert and Extract
45 /// are set if the result needs to be inserted and/or extracted from vectors.
46 unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) {
47 assert(Ty->isVectorTy() && "Can only scalarize vectors");
50 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
52 Cost += static_cast<T *>(this)
53 ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
55 Cost += static_cast<T *>(this)
56 ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
62 /// Estimate the cost overhead of SK_Alternate shuffle.
63 unsigned getAltShuffleOverhead(Type *Ty) {
64 assert(Ty->isVectorTy() && "Can only shuffle vectors");
66 // Shuffle cost is equal to the cost of extracting element from its argument
67 // plus the cost of inserting them onto the result vector.
69 // e.g. <4 x float> has a mask of <0,5,2,7> i.e we need to extract from
70 // index 0 of first vector, index 1 of second vector,index 2 of first
71 // vector and finally index 3 of second vector and insert them at index
72 // <0,1,2,3> of result vector.
73 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
74 Cost += static_cast<T *>(this)
75 ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
76 Cost += static_cast<T *>(this)
77 ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
82 /// \brief Local query method delegates up to T which *must* implement this!
83 const TargetSubtargetInfo *getST() const {
84 return static_cast<const T *>(this)->getST();
87 /// \brief Local query method delegates up to T which *must* implement this!
88 const TargetLoweringBase *getTLI() const {
89 return static_cast<const T *>(this)->getTLI();
93 explicit BasicTTIImplBase(const TargetMachine *TM)
94 : BaseT(TM->getDataLayout()) {}
97 // Provide value semantics. MSVC requires that we spell all of these out.
98 BasicTTIImplBase(const BasicTTIImplBase &Arg)
99 : BaseT(static_cast<const BaseT &>(Arg)) {}
100 BasicTTIImplBase(BasicTTIImplBase &&Arg)
101 : BaseT(std::move(static_cast<BaseT &>(Arg))) {}
102 BasicTTIImplBase &operator=(const BasicTTIImplBase &RHS) {
103 BaseT::operator=(static_cast<const BaseT &>(RHS));
106 BasicTTIImplBase &operator=(BasicTTIImplBase &&RHS) {
107 BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
111 /// \name Scalar TTI Implementations
114 bool hasBranchDivergence() { return false; }
116 bool isLegalAddImmediate(int64_t imm) {
117 return getTLI()->isLegalAddImmediate(imm);
120 bool isLegalICmpImmediate(int64_t imm) {
121 return getTLI()->isLegalICmpImmediate(imm);
124 bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
125 bool HasBaseReg, int64_t Scale) {
126 TargetLoweringBase::AddrMode AM;
128 AM.BaseOffs = BaseOffset;
129 AM.HasBaseReg = HasBaseReg;
131 return getTLI()->isLegalAddressingMode(AM, Ty);
134 int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
135 bool HasBaseReg, int64_t Scale) {
136 TargetLoweringBase::AddrMode AM;
138 AM.BaseOffs = BaseOffset;
139 AM.HasBaseReg = HasBaseReg;
141 return getTLI()->getScalingFactorCost(AM, Ty);
144 bool isTruncateFree(Type *Ty1, Type *Ty2) {
145 return getTLI()->isTruncateFree(Ty1, Ty2);
148 bool isTypeLegal(Type *Ty) {
149 EVT VT = getTLI()->getValueType(Ty);
150 return getTLI()->isTypeLegal(VT);
153 unsigned getJumpBufAlignment() { return getTLI()->getJumpBufAlignment(); }
155 unsigned getJumpBufSize() { return getTLI()->getJumpBufSize(); }
157 bool shouldBuildLookupTables() {
158 const TargetLoweringBase *TLI = getTLI();
159 return TLI->isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
160 TLI->isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
163 bool haveFastSqrt(Type *Ty) {
164 const TargetLoweringBase *TLI = getTLI();
165 EVT VT = TLI->getValueType(Ty);
166 return TLI->isTypeLegal(VT) &&
167 TLI->isOperationLegalOrCustom(ISD::FSQRT, VT);
170 unsigned getFPOpCost(Type *Ty) {
171 // By default, FP instructions are no more expensive since they are
172 // implemented in HW. Target specific TTI can override this.
173 return TargetTransformInfo::TCC_Basic;
176 void getUnrollingPreferences(Loop *L, TTI::UnrollingPreferences &UP) {
177 // This unrolling functionality is target independent, but to provide some
178 // motivation for its intended use, for x86:
180 // According to the Intel 64 and IA-32 Architectures Optimization Reference
181 // Manual, Intel Core models and later have a loop stream detector (and
182 // associated uop queue) that can benefit from partial unrolling.
183 // The relevant requirements are:
184 // - The loop must have no more than 4 (8 for Nehalem and later) branches
185 // taken, and none of them may be calls.
186 // - The loop can have no more than 18 (28 for Nehalem and later) uops.
188 // According to the Software Optimization Guide for AMD Family 15h
189 // Processors, models 30h-4fh (Steamroller and later) have a loop predictor
190 // and loop buffer which can benefit from partial unrolling.
191 // The relevant requirements are:
192 // - The loop must have fewer than 16 branches
193 // - The loop must have less than 40 uops in all executed loop branches
195 // The number of taken branches in a loop is hard to estimate here, and
196 // benchmarking has revealed that it is better not to be conservative when
197 // estimating the branch count. As a result, we'll ignore the branch limits
198 // until someone finds a case where it matters in practice.
201 const TargetSubtargetInfo *ST = getST();
202 if (PartialUnrollingThreshold.getNumOccurrences() > 0)
203 MaxOps = PartialUnrollingThreshold;
204 else if (ST->getSchedModel().LoopMicroOpBufferSize > 0)
205 MaxOps = ST->getSchedModel().LoopMicroOpBufferSize;
209 // Scan the loop: don't unroll loops with calls.
210 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
214 for (BasicBlock::iterator J = BB->begin(), JE = BB->end(); J != JE; ++J)
215 if (isa<CallInst>(J) || isa<InvokeInst>(J)) {
216 ImmutableCallSite CS(J);
217 if (const Function *F = CS.getCalledFunction()) {
218 if (!static_cast<T *>(this)->isLoweredToCall(F))
226 // Enable runtime and partial unrolling up to the specified size.
227 UP.Partial = UP.Runtime = true;
228 UP.PartialThreshold = UP.PartialOptSizeThreshold = MaxOps;
233 /// \name Vector TTI Implementations
236 unsigned getNumberOfRegisters(bool Vector) { return 1; }
238 unsigned getRegisterBitWidth(bool Vector) { return 32; }
240 unsigned getMaxInterleaveFactor() { return 1; }
242 unsigned getArithmeticInstrCost(
243 unsigned Opcode, Type *Ty,
244 TTI::OperandValueKind Opd1Info = TTI::OK_AnyValue,
245 TTI::OperandValueKind Opd2Info = TTI::OK_AnyValue,
246 TTI::OperandValueProperties Opd1PropInfo = TTI::OP_None,
247 TTI::OperandValueProperties Opd2PropInfo = TTI::OP_None) {
248 // Check if any of the operands are vector operands.
249 const TargetLoweringBase *TLI = getTLI();
250 int ISD = TLI->InstructionOpcodeToISD(Opcode);
251 assert(ISD && "Invalid opcode");
253 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(Ty);
255 bool IsFloat = Ty->getScalarType()->isFloatingPointTy();
256 // Assume that floating point arithmetic operations cost twice as much as
257 // integer operations.
258 unsigned OpCost = (IsFloat ? 2 : 1);
260 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
261 // The operation is legal. Assume it costs 1.
262 // If the type is split to multiple registers, assume that there is some
264 // TODO: Once we have extract/insert subvector cost we need to use them.
266 return LT.first * 2 * OpCost;
267 return LT.first * 1 * OpCost;
270 if (!TLI->isOperationExpand(ISD, LT.second)) {
271 // If the operation is custom lowered then assume
272 // thare the code is twice as expensive.
273 return LT.first * 2 * OpCost;
276 // Else, assume that we need to scalarize this op.
277 if (Ty->isVectorTy()) {
278 unsigned Num = Ty->getVectorNumElements();
279 unsigned Cost = static_cast<T *>(this)
280 ->getArithmeticInstrCost(Opcode, Ty->getScalarType());
281 // return the cost of multiple scalar invocation plus the cost of
283 // and extracting the values.
284 return getScalarizationOverhead(Ty, true, true) + Num * Cost;
287 // We don't know anything about this scalar instruction.
291 unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
293 if (Kind == TTI::SK_Alternate) {
294 return getAltShuffleOverhead(Tp);
299 unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) {
300 const TargetLoweringBase *TLI = getTLI();
301 int ISD = TLI->InstructionOpcodeToISD(Opcode);
302 assert(ISD && "Invalid opcode");
304 std::pair<unsigned, MVT> SrcLT = TLI->getTypeLegalizationCost(Src);
305 std::pair<unsigned, MVT> DstLT = TLI->getTypeLegalizationCost(Dst);
307 // Check for NOOP conversions.
308 if (SrcLT.first == DstLT.first &&
309 SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
311 // Bitcast between types that are legalized to the same type are free.
312 if (Opcode == Instruction::BitCast || Opcode == Instruction::Trunc)
316 if (Opcode == Instruction::Trunc &&
317 TLI->isTruncateFree(SrcLT.second, DstLT.second))
320 if (Opcode == Instruction::ZExt &&
321 TLI->isZExtFree(SrcLT.second, DstLT.second))
324 // If the cast is marked as legal (or promote) then assume low cost.
325 if (SrcLT.first == DstLT.first &&
326 TLI->isOperationLegalOrPromote(ISD, DstLT.second))
329 // Handle scalar conversions.
330 if (!Src->isVectorTy() && !Dst->isVectorTy()) {
332 // Scalar bitcasts are usually free.
333 if (Opcode == Instruction::BitCast)
336 // Just check the op cost. If the operation is legal then assume it costs
338 if (!TLI->isOperationExpand(ISD, DstLT.second))
341 // Assume that illegal scalar instruction are expensive.
345 // Check vector-to-vector casts.
346 if (Dst->isVectorTy() && Src->isVectorTy()) {
348 // If the cast is between same-sized registers, then the check is simple.
349 if (SrcLT.first == DstLT.first &&
350 SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
352 // Assume that Zext is done using AND.
353 if (Opcode == Instruction::ZExt)
356 // Assume that sext is done using SHL and SRA.
357 if (Opcode == Instruction::SExt)
360 // Just check the op cost. If the operation is legal then assume it
362 // 1 and multiply by the type-legalization overhead.
363 if (!TLI->isOperationExpand(ISD, DstLT.second))
364 return SrcLT.first * 1;
367 // If we are converting vectors and the operation is illegal, or
368 // if the vectors are legalized to different types, estimate the
369 // scalarization costs.
370 unsigned Num = Dst->getVectorNumElements();
371 unsigned Cost = static_cast<T *>(this)->getCastInstrCost(
372 Opcode, Dst->getScalarType(), Src->getScalarType());
374 // Return the cost of multiple scalar invocation plus the cost of
375 // inserting and extracting the values.
376 return getScalarizationOverhead(Dst, true, true) + Num * Cost;
379 // We already handled vector-to-vector and scalar-to-scalar conversions.
381 // is where we handle bitcast between vectors and scalars. We need to assume
382 // that the conversion is scalarized in one way or another.
383 if (Opcode == Instruction::BitCast)
384 // Illegal bitcasts are done by storing and loading from a stack slot.
385 return (Src->isVectorTy() ? getScalarizationOverhead(Src, false, true)
387 (Dst->isVectorTy() ? getScalarizationOverhead(Dst, true, false)
390 llvm_unreachable("Unhandled cast");
393 unsigned getCFInstrCost(unsigned Opcode) {
394 // Branches are assumed to be predicted.
398 unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy) {
399 const TargetLoweringBase *TLI = getTLI();
400 int ISD = TLI->InstructionOpcodeToISD(Opcode);
401 assert(ISD && "Invalid opcode");
403 // Selects on vectors are actually vector selects.
404 if (ISD == ISD::SELECT) {
405 assert(CondTy && "CondTy must exist");
406 if (CondTy->isVectorTy())
410 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(ValTy);
412 if (!(ValTy->isVectorTy() && !LT.second.isVector()) &&
413 !TLI->isOperationExpand(ISD, LT.second)) {
414 // The operation is legal. Assume it costs 1. Multiply
415 // by the type-legalization overhead.
419 // Otherwise, assume that the cast is scalarized.
420 if (ValTy->isVectorTy()) {
421 unsigned Num = ValTy->getVectorNumElements();
423 CondTy = CondTy->getScalarType();
424 unsigned Cost = static_cast<T *>(this)->getCmpSelInstrCost(
425 Opcode, ValTy->getScalarType(), CondTy);
427 // Return the cost of multiple scalar invocation plus the cost of
429 // and extracting the values.
430 return getScalarizationOverhead(ValTy, true, false) + Num * Cost;
433 // Unknown scalar opcode.
437 unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
438 std::pair<unsigned, MVT> LT =
439 getTLI()->getTypeLegalizationCost(Val->getScalarType());
444 unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
445 unsigned AddressSpace) {
446 assert(!Src->isVoidTy() && "Invalid type");
447 std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(Src);
449 // Assuming that all loads of legal types cost 1.
450 unsigned Cost = LT.first;
452 if (Src->isVectorTy() &&
453 Src->getPrimitiveSizeInBits() < LT.second.getSizeInBits()) {
454 // This is a vector load that legalizes to a larger type than the vector
455 // itself. Unless the corresponding extending load or truncating store is
456 // legal, then this will scalarize.
457 TargetLowering::LegalizeAction LA = TargetLowering::Expand;
458 EVT MemVT = getTLI()->getValueType(Src, true);
459 if (MemVT.isSimple() && MemVT != MVT::Other) {
460 if (Opcode == Instruction::Store)
461 LA = getTLI()->getTruncStoreAction(LT.second, MemVT.getSimpleVT());
463 LA = getTLI()->getLoadExtAction(ISD::EXTLOAD, LT.second, MemVT);
466 if (LA != TargetLowering::Legal && LA != TargetLowering::Custom) {
467 // This is a vector load/store for some illegal type that is scalarized.
468 // We must account for the cost of building or decomposing the vector.
469 Cost += getScalarizationOverhead(Src, Opcode != Instruction::Store,
470 Opcode == Instruction::Store);
477 unsigned getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
478 ArrayRef<Type *> Tys) {
482 // Assume that we need to scalarize this intrinsic.
483 unsigned ScalarizationCost = 0;
484 unsigned ScalarCalls = 1;
485 if (RetTy->isVectorTy()) {
486 ScalarizationCost = getScalarizationOverhead(RetTy, true, false);
487 ScalarCalls = std::max(ScalarCalls, RetTy->getVectorNumElements());
489 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
490 if (Tys[i]->isVectorTy()) {
491 ScalarizationCost += getScalarizationOverhead(Tys[i], false, true);
492 ScalarCalls = std::max(ScalarCalls, RetTy->getVectorNumElements());
496 return ScalarCalls + ScalarizationCost;
498 // Look for intrinsics that can be lowered directly or turned into a scalar
500 case Intrinsic::sqrt:
512 case Intrinsic::exp2:
518 case Intrinsic::log10:
521 case Intrinsic::log2:
524 case Intrinsic::fabs:
527 case Intrinsic::minnum:
530 case Intrinsic::maxnum:
533 case Intrinsic::copysign:
534 ISD = ISD::FCOPYSIGN;
536 case Intrinsic::floor:
539 case Intrinsic::ceil:
542 case Intrinsic::trunc:
545 case Intrinsic::nearbyint:
546 ISD = ISD::FNEARBYINT;
548 case Intrinsic::rint:
551 case Intrinsic::round:
560 case Intrinsic::fmuladd:
563 // FIXME: We should return 0 whenever getIntrinsicCost == TCC_Free.
564 case Intrinsic::lifetime_start:
565 case Intrinsic::lifetime_end:
567 case Intrinsic::masked_store:
568 return static_cast<T *>(this)
569 ->getMaskedMemoryOpCost(Instruction::Store, Tys[0], 0, 0);
570 case Intrinsic::masked_load:
571 return static_cast<T *>(this)
572 ->getMaskedMemoryOpCost(Instruction::Load, RetTy, 0, 0);
575 const TargetLoweringBase *TLI = getTLI();
576 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(RetTy);
578 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
579 // The operation is legal. Assume it costs 1.
580 // If the type is split to multiple registers, assume that there is some
582 // TODO: Once we have extract/insert subvector cost we need to use them.
588 if (!TLI->isOperationExpand(ISD, LT.second)) {
589 // If the operation is custom lowered then assume
590 // thare the code is twice as expensive.
594 // If we can't lower fmuladd into an FMA estimate the cost as a floating
595 // point mul followed by an add.
596 if (IID == Intrinsic::fmuladd)
597 return static_cast<T *>(this)
598 ->getArithmeticInstrCost(BinaryOperator::FMul, RetTy) +
599 static_cast<T *>(this)
600 ->getArithmeticInstrCost(BinaryOperator::FAdd, RetTy);
602 // Else, assume that we need to scalarize this intrinsic. For math builtins
603 // this will emit a costly libcall, adding call overhead and spills. Make it
605 if (RetTy->isVectorTy()) {
606 unsigned Num = RetTy->getVectorNumElements();
607 unsigned Cost = static_cast<T *>(this)->getIntrinsicInstrCost(
608 IID, RetTy->getScalarType(), Tys);
609 return 10 * Cost * Num;
612 // This is going to be turned into a library call, make it expensive.
616 unsigned getNumberOfParts(Type *Tp) {
617 std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(Tp);
621 unsigned getAddressComputationCost(Type *Ty, bool IsComplex) { return 0; }
623 unsigned getReductionCost(unsigned Opcode, Type *Ty, bool IsPairwise) {
624 assert(Ty->isVectorTy() && "Expect a vector type");
625 unsigned NumVecElts = Ty->getVectorNumElements();
626 unsigned NumReduxLevels = Log2_32(NumVecElts);
629 static_cast<T *>(this)->getArithmeticInstrCost(Opcode, Ty);
630 // Assume the pairwise shuffles add a cost.
631 unsigned ShuffleCost =
632 NumReduxLevels * (IsPairwise + 1) *
633 static_cast<T *>(this)
634 ->getShuffleCost(TTI::SK_ExtractSubvector, Ty, NumVecElts / 2, Ty);
635 return ShuffleCost + ArithCost + getScalarizationOverhead(Ty, false, true);
641 /// \brief Concrete BasicTTIImpl that can be used if no further customization
643 class BasicTTIImpl : public BasicTTIImplBase<BasicTTIImpl> {
644 typedef BasicTTIImplBase<BasicTTIImpl> BaseT;
645 friend class BasicTTIImplBase<BasicTTIImpl>;
647 const TargetSubtargetInfo *ST;
648 const TargetLoweringBase *TLI;
650 const TargetSubtargetInfo *getST() const { return ST; }
651 const TargetLoweringBase *getTLI() const { return TLI; }
654 explicit BasicTTIImpl(const TargetMachine *ST, Function &F);
656 // Provide value semantics. MSVC requires that we spell all of these out.
657 BasicTTIImpl(const BasicTTIImpl &Arg)
658 : BaseT(static_cast<const BaseT &>(Arg)), ST(Arg.ST), TLI(Arg.TLI) {}
659 BasicTTIImpl(BasicTTIImpl &&Arg)
660 : BaseT(std::move(static_cast<BaseT &>(Arg))), ST(std::move(Arg.ST)),
661 TLI(std::move(Arg.TLI)) {}
662 BasicTTIImpl &operator=(const BasicTTIImpl &RHS) {
663 BaseT::operator=(static_cast<const BaseT &>(RHS));
668 BasicTTIImpl &operator=(BasicTTIImpl &&RHS) {
669 BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
670 ST = std::move(RHS.ST);
671 TLI = std::move(RHS.TLI);