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