]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/CodeGen/BasicTTIImpl.h
Merge llvm trunk r321414 to contrib/llvm.
[FreeBSD/FreeBSD.git] / contrib / llvm / include / llvm / CodeGen / BasicTTIImpl.h
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   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     for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
96       Cost += static_cast<T *>(this)
97                   ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
98       Cost += static_cast<T *>(this)
99                   ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
100     }
101     return Cost;
102   }
103
104   /// \brief Local query method delegates up to T which *must* implement this!
105   const TargetSubtargetInfo *getST() const {
106     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     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   bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
124                                       unsigned BitWidth, unsigned AddressSpace,
125                                       unsigned Alignment, bool *Fast) const {
126     EVT E = EVT::getIntegerVT(Context, BitWidth);
127     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     return getTLI()->isLegalAddImmediate(imm);
143   }
144
145   bool isLegalICmpImmediate(int64_t imm) {
146     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     AM.BaseGV = BaseGV;
154     AM.BaseOffs = BaseOffset;
155     AM.HasBaseReg = HasBaseReg;
156     AM.Scale = Scale;
157     return getTLI()->isLegalAddressingMode(DL, AM, Ty, AddrSpace, I);
158   }
159
160   bool isLSRCostLess(TTI::LSRCost C1, TTI::LSRCost C2) {
161     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     AM.BaseGV = BaseGV;
168     AM.BaseOffs = BaseOffset;
169     AM.HasBaseReg = HasBaseReg;
170     AM.Scale = Scale;
171     return getTLI()->getScalingFactorCost(DL, AM, Ty, AddrSpace);
172   }
173
174   bool isTruncateFree(Type *Ty1, Type *Ty2) {
175     return getTLI()->isTruncateFree(Ty1, Ty2);
176   }
177
178   bool isProfitableToHoist(Instruction *I) {
179     return getTLI()->isProfitableToHoist(I);
180   }
181
182   bool isTypeLegal(Type *Ty) {
183     EVT VT = getTLI()->getValueType(DL, Ty);
184     return getTLI()->isTypeLegal(VT);
185   }
186
187   int getGEPCost(Type *PointeeType, const Value *Ptr,
188                  ArrayRef<const Value *> Operands) {
189     return BaseT::getGEPCost(PointeeType, Ptr, Operands);
190   }
191
192   int getExtCost(const Instruction *I, const Value *Src) {
193     if (getTLI()->isExtFree(I))
194       return TargetTransformInfo::TCC_Free;
195
196     if (isa<ZExtInst>(I) || isa<SExtInst>(I))
197       if (const LoadInst *LI = dyn_cast<LoadInst>(Src))
198         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     return BaseT::getIntrinsicCost(IID, RetTy, Arguments);
207   }
208
209   unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
210                             ArrayRef<Type *> ParamTys) {
211     if (IID == Intrinsic::cttz) {
212       if (getTLI()->isCheapToSpeculateCttz())
213         return TargetTransformInfo::TCC_Basic;
214       return TargetTransformInfo::TCC_Expensive;
215     }
216
217     if (IID == Intrinsic::ctlz) {
218       if (getTLI()->isCheapToSpeculateCtlz())
219         return TargetTransformInfo::TCC_Basic;
220       return TargetTransformInfo::TCC_Expensive;
221     }
222
223     return BaseT::getIntrinsicCost(IID, RetTy, ParamTys);
224   }
225
226   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     JumpTableSize = 0;
240     bool IsJTAllowed = TLI->areJTsAllowed(SI.getParent()->getParent());
241
242     // Early exit if both a jump table and bit test are not allowed.
243     if (N < 1 || (!IsJTAllowed && DL.getPointerSizeInBits() < N))
244       return N;
245
246     APInt MaxCaseVal = SI.case_begin()->getCaseValue()->getValue();
247     APInt MinCaseVal = MaxCaseVal;
248     for (auto CI : SI.cases()) {
249       const APInt &CaseVal = CI.getCaseValue()->getValue();
250       if (CaseVal.sgt(MaxCaseVal))
251         MaxCaseVal = CaseVal;
252       if (CaseVal.slt(MinCaseVal))
253         MinCaseVal = CaseVal;
254     }
255
256     // Check if suitable for a bit test
257     if (N <= DL.getPointerSizeInBits()) {
258       SmallPtrSet<const BasicBlock *, 4> Dests;
259       for (auto I : SI.cases())
260         Dests.insert(I.getCaseSuccessor());
261
262       if (TLI->isSuitableForBitTests(Dests.size(), N, MinCaseVal, MaxCaseVal,
263                                      DL))
264         return 1;
265     }
266
267     // Check if suitable for a jump table.
268     if (IsJTAllowed) {
269       if (N < 2 || N < TLI->getMinimumJumpTableEntries())
270         return N;
271       uint64_t Range =
272           (MaxCaseVal - MinCaseVal)
273               .getLimitedValue(std::numeric_limits<uint64_t>::max() - 1) + 1;
274       // Check whether a range of clusters is dense enough for a jump table
275       if (TLI->isSuitableForJumpTable(&SI, N, Range)) {
276         JumpTableSize = Range;
277         return 1;
278       }
279     }
280     return N;
281   }
282
283   unsigned getJumpBufAlignment() { return getTLI()->getJumpBufAlignment(); }
284
285   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   bool haveFastSqrt(Type *Ty) {
294     const TargetLoweringBase *TLI = getTLI();
295     EVT VT = TLI->getValueType(DL, Ty);
296     return TLI->isTypeLegal(VT) &&
297            TLI->isOperationLegalOrCustom(ISD::FSQRT, VT);
298   }
299
300   bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) {
301     return true;
302   }
303
304   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     EVT VT = TLI->getValueType(DL, Ty);
309     if (TLI->isOperationLegalOrCustomOrPromote(ISD::FADD, VT))
310       return TargetTransformInfo::TCC_Basic;
311     return TargetTransformInfo::TCC_Expensive;
312   }
313
314   unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) {
315     const TargetLoweringBase *TLI = getTLI();
316     switch (Opcode) {
317     default: break;
318     case Instruction::Trunc:
319       if (TLI->isTruncateFree(OpTy, Ty))
320         return TargetTransformInfo::TCC_Free;
321       return TargetTransformInfo::TCC_Basic;
322     case Instruction::ZExt:
323       if (TLI->isZExtFree(OpTy, Ty))
324         return TargetTransformInfo::TCC_Free;
325       return TargetTransformInfo::TCC_Basic;
326     }
327
328     return BaseT::getOperationCost(Opcode, Ty, OpTy);
329   }
330
331   unsigned getInliningThresholdMultiplier() { return 1; }
332
333   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     if (PartialUnrollingThreshold.getNumOccurrences() > 0)
361       MaxOps = PartialUnrollingThreshold;
362     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     for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
369          ++I) {
370       BasicBlock *BB = *I;
371
372       for (BasicBlock::iterator J = BB->begin(), JE = BB->end(); J != JE; ++J)
373         if (isa<CallInst>(J) || isa<InvokeInst>(J)) {
374           ImmutableCallSite CS(&*J);
375           if (const Function *F = CS.getCalledFunction()) {
376             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     UP.Partial = UP.Runtime = UP.UpperBound = true;
387     UP.PartialThreshold = MaxOps;
388
389     // Avoid unrolling when optimizing for size.
390     UP.OptSizeThreshold = 0;
391     UP.PartialOptSizeThreshold = 0;
392
393     // Set number of instructions optimized when "back edge"
394     // becomes "fall through" to default value of 2.
395     UP.BEInsns = 2;
396   }
397
398   int getInstructionLatency(const Instruction *I) {
399     if (isa<LoadInst>(I))
400       return getST()->getSchedModel().DefaultLoadLatency;
401
402     return BaseT::getInstructionLatency(I);
403   }
404
405   bool isOutOfOrder() const {
406     return getST()->getSchedModel().isOutOfOrder();
407   }
408
409   /// @}
410
411   /// \name Vector TTI Implementations
412   /// @{
413
414   unsigned getNumberOfRegisters(bool Vector) { return Vector ? 0 : 1; }
415
416   unsigned getRegisterBitWidth(bool Vector) const { return 32; }
417
418   /// Estimate the overhead of scalarizing an instruction. Insert and Extract
419   /// are set if the result needs to be inserted and/or extracted from vectors.
420   unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) {
421     assert(Ty->isVectorTy() && "Can only scalarize vectors");
422     unsigned Cost = 0;
423
424     for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
425       if (Insert)
426         Cost += static_cast<T *>(this)
427                     ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
428       if (Extract)
429         Cost += static_cast<T *>(this)
430                     ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
431     }
432
433     return Cost;
434   }
435
436   /// Estimate the overhead of scalarizing an instructions unique
437   /// non-constant operands. The types of the arguments are ordinarily
438   /// scalar, in which case the costs are multiplied with VF.
439   unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
440                                             unsigned VF) {
441     unsigned Cost = 0;
442     SmallPtrSet<const Value*, 4> UniqueOperands;
443     for (const Value *A : Args) {
444       if (!isa<Constant>(A) && UniqueOperands.insert(A).second) {
445         Type *VecTy = nullptr;
446         if (A->getType()->isVectorTy()) {
447           VecTy = A->getType();
448           // If A is a vector operand, VF should be 1 or correspond to A.
449           assert((VF == 1 || VF == VecTy->getVectorNumElements()) &&
450                  "Vector argument does not match VF");
451         }
452         else
453           VecTy = VectorType::get(A->getType(), VF);
454
455         Cost += getScalarizationOverhead(VecTy, false, true);
456       }
457     }
458
459     return Cost;
460   }
461
462   unsigned getScalarizationOverhead(Type *VecTy, ArrayRef<const Value *> Args) {
463     assert(VecTy->isVectorTy());
464
465     unsigned Cost = 0;
466
467     Cost += getScalarizationOverhead(VecTy, true, false);
468     if (!Args.empty())
469       Cost += getOperandsScalarizationOverhead(Args,
470                                                VecTy->getVectorNumElements());
471     else
472       // When no information on arguments is provided, we add the cost
473       // associated with one argument as a heuristic.
474       Cost += getScalarizationOverhead(VecTy, false, true);
475
476     return Cost;
477   }
478
479   unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
480
481   unsigned getArithmeticInstrCost(
482       unsigned Opcode, Type *Ty,
483       TTI::OperandValueKind Opd1Info = TTI::OK_AnyValue,
484       TTI::OperandValueKind Opd2Info = TTI::OK_AnyValue,
485       TTI::OperandValueProperties Opd1PropInfo = TTI::OP_None,
486       TTI::OperandValueProperties Opd2PropInfo = TTI::OP_None,
487       ArrayRef<const Value *> Args = ArrayRef<const Value *>()) {
488     // Check if any of the operands are vector operands.
489     const TargetLoweringBase *TLI = getTLI();
490     int ISD = TLI->InstructionOpcodeToISD(Opcode);
491     assert(ISD && "Invalid opcode");
492
493     std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
494
495     bool IsFloat = Ty->isFPOrFPVectorTy();
496     // Assume that floating point arithmetic operations cost twice as much as
497     // integer operations.
498     unsigned OpCost = (IsFloat ? 2 : 1);
499
500     if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
501       // The operation is legal. Assume it costs 1.
502       // TODO: Once we have extract/insert subvector cost we need to use them.
503       return LT.first * OpCost;
504     }
505
506     if (!TLI->isOperationExpand(ISD, LT.second)) {
507       // If the operation is custom lowered, then assume that the code is twice
508       // as expensive.
509       return LT.first * 2 * OpCost;
510     }
511
512     // Else, assume that we need to scalarize this op.
513     // TODO: If one of the types get legalized by splitting, handle this
514     // similarly to what getCastInstrCost() does.
515     if (Ty->isVectorTy()) {
516       unsigned Num = Ty->getVectorNumElements();
517       unsigned Cost = static_cast<T *>(this)
518                           ->getArithmeticInstrCost(Opcode, Ty->getScalarType());
519       // Return the cost of multiple scalar invocation plus the cost of
520       // inserting and extracting the values.
521       return getScalarizationOverhead(Ty, Args) + Num * Cost;
522     }
523
524     // We don't know anything about this scalar instruction.
525     return OpCost;
526   }
527
528   unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
529                           Type *SubTp) {
530     if (Kind == TTI::SK_Alternate || Kind == TTI::SK_PermuteTwoSrc ||
531         Kind == TTI::SK_PermuteSingleSrc) {
532       return getPermuteShuffleOverhead(Tp);
533     }
534     return 1;
535   }
536
537   unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
538                             const Instruction *I = nullptr) {
539     const TargetLoweringBase *TLI = getTLI();
540     int ISD = TLI->InstructionOpcodeToISD(Opcode);
541     assert(ISD && "Invalid opcode");
542     std::pair<unsigned, MVT> SrcLT = TLI->getTypeLegalizationCost(DL, Src);
543     std::pair<unsigned, MVT> DstLT = TLI->getTypeLegalizationCost(DL, Dst);
544
545     // Check for NOOP conversions.
546     if (SrcLT.first == DstLT.first &&
547         SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
548
549       // Bitcast between types that are legalized to the same type are free.
550       if (Opcode == Instruction::BitCast || Opcode == Instruction::Trunc)
551         return 0;
552     }
553
554     if (Opcode == Instruction::Trunc &&
555         TLI->isTruncateFree(SrcLT.second, DstLT.second))
556       return 0;
557
558     if (Opcode == Instruction::ZExt &&
559         TLI->isZExtFree(SrcLT.second, DstLT.second))
560       return 0;
561
562     if (Opcode == Instruction::AddrSpaceCast &&
563         TLI->isNoopAddrSpaceCast(Src->getPointerAddressSpace(),
564                                  Dst->getPointerAddressSpace()))
565       return 0;
566
567     // If this is a zext/sext of a load, return 0 if the corresponding
568     // extending load exists on target.
569     if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
570         I && isa<LoadInst>(I->getOperand(0))) {
571         EVT ExtVT = EVT::getEVT(Dst);
572         EVT LoadVT = EVT::getEVT(Src);
573         unsigned LType =
574           ((Opcode == Instruction::ZExt) ? ISD::ZEXTLOAD : ISD::SEXTLOAD);
575         if (TLI->isLoadExtLegal(LType, ExtVT, LoadVT))
576           return 0;
577     }
578
579     // If the cast is marked as legal (or promote) then assume low cost.
580     if (SrcLT.first == DstLT.first &&
581         TLI->isOperationLegalOrPromote(ISD, DstLT.second))
582       return 1;
583
584     // Handle scalar conversions.
585     if (!Src->isVectorTy() && !Dst->isVectorTy()) {
586       // Scalar bitcasts are usually free.
587       if (Opcode == Instruction::BitCast)
588         return 0;
589
590       // Just check the op cost. If the operation is legal then assume it costs
591       // 1.
592       if (!TLI->isOperationExpand(ISD, DstLT.second))
593         return 1;
594
595       // Assume that illegal scalar instruction are expensive.
596       return 4;
597     }
598
599     // Check vector-to-vector casts.
600     if (Dst->isVectorTy() && Src->isVectorTy()) {
601       // If the cast is between same-sized registers, then the check is simple.
602       if (SrcLT.first == DstLT.first &&
603           SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
604
605         // Assume that Zext is done using AND.
606         if (Opcode == Instruction::ZExt)
607           return 1;
608
609         // Assume that sext is done using SHL and SRA.
610         if (Opcode == Instruction::SExt)
611           return 2;
612
613         // Just check the op cost. If the operation is legal then assume it
614         // costs
615         // 1 and multiply by the type-legalization overhead.
616         if (!TLI->isOperationExpand(ISD, DstLT.second))
617           return SrcLT.first * 1;
618       }
619
620       // If we are legalizing by splitting, query the concrete TTI for the cost
621       // of casting the original vector twice. We also need to factor int the
622       // cost of the split itself. Count that as 1, to be consistent with
623       // TLI->getTypeLegalizationCost().
624       if ((TLI->getTypeAction(Src->getContext(), TLI->getValueType(DL, Src)) ==
625            TargetLowering::TypeSplitVector) ||
626           (TLI->getTypeAction(Dst->getContext(), TLI->getValueType(DL, Dst)) ==
627            TargetLowering::TypeSplitVector)) {
628         Type *SplitDst = VectorType::get(Dst->getVectorElementType(),
629                                          Dst->getVectorNumElements() / 2);
630         Type *SplitSrc = VectorType::get(Src->getVectorElementType(),
631                                          Src->getVectorNumElements() / 2);
632         T *TTI = static_cast<T *>(this);
633         return TTI->getVectorSplitCost() +
634                (2 * TTI->getCastInstrCost(Opcode, SplitDst, SplitSrc, I));
635       }
636
637       // In other cases where the source or destination are illegal, assume
638       // the operation will get scalarized.
639       unsigned Num = Dst->getVectorNumElements();
640       unsigned Cost = static_cast<T *>(this)->getCastInstrCost(
641           Opcode, Dst->getScalarType(), Src->getScalarType(), I);
642
643       // Return the cost of multiple scalar invocation plus the cost of
644       // inserting and extracting the values.
645       return getScalarizationOverhead(Dst, true, true) + Num * Cost;
646     }
647
648     // We already handled vector-to-vector and scalar-to-scalar conversions.
649     // This
650     // is where we handle bitcast between vectors and scalars. We need to assume
651     //  that the conversion is scalarized in one way or another.
652     if (Opcode == Instruction::BitCast)
653       // Illegal bitcasts are done by storing and loading from a stack slot.
654       return (Src->isVectorTy() ? getScalarizationOverhead(Src, false, true)
655                                 : 0) +
656              (Dst->isVectorTy() ? getScalarizationOverhead(Dst, true, false)
657                                 : 0);
658
659     llvm_unreachable("Unhandled cast");
660   }
661
662   unsigned getExtractWithExtendCost(unsigned Opcode, Type *Dst,
663                                     VectorType *VecTy, unsigned Index) {
664     return static_cast<T *>(this)->getVectorInstrCost(
665                Instruction::ExtractElement, VecTy, Index) +
666            static_cast<T *>(this)->getCastInstrCost(Opcode, Dst,
667                                                     VecTy->getElementType());
668   }
669
670   unsigned getCFInstrCost(unsigned Opcode) {
671     // Branches are assumed to be predicted.
672     return 0;
673   }
674
675   unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
676                               const Instruction *I) {
677     const TargetLoweringBase *TLI = getTLI();
678     int ISD = TLI->InstructionOpcodeToISD(Opcode);
679     assert(ISD && "Invalid opcode");
680
681     // Selects on vectors are actually vector selects.
682     if (ISD == ISD::SELECT) {
683       assert(CondTy && "CondTy must exist");
684       if (CondTy->isVectorTy())
685         ISD = ISD::VSELECT;
686     }
687     std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
688
689     if (!(ValTy->isVectorTy() && !LT.second.isVector()) &&
690         !TLI->isOperationExpand(ISD, LT.second)) {
691       // The operation is legal. Assume it costs 1. Multiply
692       // by the type-legalization overhead.
693       return LT.first * 1;
694     }
695
696     // Otherwise, assume that the cast is scalarized.
697     // TODO: If one of the types get legalized by splitting, handle this
698     // similarly to what getCastInstrCost() does.
699     if (ValTy->isVectorTy()) {
700       unsigned Num = ValTy->getVectorNumElements();
701       if (CondTy)
702         CondTy = CondTy->getScalarType();
703       unsigned Cost = static_cast<T *>(this)->getCmpSelInstrCost(
704           Opcode, ValTy->getScalarType(), CondTy, I);
705
706       // Return the cost of multiple scalar invocation plus the cost of
707       // inserting and extracting the values.
708       return getScalarizationOverhead(ValTy, true, false) + Num * Cost;
709     }
710
711     // Unknown scalar opcode.
712     return 1;
713   }
714
715   unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
716     std::pair<unsigned, MVT> LT =
717         getTLI()->getTypeLegalizationCost(DL, Val->getScalarType());
718
719     return LT.first;
720   }
721
722   unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
723                        unsigned AddressSpace, const Instruction *I = nullptr) {
724     assert(!Src->isVoidTy() && "Invalid type");
725     std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(DL, Src);
726
727     // Assuming that all loads of legal types cost 1.
728     unsigned Cost = LT.first;
729
730     if (Src->isVectorTy() &&
731         Src->getPrimitiveSizeInBits() < LT.second.getSizeInBits()) {
732       // This is a vector load that legalizes to a larger type than the vector
733       // itself. Unless the corresponding extending load or truncating store is
734       // legal, then this will scalarize.
735       TargetLowering::LegalizeAction LA = TargetLowering::Expand;
736       EVT MemVT = getTLI()->getValueType(DL, Src);
737       if (Opcode == Instruction::Store)
738         LA = getTLI()->getTruncStoreAction(LT.second, MemVT);
739       else
740         LA = getTLI()->getLoadExtAction(ISD::EXTLOAD, LT.second, MemVT);
741
742       if (LA != TargetLowering::Legal && LA != TargetLowering::Custom) {
743         // This is a vector load/store for some illegal type that is scalarized.
744         // We must account for the cost of building or decomposing the vector.
745         Cost += getScalarizationOverhead(Src, Opcode != Instruction::Store,
746                                          Opcode == Instruction::Store);
747       }
748     }
749
750     return Cost;
751   }
752
753   unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
754                                       unsigned Factor,
755                                       ArrayRef<unsigned> Indices,
756                                       unsigned Alignment,
757                                       unsigned AddressSpace) {
758     VectorType *VT = dyn_cast<VectorType>(VecTy);
759     assert(VT && "Expect a vector type for interleaved memory op");
760
761     unsigned NumElts = VT->getNumElements();
762     assert(Factor > 1 && NumElts % Factor == 0 && "Invalid interleave factor");
763
764     unsigned NumSubElts = NumElts / Factor;
765     VectorType *SubVT = VectorType::get(VT->getElementType(), NumSubElts);
766
767     // Firstly, the cost of load/store operation.
768     unsigned Cost = static_cast<T *>(this)->getMemoryOpCost(
769         Opcode, VecTy, Alignment, AddressSpace);
770
771     // Legalize the vector type, and get the legalized and unlegalized type
772     // sizes.
773     MVT VecTyLT = getTLI()->getTypeLegalizationCost(DL, VecTy).second;
774     unsigned VecTySize =
775         static_cast<T *>(this)->getDataLayout().getTypeStoreSize(VecTy);
776     unsigned VecTyLTSize = VecTyLT.getStoreSize();
777
778     // Return the ceiling of dividing A by B.
779     auto ceil = [](unsigned A, unsigned B) { return (A + B - 1) / B; };
780
781     // Scale the cost of the memory operation by the fraction of legalized
782     // instructions that will actually be used. We shouldn't account for the
783     // cost of dead instructions since they will be removed.
784     //
785     // E.g., An interleaved load of factor 8:
786     //       %vec = load <16 x i64>, <16 x i64>* %ptr
787     //       %v0 = shufflevector %vec, undef, <0, 8>
788     //
789     // If <16 x i64> is legalized to 8 v2i64 loads, only 2 of the loads will be
790     // used (those corresponding to elements [0:1] and [8:9] of the unlegalized
791     // type). The other loads are unused.
792     //
793     // We only scale the cost of loads since interleaved store groups aren't
794     // allowed to have gaps.
795     if (Opcode == Instruction::Load && VecTySize > VecTyLTSize) {
796       // The number of loads of a legal type it will take to represent a load
797       // of the unlegalized vector type.
798       unsigned NumLegalInsts = ceil(VecTySize, VecTyLTSize);
799
800       // The number of elements of the unlegalized type that correspond to a
801       // single legal instruction.
802       unsigned NumEltsPerLegalInst = ceil(NumElts, NumLegalInsts);
803
804       // Determine which legal instructions will be used.
805       BitVector UsedInsts(NumLegalInsts, false);
806       for (unsigned Index : Indices)
807         for (unsigned Elt = 0; Elt < NumSubElts; ++Elt)
808           UsedInsts.set((Index + Elt * Factor) / NumEltsPerLegalInst);
809
810       // Scale the cost of the load by the fraction of legal instructions that
811       // will be used.
812       Cost *= UsedInsts.count() / NumLegalInsts;
813     }
814
815     // Then plus the cost of interleave operation.
816     if (Opcode == Instruction::Load) {
817       // The interleave cost is similar to extract sub vectors' elements
818       // from the wide vector, and insert them into sub vectors.
819       //
820       // E.g. An interleaved load of factor 2 (with one member of index 0):
821       //      %vec = load <8 x i32>, <8 x i32>* %ptr
822       //      %v0 = shuffle %vec, undef, <0, 2, 4, 6>         ; Index 0
823       // The cost is estimated as extract elements at 0, 2, 4, 6 from the
824       // <8 x i32> vector and insert them into a <4 x i32> vector.
825
826       assert(Indices.size() <= Factor &&
827              "Interleaved memory op has too many members");
828
829       for (unsigned Index : Indices) {
830         assert(Index < Factor && "Invalid index for interleaved memory op");
831
832         // Extract elements from loaded vector for each sub vector.
833         for (unsigned i = 0; i < NumSubElts; i++)
834           Cost += static_cast<T *>(this)->getVectorInstrCost(
835               Instruction::ExtractElement, VT, Index + i * Factor);
836       }
837
838       unsigned InsSubCost = 0;
839       for (unsigned i = 0; i < NumSubElts; i++)
840         InsSubCost += static_cast<T *>(this)->getVectorInstrCost(
841             Instruction::InsertElement, SubVT, i);
842
843       Cost += Indices.size() * InsSubCost;
844     } else {
845       // The interleave cost is extract all elements from sub vectors, and
846       // insert them into the wide vector.
847       //
848       // E.g. An interleaved store of factor 2:
849       //      %v0_v1 = shuffle %v0, %v1, <0, 4, 1, 5, 2, 6, 3, 7>
850       //      store <8 x i32> %interleaved.vec, <8 x i32>* %ptr
851       // The cost is estimated as extract all elements from both <4 x i32>
852       // vectors and insert into the <8 x i32> vector.
853
854       unsigned ExtSubCost = 0;
855       for (unsigned i = 0; i < NumSubElts; i++)
856         ExtSubCost += static_cast<T *>(this)->getVectorInstrCost(
857             Instruction::ExtractElement, SubVT, i);
858       Cost += ExtSubCost * Factor;
859
860       for (unsigned i = 0; i < NumElts; i++)
861         Cost += static_cast<T *>(this)
862                     ->getVectorInstrCost(Instruction::InsertElement, VT, i);
863     }
864
865     return Cost;
866   }
867
868   /// Get intrinsic cost based on arguments.
869   unsigned getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
870                                  ArrayRef<Value *> Args, FastMathFlags FMF,
871                                  unsigned VF = 1) {
872     unsigned RetVF = (RetTy->isVectorTy() ? RetTy->getVectorNumElements() : 1);
873     assert((RetVF == 1 || VF == 1) && "VF > 1 and RetVF is a vector type");
874
875     switch (IID) {
876     default: {
877       // Assume that we need to scalarize this intrinsic.
878       SmallVector<Type *, 4> Types;
879       for (Value *Op : Args) {
880         Type *OpTy = Op->getType();
881         assert(VF == 1 || !OpTy->isVectorTy());
882         Types.push_back(VF == 1 ? OpTy : VectorType::get(OpTy, VF));
883       }
884
885       if (VF > 1 && !RetTy->isVoidTy())
886         RetTy = VectorType::get(RetTy, VF);
887
888       // Compute the scalarization overhead based on Args for a vector
889       // intrinsic. A vectorizer will pass a scalar RetTy and VF > 1, while
890       // CostModel will pass a vector RetTy and VF is 1.
891       unsigned ScalarizationCost = std::numeric_limits<unsigned>::max();
892       if (RetVF > 1 || VF > 1) {
893         ScalarizationCost = 0;
894         if (!RetTy->isVoidTy())
895           ScalarizationCost += getScalarizationOverhead(RetTy, true, false);
896         ScalarizationCost += getOperandsScalarizationOverhead(Args, VF);
897       }
898
899       return static_cast<T *>(this)->
900         getIntrinsicInstrCost(IID, RetTy, Types, FMF, ScalarizationCost);
901     }
902     case Intrinsic::masked_scatter: {
903       assert(VF == 1 && "Can't vectorize types here.");
904       Value *Mask = Args[3];
905       bool VarMask = !isa<Constant>(Mask);
906       unsigned Alignment = cast<ConstantInt>(Args[2])->getZExtValue();
907       return
908         static_cast<T *>(this)->getGatherScatterOpCost(Instruction::Store,
909                                                        Args[0]->getType(),
910                                                        Args[1], VarMask,
911                                                        Alignment);
912     }
913     case Intrinsic::masked_gather: {
914       assert(VF == 1 && "Can't vectorize types here.");
915       Value *Mask = Args[2];
916       bool VarMask = !isa<Constant>(Mask);
917       unsigned Alignment = cast<ConstantInt>(Args[1])->getZExtValue();
918       return
919         static_cast<T *>(this)->getGatherScatterOpCost(Instruction::Load,
920                                                        RetTy, Args[0], VarMask,
921                                                        Alignment);
922     }
923     }
924   }
925
926   /// Get intrinsic cost based on argument types.
927   /// If ScalarizationCostPassed is std::numeric_limits<unsigned>::max(), the
928   /// cost of scalarizing the arguments and the return value will be computed
929   /// based on types.
930   unsigned getIntrinsicInstrCost(
931       Intrinsic::ID IID, Type *RetTy, ArrayRef<Type *> Tys, FastMathFlags FMF,
932       unsigned ScalarizationCostPassed = std::numeric_limits<unsigned>::max()) {
933     SmallVector<unsigned, 2> ISDs;
934     unsigned SingleCallCost = 10; // Library call cost. Make it expensive.
935     switch (IID) {
936     default: {
937       // Assume that we need to scalarize this intrinsic.
938       unsigned ScalarizationCost = ScalarizationCostPassed;
939       unsigned ScalarCalls = 1;
940       Type *ScalarRetTy = RetTy;
941       if (RetTy->isVectorTy()) {
942         if (ScalarizationCostPassed == std::numeric_limits<unsigned>::max())
943           ScalarizationCost = getScalarizationOverhead(RetTy, true, false);
944         ScalarCalls = std::max(ScalarCalls, RetTy->getVectorNumElements());
945         ScalarRetTy = RetTy->getScalarType();
946       }
947       SmallVector<Type *, 4> ScalarTys;
948       for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
949         Type *Ty = Tys[i];
950         if (Ty->isVectorTy()) {
951           if (ScalarizationCostPassed == std::numeric_limits<unsigned>::max())
952             ScalarizationCost += getScalarizationOverhead(Ty, false, true);
953           ScalarCalls = std::max(ScalarCalls, Ty->getVectorNumElements());
954           Ty = Ty->getScalarType();
955         }
956         ScalarTys.push_back(Ty);
957       }
958       if (ScalarCalls == 1)
959         return 1; // Return cost of a scalar intrinsic. Assume it to be cheap.
960
961       unsigned ScalarCost = static_cast<T *>(this)->getIntrinsicInstrCost(
962           IID, ScalarRetTy, ScalarTys, FMF);
963
964       return ScalarCalls * ScalarCost + ScalarizationCost;
965     }
966     // Look for intrinsics that can be lowered directly or turned into a scalar
967     // intrinsic call.
968     case Intrinsic::sqrt:
969       ISDs.push_back(ISD::FSQRT);
970       break;
971     case Intrinsic::sin:
972       ISDs.push_back(ISD::FSIN);
973       break;
974     case Intrinsic::cos:
975       ISDs.push_back(ISD::FCOS);
976       break;
977     case Intrinsic::exp:
978       ISDs.push_back(ISD::FEXP);
979       break;
980     case Intrinsic::exp2:
981       ISDs.push_back(ISD::FEXP2);
982       break;
983     case Intrinsic::log:
984       ISDs.push_back(ISD::FLOG);
985       break;
986     case Intrinsic::log10:
987       ISDs.push_back(ISD::FLOG10);
988       break;
989     case Intrinsic::log2:
990       ISDs.push_back(ISD::FLOG2);
991       break;
992     case Intrinsic::fabs:
993       ISDs.push_back(ISD::FABS);
994       break;
995     case Intrinsic::minnum:
996       ISDs.push_back(ISD::FMINNUM);
997       if (FMF.noNaNs())
998         ISDs.push_back(ISD::FMINNAN);
999       break;
1000     case Intrinsic::maxnum:
1001       ISDs.push_back(ISD::FMAXNUM);
1002       if (FMF.noNaNs())
1003         ISDs.push_back(ISD::FMAXNAN);
1004       break;
1005     case Intrinsic::copysign:
1006       ISDs.push_back(ISD::FCOPYSIGN);
1007       break;
1008     case Intrinsic::floor:
1009       ISDs.push_back(ISD::FFLOOR);
1010       break;
1011     case Intrinsic::ceil:
1012       ISDs.push_back(ISD::FCEIL);
1013       break;
1014     case Intrinsic::trunc:
1015       ISDs.push_back(ISD::FTRUNC);
1016       break;
1017     case Intrinsic::nearbyint:
1018       ISDs.push_back(ISD::FNEARBYINT);
1019       break;
1020     case Intrinsic::rint:
1021       ISDs.push_back(ISD::FRINT);
1022       break;
1023     case Intrinsic::round:
1024       ISDs.push_back(ISD::FROUND);
1025       break;
1026     case Intrinsic::pow:
1027       ISDs.push_back(ISD::FPOW);
1028       break;
1029     case Intrinsic::fma:
1030       ISDs.push_back(ISD::FMA);
1031       break;
1032     case Intrinsic::fmuladd:
1033       ISDs.push_back(ISD::FMA);
1034       break;
1035     // FIXME: We should return 0 whenever getIntrinsicCost == TCC_Free.
1036     case Intrinsic::lifetime_start:
1037     case Intrinsic::lifetime_end:
1038     case Intrinsic::sideeffect:
1039       return 0;
1040     case Intrinsic::masked_store:
1041       return static_cast<T *>(this)
1042           ->getMaskedMemoryOpCost(Instruction::Store, Tys[0], 0, 0);
1043     case Intrinsic::masked_load:
1044       return static_cast<T *>(this)
1045           ->getMaskedMemoryOpCost(Instruction::Load, RetTy, 0, 0);
1046     case Intrinsic::ctpop:
1047       ISDs.push_back(ISD::CTPOP);
1048       // In case of legalization use TCC_Expensive. This is cheaper than a
1049       // library call but still not a cheap instruction.
1050       SingleCallCost = TargetTransformInfo::TCC_Expensive;
1051       break;
1052     // FIXME: ctlz, cttz, ...
1053     }
1054
1055     const TargetLoweringBase *TLI = getTLI();
1056     std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, RetTy);
1057
1058     SmallVector<unsigned, 2> LegalCost;
1059     SmallVector<unsigned, 2> CustomCost;
1060     for (unsigned ISD : ISDs) {
1061       if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
1062         if (IID == Intrinsic::fabs && TLI->isFAbsFree(LT.second)) {
1063           return 0;
1064         }
1065
1066         // The operation is legal. Assume it costs 1.
1067         // If the type is split to multiple registers, assume that there is some
1068         // overhead to this.
1069         // TODO: Once we have extract/insert subvector cost we need to use them.
1070         if (LT.first > 1)
1071           LegalCost.push_back(LT.first * 2);
1072         else
1073           LegalCost.push_back(LT.first * 1);
1074       } else if (!TLI->isOperationExpand(ISD, LT.second)) {
1075         // If the operation is custom lowered then assume
1076         // that the code is twice as expensive.
1077         CustomCost.push_back(LT.first * 2);
1078       }
1079     }
1080
1081     auto MinLegalCostI = std::min_element(LegalCost.begin(), LegalCost.end());
1082     if (MinLegalCostI != LegalCost.end())
1083       return *MinLegalCostI;
1084
1085     auto MinCustomCostI = std::min_element(CustomCost.begin(), CustomCost.end());
1086     if (MinCustomCostI != CustomCost.end())
1087       return *MinCustomCostI;
1088
1089     // If we can't lower fmuladd into an FMA estimate the cost as a floating
1090     // point mul followed by an add.
1091     if (IID == Intrinsic::fmuladd)
1092       return static_cast<T *>(this)
1093                  ->getArithmeticInstrCost(BinaryOperator::FMul, RetTy) +
1094              static_cast<T *>(this)
1095                  ->getArithmeticInstrCost(BinaryOperator::FAdd, RetTy);
1096
1097     // Else, assume that we need to scalarize this intrinsic. For math builtins
1098     // this will emit a costly libcall, adding call overhead and spills. Make it
1099     // very expensive.
1100     if (RetTy->isVectorTy()) {
1101       unsigned ScalarizationCost =
1102           ((ScalarizationCostPassed != std::numeric_limits<unsigned>::max())
1103                ? ScalarizationCostPassed
1104                : getScalarizationOverhead(RetTy, true, false));
1105       unsigned ScalarCalls = RetTy->getVectorNumElements();
1106       SmallVector<Type *, 4> ScalarTys;
1107       for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
1108         Type *Ty = Tys[i];
1109         if (Ty->isVectorTy())
1110           Ty = Ty->getScalarType();
1111         ScalarTys.push_back(Ty);
1112       }
1113       unsigned ScalarCost = static_cast<T *>(this)->getIntrinsicInstrCost(
1114           IID, RetTy->getScalarType(), ScalarTys, FMF);
1115       for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
1116         if (Tys[i]->isVectorTy()) {
1117           if (ScalarizationCostPassed == std::numeric_limits<unsigned>::max())
1118             ScalarizationCost += getScalarizationOverhead(Tys[i], false, true);
1119           ScalarCalls = std::max(ScalarCalls, Tys[i]->getVectorNumElements());
1120         }
1121       }
1122
1123       return ScalarCalls * ScalarCost + ScalarizationCost;
1124     }
1125
1126     // This is going to be turned into a library call, make it expensive.
1127     return SingleCallCost;
1128   }
1129
1130   /// \brief Compute a cost of the given call instruction.
1131   ///
1132   /// Compute the cost of calling function F with return type RetTy and
1133   /// argument types Tys. F might be nullptr, in this case the cost of an
1134   /// arbitrary call with the specified signature will be returned.
1135   /// This is used, for instance,  when we estimate call of a vector
1136   /// counterpart of the given function.
1137   /// \param F Called function, might be nullptr.
1138   /// \param RetTy Return value types.
1139   /// \param Tys Argument types.
1140   /// \returns The cost of Call instruction.
1141   unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) {
1142     return 10;
1143   }
1144
1145   unsigned getNumberOfParts(Type *Tp) {
1146     std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(DL, Tp);
1147     return LT.first;
1148   }
1149
1150   unsigned getAddressComputationCost(Type *Ty, ScalarEvolution *,
1151                                      const SCEV *) {
1152     return 0;
1153   }
1154
1155   /// Try to calculate arithmetic and shuffle op costs for reduction operations.
1156   /// We're assuming that reduction operation are performing the following way:
1157   /// 1. Non-pairwise reduction
1158   /// %val1 = shufflevector<n x t> %val, <n x t> %undef,
1159   /// <n x i32> <i32 n/2, i32 n/2 + 1, ..., i32 n, i32 undef, ..., i32 undef>
1160   ///            \----------------v-------------/  \----------v------------/
1161   ///                            n/2 elements               n/2 elements
1162   /// %red1 = op <n x t> %val, <n x t> val1
1163   /// After this operation we have a vector %red1 where only the first n/2
1164   /// elements are meaningful, the second n/2 elements are undefined and can be
1165   /// dropped. All other operations are actually working with the vector of
1166   /// length n/2, not n, though the real vector length is still n.
1167   /// %val2 = shufflevector<n x t> %red1, <n x t> %undef,
1168   /// <n x i32> <i32 n/4, i32 n/4 + 1, ..., i32 n/2, i32 undef, ..., i32 undef>
1169   ///            \----------------v-------------/  \----------v------------/
1170   ///                            n/4 elements               3*n/4 elements
1171   /// %red2 = op <n x t> %red1, <n x t> val2  - working with the vector of
1172   /// length n/2, the resulting vector has length n/4 etc.
1173   /// 2. Pairwise reduction:
1174   /// Everything is the same except for an additional shuffle operation which
1175   /// is used to produce operands for pairwise kind of reductions.
1176   /// %val1 = shufflevector<n x t> %val, <n x t> %undef,
1177   /// <n x i32> <i32 0, i32 2, ..., i32 n-2, i32 undef, ..., i32 undef>
1178   ///            \-------------v----------/  \----------v------------/
1179   ///                   n/2 elements               n/2 elements
1180   /// %val2 = shufflevector<n x t> %val, <n x t> %undef,
1181   /// <n x i32> <i32 1, i32 3, ..., i32 n-1, i32 undef, ..., i32 undef>
1182   ///            \-------------v----------/  \----------v------------/
1183   ///                   n/2 elements               n/2 elements
1184   /// %red1 = op <n x t> %val1, <n x t> val2
1185   /// Again, the operation is performed on <n x t> vector, but the resulting
1186   /// vector %red1 is <n/2 x t> vector.
1187   ///
1188   /// The cost model should take into account that the actual length of the
1189   /// vector is reduced on each iteration.
1190   unsigned getArithmeticReductionCost(unsigned Opcode, Type *Ty,
1191                                       bool IsPairwise) {
1192     assert(Ty->isVectorTy() && "Expect a vector type");
1193     Type *ScalarTy = Ty->getVectorElementType();
1194     unsigned NumVecElts = Ty->getVectorNumElements();
1195     unsigned NumReduxLevels = Log2_32(NumVecElts);
1196     unsigned ArithCost = 0;
1197     unsigned ShuffleCost = 0;
1198     auto *ConcreteTTI = static_cast<T *>(this);
1199     std::pair<unsigned, MVT> LT =
1200         ConcreteTTI->getTLI()->getTypeLegalizationCost(DL, Ty);
1201     unsigned LongVectorCount = 0;
1202     unsigned MVTLen =
1203         LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
1204     while (NumVecElts > MVTLen) {
1205       NumVecElts /= 2;
1206       // Assume the pairwise shuffles add a cost.
1207       ShuffleCost += (IsPairwise + 1) *
1208                      ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1209                                                  NumVecElts, Ty);
1210       ArithCost += ConcreteTTI->getArithmeticInstrCost(Opcode, Ty);
1211       Ty = VectorType::get(ScalarTy, NumVecElts);
1212       ++LongVectorCount;
1213     }
1214     // The minimal length of the vector is limited by the real length of vector
1215     // operations performed on the current platform. That's why several final
1216     // reduction operations are performed on the vectors with the same
1217     // architecture-dependent length.
1218     ShuffleCost += (NumReduxLevels - LongVectorCount) * (IsPairwise + 1) *
1219                    ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1220                                                NumVecElts, Ty);
1221     ArithCost += (NumReduxLevels - LongVectorCount) *
1222                  ConcreteTTI->getArithmeticInstrCost(Opcode, Ty);
1223     return ShuffleCost + ArithCost + getScalarizationOverhead(Ty, false, true);
1224   }
1225
1226   /// Try to calculate op costs for min/max reduction operations.
1227   /// \param CondTy Conditional type for the Select instruction.
1228   unsigned getMinMaxReductionCost(Type *Ty, Type *CondTy, bool IsPairwise,
1229                                   bool) {
1230     assert(Ty->isVectorTy() && "Expect a vector type");
1231     Type *ScalarTy = Ty->getVectorElementType();
1232     Type *ScalarCondTy = CondTy->getVectorElementType();
1233     unsigned NumVecElts = Ty->getVectorNumElements();
1234     unsigned NumReduxLevels = Log2_32(NumVecElts);
1235     unsigned CmpOpcode;
1236     if (Ty->isFPOrFPVectorTy()) {
1237       CmpOpcode = Instruction::FCmp;
1238     } else {
1239       assert(Ty->isIntOrIntVectorTy() &&
1240              "expecting floating point or integer type for min/max reduction");
1241       CmpOpcode = Instruction::ICmp;
1242     }
1243     unsigned MinMaxCost = 0;
1244     unsigned ShuffleCost = 0;
1245     auto *ConcreteTTI = static_cast<T *>(this);
1246     std::pair<unsigned, MVT> LT =
1247         ConcreteTTI->getTLI()->getTypeLegalizationCost(DL, Ty);
1248     unsigned LongVectorCount = 0;
1249     unsigned MVTLen =
1250         LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
1251     while (NumVecElts > MVTLen) {
1252       NumVecElts /= 2;
1253       // Assume the pairwise shuffles add a cost.
1254       ShuffleCost += (IsPairwise + 1) *
1255                      ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1256                                                  NumVecElts, Ty);
1257       MinMaxCost +=
1258           ConcreteTTI->getCmpSelInstrCost(CmpOpcode, Ty, CondTy, nullptr) +
1259           ConcreteTTI->getCmpSelInstrCost(Instruction::Select, Ty, CondTy,
1260                                           nullptr);
1261       Ty = VectorType::get(ScalarTy, NumVecElts);
1262       CondTy = VectorType::get(ScalarCondTy, NumVecElts);
1263       ++LongVectorCount;
1264     }
1265     // The minimal length of the vector is limited by the real length of vector
1266     // operations performed on the current platform. That's why several final
1267     // reduction opertions are perfomed on the vectors with the same
1268     // architecture-dependent length.
1269     ShuffleCost += (NumReduxLevels - LongVectorCount) * (IsPairwise + 1) *
1270                    ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1271                                                NumVecElts, Ty);
1272     MinMaxCost +=
1273         (NumReduxLevels - LongVectorCount) *
1274         (ConcreteTTI->getCmpSelInstrCost(CmpOpcode, Ty, CondTy, nullptr) +
1275          ConcreteTTI->getCmpSelInstrCost(Instruction::Select, Ty, CondTy,
1276                                          nullptr));
1277     // Need 3 extractelement instructions for scalarization + an additional
1278     // scalar select instruction.
1279     return ShuffleCost + MinMaxCost +
1280            3 * getScalarizationOverhead(Ty, /*Insert=*/false,
1281                                         /*Extract=*/true) +
1282            ConcreteTTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
1283                                            ScalarCondTy, nullptr);
1284   }
1285
1286   unsigned getVectorSplitCost() { return 1; }
1287
1288   /// @}
1289 };
1290
1291 /// \brief Concrete BasicTTIImpl that can be used if no further customization
1292 /// is needed.
1293 class BasicTTIImpl : public BasicTTIImplBase<BasicTTIImpl> {
1294   using BaseT = BasicTTIImplBase<BasicTTIImpl>;
1295
1296   friend class BasicTTIImplBase<BasicTTIImpl>;
1297
1298   const TargetSubtargetInfo *ST;
1299   const TargetLoweringBase *TLI;
1300
1301   const TargetSubtargetInfo *getST() const { return ST; }
1302   const TargetLoweringBase *getTLI() const { return TLI; }
1303
1304 public:
1305   explicit BasicTTIImpl(const TargetMachine *ST, const Function &F);
1306 };
1307
1308 } // end namespace llvm
1309
1310 #endif // LLVM_CODEGEN_BASICTTIIMPL_H