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