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