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