LCOV - code coverage report
Current view: top level - include/llvm/CodeGen - BasicTTIImpl.h (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 377 405 93.1 %
Date: 2018-02-23 05:02:05 Functions: 106 248 42.7 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- BasicTTIImpl.h -------------------------------------------*- C++ -*-===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : /// \file
      11             : /// This file provides a helper that implements much of the TTI interface in
      12             : /// terms of the target-independent code generator and TargetLowering
      13             : /// interfaces.
      14             : //
      15             : //===----------------------------------------------------------------------===//
      16             : 
      17             : #ifndef LLVM_CODEGEN_BASICTTIIMPL_H
      18             : #define LLVM_CODEGEN_BASICTTIIMPL_H
      19             : 
      20             : #include "llvm/ADT/APInt.h"
      21             : #include "llvm/ADT/ArrayRef.h"
      22             : #include "llvm/ADT/BitVector.h"
      23             : #include "llvm/ADT/SmallPtrSet.h"
      24             : #include "llvm/ADT/SmallVector.h"
      25             : #include "llvm/Analysis/LoopInfo.h"
      26             : #include "llvm/Analysis/TargetTransformInfo.h"
      27             : #include "llvm/Analysis/TargetTransformInfoImpl.h"
      28             : #include "llvm/CodeGen/ISDOpcodes.h"
      29             : #include "llvm/CodeGen/MachineValueType.h"
      30             : #include "llvm/CodeGen/TargetLowering.h"
      31             : #include "llvm/CodeGen/TargetSubtargetInfo.h"
      32             : #include "llvm/CodeGen/ValueTypes.h"
      33             : #include "llvm/IR/BasicBlock.h"
      34             : #include "llvm/IR/CallSite.h"
      35             : #include "llvm/IR/Constant.h"
      36             : #include "llvm/IR/Constants.h"
      37             : #include "llvm/IR/DataLayout.h"
      38             : #include "llvm/IR/DerivedTypes.h"
      39             : #include "llvm/IR/InstrTypes.h"
      40             : #include "llvm/IR/Instruction.h"
      41             : #include "llvm/IR/Instructions.h"
      42             : #include "llvm/IR/Intrinsics.h"
      43             : #include "llvm/IR/Operator.h"
      44             : #include "llvm/IR/Type.h"
      45             : #include "llvm/IR/Value.h"
      46             : #include "llvm/MC/MCSchedule.h"
      47             : #include "llvm/Support/Casting.h"
      48             : #include "llvm/Support/CommandLine.h"
      49             : #include "llvm/Support/ErrorHandling.h"
      50             : #include "llvm/Support/MathExtras.h"
      51             : #include <algorithm>
      52             : #include <cassert>
      53             : #include <cstdint>
      54             : #include <limits>
      55             : #include <utility>
      56             : 
      57             : namespace llvm {
      58             : 
      59             : class Function;
      60             : class GlobalValue;
      61             : class LLVMContext;
      62             : class ScalarEvolution;
      63             : class SCEV;
      64             : class TargetMachine;
      65             : 
      66             : extern cl::opt<unsigned> PartialUnrollingThreshold;
      67             : 
      68             : /// \brief Base class which can be used to help build a TTI implementation.
      69             : ///
      70             : /// This class provides as much implementation of the TTI interface as is
      71             : /// possible using the target independent parts of the code generator.
      72             : ///
      73             : /// In order to subclass it, your class must implement a getST() method to
      74             : /// return the subtarget, and a getTLI() method to return the target lowering.
      75             : /// We need these methods implemented in the derived class so that this class
      76             : /// doesn't have to duplicate storage for them.
      77             : template <typename T>
      78             : class BasicTTIImplBase : public TargetTransformInfoImplCRTPBase<T> {
      79             : private:
      80             :   using BaseT = TargetTransformInfoImplCRTPBase<T>;
      81             :   using TTI = TargetTransformInfo;
      82             : 
      83             :   /// Estimate a cost of shuffle as a sequence of extract and insert
      84             :   /// operations.
      85           6 :   unsigned getPermuteShuffleOverhead(Type *Ty) {
      86             :     assert(Ty->isVectorTy() && "Can only shuffle vectors");
      87             :     unsigned Cost = 0;
      88             :     // Shuffle cost is equal to the cost of extracting element from its argument
      89             :     // plus the cost of inserting them onto the result vector.
      90             : 
      91             :     // e.g. <4 x float> has a mask of <0,5,2,7> i.e we need to extract from
      92             :     // index 0 of first vector, index 1 of second vector,index 2 of first
      93             :     // vector and finally index 3 of second vector and insert them at index
      94             :     // <0,1,2,3> of result vector.
      95          20 :     for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
      96          14 :       Cost += static_cast<T *>(this)
      97             :                   ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
      98          14 :       Cost += static_cast<T *>(this)
      99             :                   ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
     100             :     }
     101           6 :     return Cost;
     102             :   }
     103             : 
     104             :   /// \brief Local query method delegates up to T which *must* implement this!
     105             :   const TargetSubtargetInfo *getST() const {
     106        5667 :     return static_cast<const T *>(this)->getST();
     107             :   }
     108             : 
     109             :   /// \brief Local query method delegates up to T which *must* implement this!
     110             :   const TargetLoweringBase *getTLI() const {
     111     2469115 :     return static_cast<const T *>(this)->getTLI();
     112             :   }
     113             : 
     114             : protected:
     115             :   explicit BasicTTIImplBase(const TargetMachine *TM, const DataLayout &DL)
     116             :       : BaseT(DL) {}
     117             : 
     118             :   using TargetTransformInfoImplBase::DL;
     119             : 
     120             : public:
     121             :   /// \name Scalar TTI Implementations
     122             :   /// @{
     123         907 :   bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
     124             :                                       unsigned BitWidth, unsigned AddressSpace,
     125             :                                       unsigned Alignment, bool *Fast) const {
     126         907 :     EVT E = EVT::getIntegerVT(Context, BitWidth);
     127         907 :     return getTLI()->allowsMisalignedMemoryAccesses(E, AddressSpace, Alignment, Fast);
     128             :   }
     129             : 
     130             :   bool hasBranchDivergence() { return false; }
     131             : 
     132             :   bool isSourceOfDivergence(const Value *V) { return false; }
     133             : 
     134             :   bool isAlwaysUniform(const Value *V) { return false; }
     135             : 
     136             :   unsigned getFlatAddressSpace() {
     137             :     // Return an invalid address space.
     138             :     return -1;
     139             :   }
     140             : 
     141             :   bool isLegalAddImmediate(int64_t imm) {
     142       17733 :     return getTLI()->isLegalAddImmediate(imm);
     143             :   }
     144             : 
     145             :   bool isLegalICmpImmediate(int64_t imm) {
     146       23055 :     return getTLI()->isLegalICmpImmediate(imm);
     147             :   }
     148             : 
     149             :   bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
     150             :                              bool HasBaseReg, int64_t Scale,
     151             :                              unsigned AddrSpace, Instruction *I = nullptr) {
     152             :     TargetLoweringBase::AddrMode AM;
     153      700677 :     AM.BaseGV = BaseGV;
     154      700677 :     AM.BaseOffs = BaseOffset;
     155      700677 :     AM.HasBaseReg = HasBaseReg;
     156      700677 :     AM.Scale = Scale;
     157      700677 :     return getTLI()->isLegalAddressingMode(DL, AM, Ty, AddrSpace, I);
     158             :   }
     159             : 
     160             :   bool isLSRCostLess(TTI::LSRCost C1, TTI::LSRCost C2) {
     161       11959 :     return TargetTransformInfoImplBase::isLSRCostLess(C1, C2);
     162             :   }
     163             : 
     164             :   int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
     165             :                            bool HasBaseReg, int64_t Scale, unsigned AddrSpace) {
     166             :     TargetLoweringBase::AddrMode AM;
     167       70096 :     AM.BaseGV = BaseGV;
     168       70096 :     AM.BaseOffs = BaseOffset;
     169       70096 :     AM.HasBaseReg = HasBaseReg;
     170       70096 :     AM.Scale = Scale;
     171       70096 :     return getTLI()->getScalingFactorCost(DL, AM, Ty, AddrSpace);
     172             :   }
     173             : 
     174             :   bool isTruncateFree(Type *Ty1, Type *Ty2) {
     175        9675 :     return getTLI()->isTruncateFree(Ty1, Ty2);
     176             :   }
     177             : 
     178             :   bool isProfitableToHoist(Instruction *I) {
     179        3345 :     return getTLI()->isProfitableToHoist(I);
     180             :   }
     181             : 
     182         242 :   bool isTypeLegal(Type *Ty) {
     183         242 :     EVT VT = getTLI()->getValueType(DL, Ty);
     184         484 :     return getTLI()->isTypeLegal(VT);
     185             :   }
     186             : 
     187             :   int getGEPCost(Type *PointeeType, const Value *Ptr,
     188             :                  ArrayRef<const Value *> Operands) {
     189      365917 :     return BaseT::getGEPCost(PointeeType, Ptr, Operands);
     190             :   }
     191             : 
     192       17990 :   int getExtCost(const Instruction *I, const Value *Src) {
     193       17990 :     if (getTLI()->isExtFree(I))
     194             :       return TargetTransformInfo::TCC_Free;
     195             : 
     196       13600 :     if (isa<ZExtInst>(I) || isa<SExtInst>(I))
     197             :       if (const LoadInst *LI = dyn_cast<LoadInst>(Src))
     198        4605 :         if (getTLI()->isExtLoad(LI, I, DL))
     199             :           return TargetTransformInfo::TCC_Free;
     200             : 
     201             :     return TargetTransformInfo::TCC_Basic;
     202             :   }
     203             : 
     204             :   unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
     205             :                             ArrayRef<const Value *> Arguments) {
     206           4 :     return BaseT::getIntrinsicCost(IID, RetTy, Arguments);
     207             :   }
     208             : 
     209      391581 :   unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
     210             :                             ArrayRef<Type *> ParamTys) {
     211      391581 :     if (IID == Intrinsic::cttz) {
     212         599 :       if (getTLI()->isCheapToSpeculateCttz())
     213             :         return TargetTransformInfo::TCC_Basic;
     214             :       return TargetTransformInfo::TCC_Expensive;
     215             :     }
     216             : 
     217      390982 :     if (IID == Intrinsic::ctlz) {
     218         643 :       if (getTLI()->isCheapToSpeculateCtlz())
     219             :         return TargetTransformInfo::TCC_Basic;
     220             :       return TargetTransformInfo::TCC_Expensive;
     221             :     }
     222             : 
     223      390339 :     return BaseT::getIntrinsicCost(IID, RetTy, ParamTys);
     224             :   }
     225             : 
     226        1543 :   unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
     227             :                                             unsigned &JumpTableSize) {
     228             :     /// Try to find the estimated number of clusters. Note that the number of
     229             :     /// clusters identified in this function could be different from the actural
     230             :     /// numbers found in lowering. This function ignore switches that are
     231             :     /// lowered with a mix of jump table / bit test / BTree. This function was
     232             :     /// initially intended to be used when estimating the cost of switch in
     233             :     /// inline cost heuristic, but it's a generic cost model to be used in other
     234             :     /// places (e.g., in loop unrolling).
     235             :     unsigned N = SI.getNumCases();
     236             :     const TargetLoweringBase *TLI = getTLI();
     237             :     const DataLayout &DL = this->getDataLayout();
     238             : 
     239        1543 :     JumpTableSize = 0;
     240        1543 :     bool IsJTAllowed = TLI->areJTsAllowed(SI.getParent()->getParent());
     241             : 
     242             :     // Early exit if both a jump table and bit test are not allowed.
     243        1543 :     if (N < 1 || (!IsJTAllowed && DL.getIndexSizeInBits(0u) < N))
     244             :       return N;
     245             : 
     246             :     APInt MaxCaseVal = SI.case_begin()->getCaseValue()->getValue();
     247             :     APInt MinCaseVal = MaxCaseVal;
     248        6703 :     for (auto CI : SI.cases()) {
     249             :       const APInt &CaseVal = CI.getCaseValue()->getValue();
     250        5160 :       if (CaseVal.sgt(MaxCaseVal))
     251         704 :         MaxCaseVal = CaseVal;
     252        5160 :       if (CaseVal.slt(MinCaseVal))
     253        1745 :         MinCaseVal = CaseVal;
     254             :     }
     255             : 
     256             :     // Check if suitable for a bit test
     257        1543 :     if (N <= DL.getIndexSizeInBits(0u)) {
     258             :       SmallPtrSet<const BasicBlock *, 4> Dests;
     259        6703 :       for (auto I : SI.cases())
     260        5160 :         Dests.insert(I.getCaseSuccessor());
     261             : 
     262        3086 :       if (TLI->isSuitableForBitTests(Dests.size(), N, MinCaseVal, MaxCaseVal,
     263             :                                      DL))
     264             :         return 1;
     265             :     }
     266             : 
     267             :     // Check if suitable for a jump table.
     268        1514 :     if (IsJTAllowed) {
     269        1514 :       if (N < 2 || N < TLI->getMinimumJumpTableEntries())
     270             :         return N;
     271         246 :       uint64_t Range =
     272             :           (MaxCaseVal - MinCaseVal)
     273         492 :               .getLimitedValue(std::numeric_limits<uint64_t>::max() - 1) + 1;
     274             :       // Check whether a range of clusters is dense enough for a jump table
     275         246 :       if (TLI->isSuitableForJumpTable(&SI, N, Range)) {
     276         194 :         JumpTableSize = Range;
     277         194 :         return 1;
     278             :       }
     279             :     }
     280             :     return N;
     281             :   }
     282             : 
     283           0 :   unsigned getJumpBufAlignment() { return getTLI()->getJumpBufAlignment(); }
     284             : 
     285           0 :   unsigned getJumpBufSize() { return getTLI()->getJumpBufSize(); }
     286             : 
     287             :   bool shouldBuildLookupTables() {
     288             :     const TargetLoweringBase *TLI = getTLI();
     289             :     return TLI->isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
     290             :            TLI->isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
     291             :   }
     292             : 
     293          54 :   bool haveFastSqrt(Type *Ty) {
     294             :     const TargetLoweringBase *TLI = getTLI();
     295          54 :     EVT VT = TLI->getValueType(DL, Ty);
     296             :     return TLI->isTypeLegal(VT) &&
     297          54 :            TLI->isOperationLegalOrCustom(ISD::FSQRT, VT);
     298             :   }
     299             : 
     300             :   bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) {
     301             :     return true;
     302             :   }
     303             : 
     304         703 :   unsigned getFPOpCost(Type *Ty) {
     305             :     // Check whether FADD is available, as a proxy for floating-point in
     306             :     // general.
     307             :     const TargetLoweringBase *TLI = getTLI();
     308         703 :     EVT VT = TLI->getValueType(DL, Ty);
     309         703 :     if (TLI->isOperationLegalOrCustomOrPromote(ISD::FADD, VT))
     310             :       return TargetTransformInfo::TCC_Basic;
     311          60 :     return TargetTransformInfo::TCC_Expensive;
     312             :   }
     313             : 
     314     1352678 :   unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) {
     315             :     const TargetLoweringBase *TLI = getTLI();
     316     1352678 :     switch (Opcode) {
     317             :     default: break;
     318        7368 :     case Instruction::Trunc:
     319        7368 :       if (TLI->isTruncateFree(OpTy, Ty))
     320             :         return TargetTransformInfo::TCC_Free;
     321          65 :       return TargetTransformInfo::TCC_Basic;
     322           0 :     case Instruction::ZExt:
     323           0 :       if (TLI->isZExtFree(OpTy, Ty))
     324             :         return TargetTransformInfo::TCC_Free;
     325           0 :       return TargetTransformInfo::TCC_Basic;
     326             :     }
     327             : 
     328     1345310 :     return BaseT::getOperationCost(Opcode, Ty, OpTy);
     329             :   }
     330             : 
     331             :   unsigned getInliningThresholdMultiplier() { return 1; }
     332             : 
     333        5667 :   void getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
     334             :                                TTI::UnrollingPreferences &UP) {
     335             :     // This unrolling functionality is target independent, but to provide some
     336             :     // motivation for its intended use, for x86:
     337             : 
     338             :     // According to the Intel 64 and IA-32 Architectures Optimization Reference
     339             :     // Manual, Intel Core models and later have a loop stream detector (and
     340             :     // associated uop queue) that can benefit from partial unrolling.
     341             :     // The relevant requirements are:
     342             :     //  - The loop must have no more than 4 (8 for Nehalem and later) branches
     343             :     //    taken, and none of them may be calls.
     344             :     //  - The loop can have no more than 18 (28 for Nehalem and later) uops.
     345             : 
     346             :     // According to the Software Optimization Guide for AMD Family 15h
     347             :     // Processors, models 30h-4fh (Steamroller and later) have a loop predictor
     348             :     // and loop buffer which can benefit from partial unrolling.
     349             :     // The relevant requirements are:
     350             :     //  - The loop must have fewer than 16 branches
     351             :     //  - The loop must have less than 40 uops in all executed loop branches
     352             : 
     353             :     // The number of taken branches in a loop is hard to estimate here, and
     354             :     // benchmarking has revealed that it is better not to be conservative when
     355             :     // estimating the branch count. As a result, we'll ignore the branch limits
     356             :     // until someone finds a case where it matters in practice.
     357             : 
     358             :     unsigned MaxOps;
     359             :     const TargetSubtargetInfo *ST = getST();
     360        5667 :     if (PartialUnrollingThreshold.getNumOccurrences() > 0)
     361             :       MaxOps = PartialUnrollingThreshold;
     362        5667 :     else if (ST->getSchedModel().LoopMicroOpBufferSize > 0)
     363             :       MaxOps = ST->getSchedModel().LoopMicroOpBufferSize;
     364             :     else
     365             :       return;
     366             : 
     367             :     // Scan the loop: don't unroll loops with calls.
     368       16769 :     for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
     369             :          ++I) {
     370        8704 :       BasicBlock *BB = *I;
     371             : 
     372      117065 :       for (BasicBlock::iterator J = BB->begin(), JE = BB->end(); J != JE; ++J)
     373      110580 :         if (isa<CallInst>(J) || isa<InvokeInst>(J)) {
     374             :           ImmutableCallSite CS(&*J);
     375             :           if (const Function *F = CS.getCalledFunction()) {
     376       27078 :             if (!static_cast<T *>(this)->isLoweredToCall(F))
     377             :               continue;
     378             :           }
     379             : 
     380             :           return;
     381             :         }
     382             :     }
     383             : 
     384             :     // Enable runtime and partial unrolling up to the specified size.
     385             :     // Enable using trip count upper bound to unroll loops.
     386        1580 :     UP.Partial = UP.Runtime = UP.UpperBound = true;
     387        1580 :     UP.PartialThreshold = MaxOps;
     388             : 
     389             :     // Avoid unrolling when optimizing for size.
     390        1580 :     UP.OptSizeThreshold = 0;
     391        1580 :     UP.PartialOptSizeThreshold = 0;
     392             : 
     393             :     // Set number of instructions optimized when "back edge"
     394             :     // becomes "fall through" to default value of 2.
     395        1580 :     UP.BEInsns = 2;
     396             :   }
     397             : 
     398             :   int getInstructionLatency(const Instruction *I) {
     399          11 :     if (isa<LoadInst>(I))
     400             :       return getST()->getSchedModel().DefaultLoadLatency;
     401             : 
     402          10 :     return BaseT::getInstructionLatency(I);
     403             :   }
     404             : 
     405             :   /// @}
     406             : 
     407             :   /// \name Vector TTI Implementations
     408             :   /// @{
     409             : 
     410         661 :   unsigned getNumberOfRegisters(bool Vector) { return Vector ? 0 : 1; }
     411             : 
     412             :   unsigned getRegisterBitWidth(bool Vector) const { return 32; }
     413             : 
     414             :   /// Estimate the overhead of scalarizing an instruction. Insert and Extract
     415             :   /// are set if the result needs to be inserted and/or extracted from vectors.
     416        8506 :   unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) {
     417             :     assert(Ty->isVectorTy() && "Can only scalarize vectors");
     418             :     unsigned Cost = 0;
     419             : 
     420       71305 :     for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
     421       62799 :       if (Insert)
     422       36856 :         Cost += static_cast<T *>(this)
     423             :                     ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
     424       62799 :       if (Extract)
     425       28330 :         Cost += static_cast<T *>(this)
     426             :                     ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
     427             :     }
     428             : 
     429        8506 :     return Cost;
     430             :   }
     431             : 
     432             :   /// Estimate the overhead of scalarizing an instructions unique
     433             :   /// non-constant operands. The types of the arguments are ordinarily
     434             :   /// scalar, in which case the costs are multiplied with VF.
     435        2323 :   unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
     436             :                                             unsigned VF) {
     437             :     unsigned Cost = 0;
     438             :     SmallPtrSet<const Value*, 4> UniqueOperands;
     439        9337 :     for (const Value *A : Args) {
     440        4591 :       if (!isa<Constant>(A) && UniqueOperands.insert(A).second) {
     441             :         Type *VecTy = nullptr;
     442        4846 :         if (A->getType()->isVectorTy()) {
     443             :           VecTy = A->getType();
     444             :           // If A is a vector operand, VF should be 1 or correspond to A.
     445             :           assert((VF == 1 || VF == VecTy->getVectorNumElements()) &&
     446             :                  "Vector argument does not match VF");
     447             :         }
     448             :         else
     449        1773 :           VecTy = VectorType::get(A->getType(), VF);
     450             : 
     451        2423 :         Cost += getScalarizationOverhead(VecTy, false, true);
     452             :       }
     453             :     }
     454             : 
     455        2323 :     return Cost;
     456             :   }
     457             : 
     458         323 :   unsigned getScalarizationOverhead(Type *VecTy, ArrayRef<const Value *> Args) {
     459             :     assert(VecTy->isVectorTy());
     460             : 
     461             :     unsigned Cost = 0;
     462             : 
     463         323 :     Cost += getScalarizationOverhead(VecTy, true, false);
     464         323 :     if (!Args.empty())
     465          84 :       Cost += getOperandsScalarizationOverhead(Args,
     466             :                                                VecTy->getVectorNumElements());
     467             :     else
     468             :       // When no information on arguments is provided, we add the cost
     469             :       // associated with one argument as a heuristic.
     470         239 :       Cost += getScalarizationOverhead(VecTy, false, true);
     471             : 
     472         323 :     return Cost;
     473             :   }
     474             : 
     475             :   unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
     476             : 
     477      145269 :   unsigned getArithmeticInstrCost(
     478             :       unsigned Opcode, Type *Ty,
     479             :       TTI::OperandValueKind Opd1Info = TTI::OK_AnyValue,
     480             :       TTI::OperandValueKind Opd2Info = TTI::OK_AnyValue,
     481             :       TTI::OperandValueProperties Opd1PropInfo = TTI::OP_None,
     482             :       TTI::OperandValueProperties Opd2PropInfo = TTI::OP_None,
     483             :       ArrayRef<const Value *> Args = ArrayRef<const Value *>()) {
     484             :     // Check if any of the operands are vector operands.
     485             :     const TargetLoweringBase *TLI = getTLI();
     486      145269 :     int ISD = TLI->InstructionOpcodeToISD(Opcode);
     487             :     assert(ISD && "Invalid opcode");
     488             : 
     489      290538 :     std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
     490             : 
     491             :     bool IsFloat = Ty->isFPOrFPVectorTy();
     492             :     // Assume that floating point arithmetic operations cost twice as much as
     493             :     // integer operations.
     494             :     unsigned OpCost = (IsFloat ? 2 : 1);
     495             : 
     496      145269 :     if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
     497             :       // The operation is legal. Assume it costs 1.
     498             :       // TODO: Once we have extract/insert subvector cost we need to use them.
     499      144471 :       return LT.first * OpCost;
     500             :     }
     501             : 
     502             :     if (!TLI->isOperationExpand(ISD, LT.second)) {
     503             :       // If the operation is custom lowered, then assume that the code is twice
     504             :       // as expensive.
     505          30 :       return LT.first * 2 * OpCost;
     506             :     }
     507             : 
     508             :     // Else, assume that we need to scalarize this op.
     509             :     // TODO: If one of the types get legalized by splitting, handle this
     510             :     // similarly to what getCastInstrCost() does.
     511         768 :     if (Ty->isVectorTy()) {
     512             :       unsigned Num = Ty->getVectorNumElements();
     513         614 :       unsigned Cost = static_cast<T *>(this)
     514             :                           ->getArithmeticInstrCost(Opcode, Ty->getScalarType());
     515             :       // Return the cost of multiple scalar invocation plus the cost of
     516             :       // inserting and extracting the values.
     517         307 :       return getScalarizationOverhead(Ty, Args) + Num * Cost;
     518             :     }
     519             : 
     520             :     // We don't know anything about this scalar instruction.
     521             :     return OpCost;
     522             :   }
     523             : 
     524             :   unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
     525             :                           Type *SubTp) {
     526        1767 :     if (Kind == TTI::SK_Alternate || Kind == TTI::SK_PermuteTwoSrc ||
     527             :         Kind == TTI::SK_PermuteSingleSrc) {
     528           6 :       return getPermuteShuffleOverhead(Tp);
     529             :     }
     530             :     return 1;
     531             :   }
     532             : 
     533        3806 :   unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
     534             :                             const Instruction *I = nullptr) {
     535             :     const TargetLoweringBase *TLI = getTLI();
     536        3810 :     int ISD = TLI->InstructionOpcodeToISD(Opcode);
     537             :     assert(ISD && "Invalid opcode");
     538        7620 :     std::pair<unsigned, MVT> SrcLT = TLI->getTypeLegalizationCost(DL, Src);
     539        7620 :     std::pair<unsigned, MVT> DstLT = TLI->getTypeLegalizationCost(DL, Dst);
     540             : 
     541             :     // Check for NOOP conversions.
     542        7189 :     if (SrcLT.first == DstLT.first &&
     543        3379 :         SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
     544             : 
     545             :       // Bitcast between types that are legalized to the same type are free.
     546        1579 :       if (Opcode == Instruction::BitCast || Opcode == Instruction::Trunc)
     547             :         return 0;
     548             :     }
     549             : 
     550        4004 :     if (Opcode == Instruction::Trunc &&
     551        4365 :         TLI->isTruncateFree(SrcLT.second, DstLT.second))
     552             :       return 0;
     553             : 
     554        3596 :     if (Opcode == Instruction::ZExt &&
     555        3866 :         TLI->isZExtFree(SrcLT.second, DstLT.second))
     556             :       return 0;
     557             : 
     558        3315 :     if (Opcode == Instruction::AddrSpaceCast &&
     559          24 :         TLI->isNoopAddrSpaceCast(Src->getPointerAddressSpace(),
     560             :                                  Dst->getPointerAddressSpace()))
     561             :       return 0;
     562             : 
     563             :     // If this is a zext/sext of a load, return 0 if the corresponding
     564             :     // extending load exists on target.
     565        3780 :     if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
     566        3658 :         I && isa<LoadInst>(I->getOperand(0))) {
     567         272 :         EVT ExtVT = EVT::getEVT(Dst);
     568         272 :         EVT LoadVT = EVT::getEVT(Src);
     569         272 :         unsigned LType =
     570             :           ((Opcode == Instruction::ZExt) ? ISD::ZEXTLOAD : ISD::SEXTLOAD);
     571         544 :         if (TLI->isLoadExtLegal(LType, ExtVT, LoadVT))
     572         248 :           return 0;
     573             :     }
     574             : 
     575             :     // If the cast is marked as legal (or promote) then assume low cost.
     576        5677 :     if (SrcLT.first == DstLT.first &&
     577        2625 :         TLI->isOperationLegalOrPromote(ISD, DstLT.second))
     578             :       return 1;
     579             : 
     580             :     // Handle scalar conversions.
     581        2054 :     if (!Src->isVectorTy() && !Dst->isVectorTy()) {
     582             :       // Scalar bitcasts are usually free.
     583         501 :       if (Opcode == Instruction::BitCast)
     584             :         return 0;
     585             : 
     586             :       // Just check the op cost. If the operation is legal then assume it costs
     587             :       // 1.
     588         499 :       if (!TLI->isOperationExpand(ISD, DstLT.second))
     589             :         return 1;
     590             : 
     591             :       // Assume that illegal scalar instruction are expensive.
     592             :       return 4;
     593             :     }
     594             : 
     595             :     // Check vector-to-vector casts.
     596        2104 :     if (Dst->isVectorTy() && Src->isVectorTy()) {
     597             :       // If the cast is between same-sized registers, then the check is simple.
     598        1701 :       if (SrcLT.first == DstLT.first &&
     599         649 :           SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
     600             : 
     601             :         // Assume that Zext is done using AND.
     602         474 :         if (Opcode == Instruction::ZExt)
     603             :           return 1;
     604             : 
     605             :         // Assume that sext is done using SHL and SRA.
     606         455 :         if (Opcode == Instruction::SExt)
     607             :           return 2;
     608             : 
     609             :         // Just check the op cost. If the operation is legal then assume it
     610             :         // costs
     611             :         // 1 and multiply by the type-legalization overhead.
     612         435 :         if (!TLI->isOperationExpand(ISD, DstLT.second))
     613             :           return SrcLT.first * 1;
     614             :       }
     615             : 
     616             :       // If we are legalizing by splitting, query the concrete TTI for the cost
     617             :       // of casting the original vector twice. We also need to factor int the
     618             :       // cost of the split itself. Count that as 1, to be consistent with
     619             :       // TLI->getTypeLegalizationCost().
     620        1001 :       if ((TLI->getTypeAction(Src->getContext(), TLI->getValueType(DL, Src)) ==
     621        1673 :            TargetLowering::TypeSplitVector) ||
     622         672 :           (TLI->getTypeAction(Dst->getContext(), TLI->getValueType(DL, Dst)) ==
     623             :            TargetLowering::TypeSplitVector)) {
     624         924 :         Type *SplitDst = VectorType::get(Dst->getVectorElementType(),
     625             :                                          Dst->getVectorNumElements() / 2);
     626         924 :         Type *SplitSrc = VectorType::get(Src->getVectorElementType(),
     627             :                                          Src->getVectorNumElements() / 2);
     628             :         T *TTI = static_cast<T *>(this);
     629           0 :         return TTI->getVectorSplitCost() +
     630         462 :                (2 * TTI->getCastInstrCost(Opcode, SplitDst, SplitSrc, I));
     631             :       }
     632             : 
     633             :       // In other cases where the source or destination are illegal, assume
     634             :       // the operation will get scalarized.
     635             :       unsigned Num = Dst->getVectorNumElements();
     636         541 :       unsigned Cost = static_cast<T *>(this)->getCastInstrCost(
     637             :           Opcode, Dst->getScalarType(), Src->getScalarType(), I);
     638             : 
     639             :       // Return the cost of multiple scalar invocation plus the cost of
     640             :       // inserting and extracting the values.
     641         539 :       return getScalarizationOverhead(Dst, true, true) + Num * Cost;
     642             :     }
     643             : 
     644             :     // We already handled vector-to-vector and scalar-to-scalar conversions.
     645             :     // This
     646             :     // is where we handle bitcast between vectors and scalars. We need to assume
     647             :     //  that the conversion is scalarized in one way or another.
     648           0 :     if (Opcode == Instruction::BitCast)
     649             :       // Illegal bitcasts are done by storing and loading from a stack slot.
     650           0 :       return (Src->isVectorTy() ? getScalarizationOverhead(Src, false, true)
     651             :                                 : 0) +
     652           0 :              (Dst->isVectorTy() ? getScalarizationOverhead(Dst, true, false)
     653           0 :                                 : 0);
     654             : 
     655           0 :     llvm_unreachable("Unhandled cast");
     656             :   }
     657             : 
     658           4 :   unsigned getExtractWithExtendCost(unsigned Opcode, Type *Dst,
     659             :                                     VectorType *VecTy, unsigned Index) {
     660             :     return static_cast<T *>(this)->getVectorInstrCost(
     661           4 :                Instruction::ExtractElement, VecTy, Index) +
     662             :            static_cast<T *>(this)->getCastInstrCost(Opcode, Dst,
     663           4 :                                                     VecTy->getElementType());
     664             :   }
     665             : 
     666             :   unsigned getCFInstrCost(unsigned Opcode) {
     667             :     // Branches are assumed to be predicted.
     668             :     return 0;
     669             :   }
     670             : 
     671        8212 :   unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
     672             :                               const Instruction *I) {
     673             :     const TargetLoweringBase *TLI = getTLI();
     674        8212 :     int ISD = TLI->InstructionOpcodeToISD(Opcode);
     675             :     assert(ISD && "Invalid opcode");
     676             : 
     677             :     // Selects on vectors are actually vector selects.
     678        8212 :     if (ISD == ISD::SELECT) {
     679             :       assert(CondTy && "CondTy must exist");
     680        3169 :       if (CondTy->isVectorTy())
     681             :         ISD = ISD::VSELECT;
     682             :     }
     683       16424 :     std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
     684             : 
     685       11700 :     if (!(ValTy->isVectorTy() && !LT.second.isVector()) &&
     686        8211 :         !TLI->isOperationExpand(ISD, LT.second)) {
     687             :       // The operation is legal. Assume it costs 1. Multiply
     688             :       // by the type-legalization overhead.
     689        6515 :       return LT.first * 1;
     690             :     }
     691             : 
     692             :     // Otherwise, assume that the cast is scalarized.
     693             :     // TODO: If one of the types get legalized by splitting, handle this
     694             :     // similarly to what getCastInstrCost() does.
     695        1697 :     if (ValTy->isVectorTy()) {
     696             :       unsigned Num = ValTy->getVectorNumElements();
     697        1658 :       if (CondTy)
     698             :         CondTy = CondTy->getScalarType();
     699        1658 :       unsigned Cost = static_cast<T *>(this)->getCmpSelInstrCost(
     700             :           Opcode, ValTy->getScalarType(), CondTy, I);
     701             : 
     702             :       // Return the cost of multiple scalar invocation plus the cost of
     703             :       // inserting and extracting the values.
     704        1658 :       return getScalarizationOverhead(ValTy, true, false) + Num * Cost;
     705             :     }
     706             : 
     707             :     // Unknown scalar opcode.
     708             :     return 1;
     709             :   }
     710             : 
     711             :   unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
     712      183158 :     std::pair<unsigned, MVT> LT =
     713             :         getTLI()->getTypeLegalizationCost(DL, Val->getScalarType());
     714             : 
     715             :     return LT.first;
     716             :   }
     717             : 
     718         799 :   unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
     719             :                        unsigned AddressSpace, const Instruction *I = nullptr) {
     720             :     assert(!Src->isVoidTy() && "Invalid type");
     721        1598 :     std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(DL, Src);
     722             : 
     723             :     // Assuming that all loads of legal types cost 1.
     724             :     unsigned Cost = LT.first;
     725             : 
     726        1260 :     if (Src->isVectorTy() &&
     727         461 :         Src->getPrimitiveSizeInBits() < LT.second.getSizeInBits()) {
     728             :       // This is a vector load that legalizes to a larger type than the vector
     729             :       // itself. Unless the corresponding extending load or truncating store is
     730             :       // legal, then this will scalarize.
     731             :       TargetLowering::LegalizeAction LA = TargetLowering::Expand;
     732          57 :       EVT MemVT = getTLI()->getValueType(DL, Src);
     733          57 :       if (Opcode == Instruction::Store)
     734             :         LA = getTLI()->getTruncStoreAction(LT.second, MemVT);
     735             :       else
     736             :         LA = getTLI()->getLoadExtAction(ISD::EXTLOAD, LT.second, MemVT);
     737             : 
     738          57 :       if (LA != TargetLowering::Legal && LA != TargetLowering::Custom) {
     739             :         // This is a vector load/store for some illegal type that is scalarized.
     740             :         // We must account for the cost of building or decomposing the vector.
     741          52 :         Cost += getScalarizationOverhead(Src, Opcode != Instruction::Store,
     742             :                                          Opcode == Instruction::Store);
     743             :       }
     744             :     }
     745             : 
     746         799 :     return Cost;
     747             :   }
     748             : 
     749           9 :   unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
     750             :                                       unsigned Factor,
     751             :                                       ArrayRef<unsigned> Indices,
     752             :                                       unsigned Alignment,
     753             :                                       unsigned AddressSpace) {
     754             :     VectorType *VT = dyn_cast<VectorType>(VecTy);
     755             :     assert(VT && "Expect a vector type for interleaved memory op");
     756             : 
     757           9 :     unsigned NumElts = VT->getNumElements();
     758             :     assert(Factor > 1 && NumElts % Factor == 0 && "Invalid interleave factor");
     759             : 
     760           9 :     unsigned NumSubElts = NumElts / Factor;
     761           9 :     VectorType *SubVT = VectorType::get(VT->getElementType(), NumSubElts);
     762             : 
     763             :     // Firstly, the cost of load/store operation.
     764           9 :     unsigned Cost = static_cast<T *>(this)->getMemoryOpCost(
     765             :         Opcode, VecTy, Alignment, AddressSpace);
     766             : 
     767             :     // Legalize the vector type, and get the legalized and unlegalized type
     768             :     // sizes.
     769           9 :     MVT VecTyLT = getTLI()->getTypeLegalizationCost(DL, VecTy).second;
     770           9 :     unsigned VecTySize =
     771             :         static_cast<T *>(this)->getDataLayout().getTypeStoreSize(VecTy);
     772             :     unsigned VecTyLTSize = VecTyLT.getStoreSize();
     773             : 
     774             :     // Return the ceiling of dividing A by B.
     775           5 :     auto ceil = [](unsigned A, unsigned B) { return (A + B - 1) / B; };
     776             : 
     777             :     // Scale the cost of the memory operation by the fraction of legalized
     778             :     // instructions that will actually be used. We shouldn't account for the
     779             :     // cost of dead instructions since they will be removed.
     780             :     //
     781             :     // E.g., An interleaved load of factor 8:
     782             :     //       %vec = load <16 x i64>, <16 x i64>* %ptr
     783             :     //       %v0 = shufflevector %vec, undef, <0, 8>
     784             :     //
     785             :     // If <16 x i64> is legalized to 8 v2i64 loads, only 2 of the loads will be
     786             :     // used (those corresponding to elements [0:1] and [8:9] of the unlegalized
     787             :     // type). The other loads are unused.
     788             :     //
     789             :     // We only scale the cost of loads since interleaved store groups aren't
     790             :     // allowed to have gaps.
     791           9 :     if (Opcode == Instruction::Load && VecTySize > VecTyLTSize) {
     792             :       // The number of loads of a legal type it will take to represent a load
     793             :       // of the unlegalized vector type.
     794             :       unsigned NumLegalInsts = ceil(VecTySize, VecTyLTSize);
     795             : 
     796             :       // The number of elements of the unlegalized type that correspond to a
     797             :       // single legal instruction.
     798             :       unsigned NumEltsPerLegalInst = ceil(NumElts, NumLegalInsts);
     799             : 
     800             :       // Determine which legal instructions will be used.
     801           5 :       BitVector UsedInsts(NumLegalInsts, false);
     802          23 :       for (unsigned Index : Indices)
     803          61 :         for (unsigned Elt = 0; Elt < NumSubElts; ++Elt)
     804          26 :           UsedInsts.set((Index + Elt * Factor) / NumEltsPerLegalInst);
     805             : 
     806             :       // Scale the cost of the load by the fraction of legal instructions that
     807             :       // will be used.
     808           5 :       Cost *= UsedInsts.count() / NumLegalInsts;
     809             :     }
     810             : 
     811             :     // Then plus the cost of interleave operation.
     812           9 :     if (Opcode == Instruction::Load) {
     813             :       // The interleave cost is similar to extract sub vectors' elements
     814             :       // from the wide vector, and insert them into sub vectors.
     815             :       //
     816             :       // E.g. An interleaved load of factor 2 (with one member of index 0):
     817             :       //      %vec = load <8 x i32>, <8 x i32>* %ptr
     818             :       //      %v0 = shuffle %vec, undef, <0, 2, 4, 6>         ; Index 0
     819             :       // The cost is estimated as extract elements at 0, 2, 4, 6 from the
     820             :       // <8 x i32> vector and insert them into a <4 x i32> vector.
     821             : 
     822             :       assert(Indices.size() <= Factor &&
     823             :              "Interleaved memory op has too many members");
     824             : 
     825          33 :       for (unsigned Index : Indices) {
     826             :         assert(Index < Factor && "Invalid index for interleaved memory op");
     827             : 
     828             :         // Extract elements from loaded vector for each sub vector.
     829          81 :         for (unsigned i = 0; i < NumSubElts; i++)
     830          34 :           Cost += static_cast<T *>(this)->getVectorInstrCost(
     831          34 :               Instruction::ExtractElement, VT, Index + i * Factor);
     832             :       }
     833             : 
     834             :       unsigned InsSubCost = 0;
     835          43 :       for (unsigned i = 0; i < NumSubElts; i++)
     836          18 :         InsSubCost += static_cast<T *>(this)->getVectorInstrCost(
     837             :             Instruction::InsertElement, SubVT, i);
     838             : 
     839           7 :       Cost += Indices.size() * InsSubCost;
     840             :     } else {
     841             :       // The interleave cost is extract all elements from sub vectors, and
     842             :       // insert them into the wide vector.
     843             :       //
     844             :       // E.g. An interleaved store of factor 2:
     845             :       //      %v0_v1 = shuffle %v0, %v1, <0, 4, 1, 5, 2, 6, 3, 7>
     846             :       //      store <8 x i32> %interleaved.vec, <8 x i32>* %ptr
     847             :       // The cost is estimated as extract all elements from both <4 x i32>
     848             :       // vectors and insert into the <8 x i32> vector.
     849             : 
     850             :       unsigned ExtSubCost = 0;
     851          14 :       for (unsigned i = 0; i < NumSubElts; i++)
     852           6 :         ExtSubCost += static_cast<T *>(this)->getVectorInstrCost(
     853             :             Instruction::ExtractElement, SubVT, i);
     854           2 :       Cost += ExtSubCost * Factor;
     855             : 
     856          38 :       for (unsigned i = 0; i < NumElts; i++)
     857          18 :         Cost += static_cast<T *>(this)
     858             :                     ->getVectorInstrCost(Instruction::InsertElement, VT, i);
     859             :     }
     860             : 
     861           9 :     return Cost;
     862             :   }
     863             : 
     864             :   /// Get intrinsic cost based on arguments.
     865        2156 :   unsigned getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
     866             :                                  ArrayRef<Value *> Args, FastMathFlags FMF,
     867             :                                  unsigned VF = 1) {
     868        2156 :     unsigned RetVF = (RetTy->isVectorTy() ? RetTy->getVectorNumElements() : 1);
     869             :     assert((RetVF == 1 || VF == 1) && "VF > 1 and RetVF is a vector type");
     870             : 
     871        2156 :     switch (IID) {
     872             :     default: {
     873             :       // Assume that we need to scalarize this intrinsic.
     874             :       SmallVector<Type *, 4> Types;
     875        8687 :       for (Value *Op : Args) {
     876        3290 :         Type *OpTy = Op->getType();
     877             :         assert(VF == 1 || !OpTy->isVectorTy());
     878        3290 :         Types.push_back(VF == 1 ? OpTy : VectorType::get(OpTy, VF));
     879             :       }
     880             : 
     881        3166 :       if (VF > 1 && !RetTy->isVoidTy())
     882        1055 :         RetTy = VectorType::get(RetTy, VF);
     883             : 
     884             :       // Compute the scalarization overhead based on Args for a vector
     885             :       // intrinsic. A vectorizer will pass a scalar RetTy and VF > 1, while
     886             :       // CostModel will pass a vector RetTy and VF is 1.
     887             :       unsigned ScalarizationCost = std::numeric_limits<unsigned>::max();
     888        2107 :       if (RetVF > 1 || VF > 1) {
     889             :         ScalarizationCost = 0;
     890        1837 :         if (!RetTy->isVoidTy())
     891        1833 :           ScalarizationCost += getScalarizationOverhead(RetTy, true, false);
     892        1837 :         ScalarizationCost += getOperandsScalarizationOverhead(Args, VF);
     893             :       }
     894             : 
     895             :       return static_cast<T *>(this)->
     896        2140 :         getIntrinsicInstrCost(IID, RetTy, Types, FMF, ScalarizationCost);
     897             :     }
     898          12 :     case Intrinsic::masked_scatter: {
     899             :       assert(VF == 1 && "Can't vectorize types here.");
     900          12 :       Value *Mask = Args[3];
     901          12 :       bool VarMask = !isa<Constant>(Mask);
     902          24 :       unsigned Alignment = cast<ConstantInt>(Args[2])->getZExtValue();
     903             :       return
     904             :         static_cast<T *>(this)->getGatherScatterOpCost(Instruction::Store,
     905             :                                                        Args[0]->getType(),
     906             :                                                        Args[1], VarMask,
     907          12 :                                                        Alignment);
     908             :     }
     909          37 :     case Intrinsic::masked_gather: {
     910             :       assert(VF == 1 && "Can't vectorize types here.");
     911          37 :       Value *Mask = Args[2];
     912          37 :       bool VarMask = !isa<Constant>(Mask);
     913          74 :       unsigned Alignment = cast<ConstantInt>(Args[1])->getZExtValue();
     914             :       return
     915             :         static_cast<T *>(this)->getGatherScatterOpCost(Instruction::Load,
     916             :                                                        RetTy, Args[0], VarMask,
     917          37 :                                                        Alignment);
     918             :     }
     919             :     }
     920             :   }
     921             : 
     922             :   /// Get intrinsic cost based on argument types.
     923             :   /// If ScalarizationCostPassed is std::numeric_limits<unsigned>::max(), the
     924             :   /// cost of scalarizing the arguments and the return value will be computed
     925             :   /// based on types.
     926        2186 :   unsigned getIntrinsicInstrCost(
     927             :       Intrinsic::ID IID, Type *RetTy, ArrayRef<Type *> Tys, FastMathFlags FMF,
     928             :       unsigned ScalarizationCostPassed = std::numeric_limits<unsigned>::max()) {
     929             :     SmallVector<unsigned, 2> ISDs;
     930             :     unsigned SingleCallCost = 10; // Library call cost. Make it expensive.
     931        2186 :     switch (IID) {
     932         393 :     default: {
     933             :       // Assume that we need to scalarize this intrinsic.
     934             :       unsigned ScalarizationCost = ScalarizationCostPassed;
     935         393 :       unsigned ScalarCalls = 1;
     936             :       Type *ScalarRetTy = RetTy;
     937         393 :       if (RetTy->isVectorTy()) {
     938           7 :         if (ScalarizationCostPassed == std::numeric_limits<unsigned>::max())
     939           0 :           ScalarizationCost = getScalarizationOverhead(RetTy, true, false);
     940          14 :         ScalarCalls = std::max(ScalarCalls, RetTy->getVectorNumElements());
     941             :         ScalarRetTy = RetTy->getScalarType();
     942             :       }
     943             :       SmallVector<Type *, 4> ScalarTys;
     944        1142 :       for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
     945        1498 :         Type *Ty = Tys[i];
     946         749 :         if (Ty->isVectorTy()) {
     947           9 :           if (ScalarizationCostPassed == std::numeric_limits<unsigned>::max())
     948           0 :             ScalarizationCost += getScalarizationOverhead(Ty, false, true);
     949          27 :           ScalarCalls = std::max(ScalarCalls, Ty->getVectorNumElements());
     950           9 :           Ty = Ty->getScalarType();
     951             :         }
     952         749 :         ScalarTys.push_back(Ty);
     953             :       }
     954         393 :       if (ScalarCalls == 1)
     955             :         return 1; // Return cost of a scalar intrinsic. Assume it to be cheap.
     956             : 
     957          12 :       unsigned ScalarCost = static_cast<T *>(this)->getIntrinsicInstrCost(
     958             :           IID, ScalarRetTy, ScalarTys, FMF);
     959             : 
     960           7 :       return ScalarCalls * ScalarCost + ScalarizationCost;
     961             :     }
     962             :     // Look for intrinsics that can be lowered directly or turned into a scalar
     963             :     // intrinsic call.
     964           6 :     case Intrinsic::sqrt:
     965           6 :       ISDs.push_back(ISD::FSQRT);
     966           6 :       break;
     967          25 :     case Intrinsic::sin:
     968          25 :       ISDs.push_back(ISD::FSIN);
     969          25 :       break;
     970          25 :     case Intrinsic::cos:
     971          25 :       ISDs.push_back(ISD::FCOS);
     972          25 :       break;
     973          44 :     case Intrinsic::exp:
     974          44 :       ISDs.push_back(ISD::FEXP);
     975          44 :       break;
     976           3 :     case Intrinsic::exp2:
     977           3 :       ISDs.push_back(ISD::FEXP2);
     978           3 :       break;
     979          22 :     case Intrinsic::log:
     980          22 :       ISDs.push_back(ISD::FLOG);
     981          22 :       break;
     982          11 :     case Intrinsic::log10:
     983          11 :       ISDs.push_back(ISD::FLOG10);
     984          11 :       break;
     985           0 :     case Intrinsic::log2:
     986           0 :       ISDs.push_back(ISD::FLOG2);
     987           0 :       break;
     988         169 :     case Intrinsic::fabs:
     989         169 :       ISDs.push_back(ISD::FABS);
     990         169 :       break;
     991           0 :     case Intrinsic::minnum:
     992           0 :       ISDs.push_back(ISD::FMINNUM);
     993           0 :       if (FMF.noNaNs())
     994           0 :         ISDs.push_back(ISD::FMINNAN);
     995             :       break;
     996           0 :     case Intrinsic::maxnum:
     997           0 :       ISDs.push_back(ISD::FMAXNUM);
     998           0 :       if (FMF.noNaNs())
     999           0 :         ISDs.push_back(ISD::FMAXNAN);
    1000             :       break;
    1001         138 :     case Intrinsic::copysign:
    1002         138 :       ISDs.push_back(ISD::FCOPYSIGN);
    1003         138 :       break;
    1004         197 :     case Intrinsic::floor:
    1005         197 :       ISDs.push_back(ISD::FFLOOR);
    1006         197 :       break;
    1007         176 :     case Intrinsic::ceil:
    1008         176 :       ISDs.push_back(ISD::FCEIL);
    1009         176 :       break;
    1010         162 :     case Intrinsic::trunc:
    1011         162 :       ISDs.push_back(ISD::FTRUNC);
    1012         162 :       break;
    1013         165 :     case Intrinsic::nearbyint:
    1014         165 :       ISDs.push_back(ISD::FNEARBYINT);
    1015         165 :       break;
    1016         162 :     case Intrinsic::rint:
    1017         162 :       ISDs.push_back(ISD::FRINT);
    1018         162 :       break;
    1019           0 :     case Intrinsic::round:
    1020           0 :       ISDs.push_back(ISD::FROUND);
    1021           0 :       break;
    1022          25 :     case Intrinsic::pow:
    1023          25 :       ISDs.push_back(ISD::FPOW);
    1024          25 :       break;
    1025         344 :     case Intrinsic::fma:
    1026         344 :       ISDs.push_back(ISD::FMA);
    1027         344 :       break;
    1028           2 :     case Intrinsic::fmuladd:
    1029           2 :       ISDs.push_back(ISD::FMA);
    1030           2 :       break;
    1031             :     // FIXME: We should return 0 whenever getIntrinsicCost == TCC_Free.
    1032             :     case Intrinsic::lifetime_start:
    1033             :     case Intrinsic::lifetime_end:
    1034             :     case Intrinsic::sideeffect:
    1035             :       return 0;
    1036          12 :     case Intrinsic::masked_store:
    1037             :       return static_cast<T *>(this)
    1038          12 :           ->getMaskedMemoryOpCost(Instruction::Store, Tys[0], 0, 0);
    1039          20 :     case Intrinsic::masked_load:
    1040             :       return static_cast<T *>(this)
    1041          20 :           ->getMaskedMemoryOpCost(Instruction::Load, RetTy, 0, 0);
    1042          80 :     case Intrinsic::ctpop:
    1043          80 :       ISDs.push_back(ISD::CTPOP);
    1044             :       // In case of legalization use TCC_Expensive. This is cheaper than a
    1045             :       // library call but still not a cheap instruction.
    1046             :       SingleCallCost = TargetTransformInfo::TCC_Expensive;
    1047          80 :       break;
    1048             :     // FIXME: ctlz, cttz, ...
    1049             :     }
    1050             : 
    1051             :     const TargetLoweringBase *TLI = getTLI();
    1052        3512 :     std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, RetTy);
    1053             : 
    1054             :     SmallVector<unsigned, 2> LegalCost;
    1055             :     SmallVector<unsigned, 2> CustomCost;
    1056        5238 :     for (unsigned ISD : ISDs) {
    1057        1756 :       if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
    1058         553 :         if (IID == Intrinsic::fabs && TLI->isFAbsFree(LT.second)) {
    1059             :           return 0;
    1060             :         }
    1061             : 
    1062             :         // The operation is legal. Assume it costs 1.
    1063             :         // If the type is split to multiple registers, assume that there is some
    1064             :         // overhead to this.
    1065             :         // TODO: Once we have extract/insert subvector cost we need to use them.
    1066         521 :         if (LT.first > 1)
    1067           7 :           LegalCost.push_back(LT.first * 2);
    1068             :         else
    1069         514 :           LegalCost.push_back(LT.first * 1);
    1070             :       } else if (!TLI->isOperationExpand(ISD, LT.second)) {
    1071             :         // If the operation is custom lowered then assume
    1072             :         // that the code is twice as expensive.
    1073         286 :         CustomCost.push_back(LT.first * 2);
    1074             :       }
    1075             :     }
    1076             : 
    1077             :     auto MinLegalCostI = std::min_element(LegalCost.begin(), LegalCost.end());
    1078        1741 :     if (MinLegalCostI != LegalCost.end())
    1079         521 :       return *MinLegalCostI;
    1080             : 
    1081             :     auto MinCustomCostI = std::min_element(CustomCost.begin(), CustomCost.end());
    1082        1220 :     if (MinCustomCostI != CustomCost.end())
    1083         286 :       return *MinCustomCostI;
    1084             : 
    1085             :     // If we can't lower fmuladd into an FMA estimate the cost as a floating
    1086             :     // point mul followed by an add.
    1087         934 :     if (IID == Intrinsic::fmuladd)
    1088             :       return static_cast<T *>(this)
    1089           4 :                  ->getArithmeticInstrCost(BinaryOperator::FMul, RetTy) +
    1090             :              static_cast<T *>(this)
    1091           2 :                  ->getArithmeticInstrCost(BinaryOperator::FAdd, RetTy);
    1092             : 
    1093             :     // Else, assume that we need to scalarize this intrinsic. For math builtins
    1094             :     // this will emit a costly libcall, adding call overhead and spills. Make it
    1095             :     // very expensive.
    1096         932 :     if (RetTy->isVectorTy()) {
    1097             :       unsigned ScalarizationCost =
    1098             :           ((ScalarizationCostPassed != std::numeric_limits<unsigned>::max())
    1099         334 :                ? ScalarizationCostPassed
    1100             :                : getScalarizationOverhead(RetTy, true, false));
    1101         334 :       unsigned ScalarCalls = RetTy->getVectorNumElements();
    1102             :       SmallVector<Type *, 4> ScalarTys;
    1103         855 :       for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
    1104        1042 :         Type *Ty = Tys[i];
    1105         521 :         if (Ty->isVectorTy())
    1106         521 :           Ty = Ty->getScalarType();
    1107         521 :         ScalarTys.push_back(Ty);
    1108             :       }
    1109         338 :       unsigned ScalarCost = static_cast<T *>(this)->getIntrinsicInstrCost(
    1110             :           IID, RetTy->getScalarType(), ScalarTys, FMF);
    1111        1376 :       for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
    1112        1563 :         if (Tys[i]->isVectorTy()) {
    1113         521 :           if (ScalarizationCostPassed == std::numeric_limits<unsigned>::max())
    1114           0 :             ScalarizationCost += getScalarizationOverhead(Tys[i], false, true);
    1115        1563 :           ScalarCalls = std::max(ScalarCalls, Tys[i]->getVectorNumElements());
    1116             :         }
    1117             :       }
    1118             : 
    1119         334 :       return ScalarCalls * ScalarCost + ScalarizationCost;
    1120             :     }
    1121             : 
    1122             :     // This is going to be turned into a library call, make it expensive.
    1123             :     return SingleCallCost;
    1124             :   }
    1125             : 
    1126             :   /// \brief Compute a cost of the given call instruction.
    1127             :   ///
    1128             :   /// Compute the cost of calling function F with return type RetTy and
    1129             :   /// argument types Tys. F might be nullptr, in this case the cost of an
    1130             :   /// arbitrary call with the specified signature will be returned.
    1131             :   /// This is used, for instance,  when we estimate call of a vector
    1132             :   /// counterpart of the given function.
    1133             :   /// \param F Called function, might be nullptr.
    1134             :   /// \param RetTy Return value types.
    1135             :   /// \param Tys Argument types.
    1136             :   /// \returns The cost of Call instruction.
    1137             :   unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) {
    1138             :     return 10;
    1139             :   }
    1140             : 
    1141             :   unsigned getNumberOfParts(Type *Tp) {
    1142       24722 :     std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(DL, Tp);
    1143             :     return LT.first;
    1144             :   }
    1145             : 
    1146             :   unsigned getAddressComputationCost(Type *Ty, ScalarEvolution *,
    1147             :                                      const SCEV *) {
    1148             :     return 0;
    1149             :   }
    1150             : 
    1151             :   /// Try to calculate arithmetic and shuffle op costs for reduction operations.
    1152             :   /// We're assuming that reduction operation are performing the following way:
    1153             :   /// 1. Non-pairwise reduction
    1154             :   /// %val1 = shufflevector<n x t> %val, <n x t> %undef,
    1155             :   /// <n x i32> <i32 n/2, i32 n/2 + 1, ..., i32 n, i32 undef, ..., i32 undef>
    1156             :   ///            \----------------v-------------/  \----------v------------/
    1157             :   ///                            n/2 elements               n/2 elements
    1158             :   /// %red1 = op <n x t> %val, <n x t> val1
    1159             :   /// After this operation we have a vector %red1 where only the first n/2
    1160             :   /// elements are meaningful, the second n/2 elements are undefined and can be
    1161             :   /// dropped. All other operations are actually working with the vector of
    1162             :   /// length n/2, not n, though the real vector length is still n.
    1163             :   /// %val2 = shufflevector<n x t> %red1, <n x t> %undef,
    1164             :   /// <n x i32> <i32 n/4, i32 n/4 + 1, ..., i32 n/2, i32 undef, ..., i32 undef>
    1165             :   ///            \----------------v-------------/  \----------v------------/
    1166             :   ///                            n/4 elements               3*n/4 elements
    1167             :   /// %red2 = op <n x t> %red1, <n x t> val2  - working with the vector of
    1168             :   /// length n/2, the resulting vector has length n/4 etc.
    1169             :   /// 2. Pairwise reduction:
    1170             :   /// Everything is the same except for an additional shuffle operation which
    1171             :   /// is used to produce operands for pairwise kind of reductions.
    1172             :   /// %val1 = shufflevector<n x t> %val, <n x t> %undef,
    1173             :   /// <n x i32> <i32 0, i32 2, ..., i32 n-2, i32 undef, ..., i32 undef>
    1174             :   ///            \-------------v----------/  \----------v------------/
    1175             :   ///                   n/2 elements               n/2 elements
    1176             :   /// %val2 = shufflevector<n x t> %val, <n x t> %undef,
    1177             :   /// <n x i32> <i32 1, i32 3, ..., i32 n-1, i32 undef, ..., i32 undef>
    1178             :   ///            \-------------v----------/  \----------v------------/
    1179             :   ///                   n/2 elements               n/2 elements
    1180             :   /// %red1 = op <n x t> %val1, <n x t> val2
    1181             :   /// Again, the operation is performed on <n x t> vector, but the resulting
    1182             :   /// vector %red1 is <n/2 x t> vector.
    1183             :   ///
    1184             :   /// The cost model should take into account that the actual length of the
    1185             :   /// vector is reduced on each iteration.
    1186          47 :   unsigned getArithmeticReductionCost(unsigned Opcode, Type *Ty,
    1187             :                                       bool IsPairwise) {
    1188             :     assert(Ty->isVectorTy() && "Expect a vector type");
    1189          47 :     Type *ScalarTy = Ty->getVectorElementType();
    1190             :     unsigned NumVecElts = Ty->getVectorNumElements();
    1191             :     unsigned NumReduxLevels = Log2_32(NumVecElts);
    1192             :     unsigned ArithCost = 0;
    1193             :     unsigned ShuffleCost = 0;
    1194             :     auto *ConcreteTTI = static_cast<T *>(this);
    1195          94 :     std::pair<unsigned, MVT> LT =
    1196          47 :         ConcreteTTI->getTLI()->getTypeLegalizationCost(DL, Ty);
    1197             :     unsigned LongVectorCount = 0;
    1198          47 :     unsigned MVTLen =
    1199             :         LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
    1200          89 :     while (NumVecElts > MVTLen) {
    1201          21 :       NumVecElts /= 2;
    1202             :       // Assume the pairwise shuffles add a cost.
    1203          21 :       ShuffleCost += (IsPairwise + 1) *
    1204             :                      ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
    1205             :                                                  NumVecElts, Ty);
    1206          21 :       ArithCost += ConcreteTTI->getArithmeticInstrCost(Opcode, Ty);
    1207          21 :       Ty = VectorType::get(ScalarTy, NumVecElts);
    1208          21 :       ++LongVectorCount;
    1209             :     }
    1210             :     // The minimal length of the vector is limited by the real length of vector
    1211             :     // operations performed on the current platform. That's why several final
    1212             :     // reduction operations are performed on the vectors with the same
    1213             :     // architecture-dependent length.
    1214          47 :     ShuffleCost += (NumReduxLevels - LongVectorCount) * (IsPairwise + 1) *
    1215             :                    ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
    1216             :                                                NumVecElts, Ty);
    1217          47 :     ArithCost += (NumReduxLevels - LongVectorCount) *
    1218             :                  ConcreteTTI->getArithmeticInstrCost(Opcode, Ty);
    1219          47 :     return ShuffleCost + ArithCost + getScalarizationOverhead(Ty, false, true);
    1220             :   }
    1221             : 
    1222             :   /// Try to calculate op costs for min/max reduction operations.
    1223             :   /// \param CondTy Conditional type for the Select instruction.
    1224         832 :   unsigned getMinMaxReductionCost(Type *Ty, Type *CondTy, bool IsPairwise,
    1225             :                                   bool) {
    1226             :     assert(Ty->isVectorTy() && "Expect a vector type");
    1227         832 :     Type *ScalarTy = Ty->getVectorElementType();
    1228         832 :     Type *ScalarCondTy = CondTy->getVectorElementType();
    1229             :     unsigned NumVecElts = Ty->getVectorNumElements();
    1230             :     unsigned NumReduxLevels = Log2_32(NumVecElts);
    1231             :     unsigned CmpOpcode;
    1232             :     if (Ty->isFPOrFPVectorTy()) {
    1233             :       CmpOpcode = Instruction::FCmp;
    1234             :     } else {
    1235             :       assert(Ty->isIntOrIntVectorTy() &&
    1236             :              "expecting floating point or integer type for min/max reduction");
    1237             :       CmpOpcode = Instruction::ICmp;
    1238             :     }
    1239             :     unsigned MinMaxCost = 0;
    1240             :     unsigned ShuffleCost = 0;
    1241             :     auto *ConcreteTTI = static_cast<T *>(this);
    1242        1664 :     std::pair<unsigned, MVT> LT =
    1243         832 :         ConcreteTTI->getTLI()->getTypeLegalizationCost(DL, Ty);
    1244             :     unsigned LongVectorCount = 0;
    1245         832 :     unsigned MVTLen =
    1246             :         LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
    1247        2536 :     while (NumVecElts > MVTLen) {
    1248         852 :       NumVecElts /= 2;
    1249             :       // Assume the pairwise shuffles add a cost.
    1250         852 :       ShuffleCost += (IsPairwise + 1) *
    1251             :                      ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
    1252             :                                                  NumVecElts, Ty);
    1253         852 :       MinMaxCost +=
    1254         852 :           ConcreteTTI->getCmpSelInstrCost(CmpOpcode, Ty, CondTy, nullptr) +
    1255             :           ConcreteTTI->getCmpSelInstrCost(Instruction::Select, Ty, CondTy,
    1256             :                                           nullptr);
    1257         852 :       Ty = VectorType::get(ScalarTy, NumVecElts);
    1258         852 :       CondTy = VectorType::get(ScalarCondTy, NumVecElts);
    1259         852 :       ++LongVectorCount;
    1260             :     }
    1261             :     // The minimal length of the vector is limited by the real length of vector
    1262             :     // operations performed on the current platform. That's why several final
    1263             :     // reduction opertions are perfomed on the vectors with the same
    1264             :     // architecture-dependent length.
    1265         832 :     ShuffleCost += (NumReduxLevels - LongVectorCount) * (IsPairwise + 1) *
    1266             :                    ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
    1267             :                                                NumVecElts, Ty);
    1268         832 :     MinMaxCost +=
    1269         832 :         (NumReduxLevels - LongVectorCount) *
    1270         832 :         (ConcreteTTI->getCmpSelInstrCost(CmpOpcode, Ty, CondTy, nullptr) +
    1271             :          ConcreteTTI->getCmpSelInstrCost(Instruction::Select, Ty, CondTy,
    1272             :                                          nullptr));
    1273             :     // Need 3 extractelement instructions for scalarization + an additional
    1274             :     // scalar select instruction.
    1275        1664 :     return ShuffleCost + MinMaxCost +
    1276         832 :            3 * getScalarizationOverhead(Ty, /*Insert=*/false,
    1277         832 :                                         /*Extract=*/true) +
    1278             :            ConcreteTTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
    1279         832 :                                            ScalarCondTy, nullptr);
    1280             :   }
    1281             : 
    1282             :   unsigned getVectorSplitCost() { return 1; }
    1283             : 
    1284             :   /// @}
    1285             : };
    1286             : 
    1287             : /// \brief Concrete BasicTTIImpl that can be used if no further customization
    1288             : /// is needed.
    1289      268581 : class BasicTTIImpl : public BasicTTIImplBase<BasicTTIImpl> {
    1290             :   using BaseT = BasicTTIImplBase<BasicTTIImpl>;
    1291             : 
    1292             :   friend class BasicTTIImplBase<BasicTTIImpl>;
    1293             : 
    1294             :   const TargetSubtargetInfo *ST;
    1295             :   const TargetLoweringBase *TLI;
    1296             : 
    1297             :   const TargetSubtargetInfo *getST() const { return ST; }
    1298             :   const TargetLoweringBase *getTLI() const { return TLI; }
    1299             : 
    1300             : public:
    1301             :   explicit BasicTTIImpl(const TargetMachine *ST, const Function &F);
    1302             : };
    1303             : 
    1304             : } // end namespace llvm
    1305             : 
    1306             : #endif // LLVM_CODEGEN_BASICTTIIMPL_H

Generated by: LCOV version 1.13