Revert r240137 (Fixed/added namespace ending comments using clang-tidy. NFC)
[oota-llvm.git] / 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 the cost overhead of SK_Alternate shuffle.
64   unsigned getAltShuffleOverhead(Type *Ty) {
65     assert(Ty->isVectorTy() && "Can only shuffle vectors");
66     unsigned Cost = 0;
67     // Shuffle cost is equal to the cost of extracting element from its argument
68     // plus the cost of inserting them onto the result vector.
69
70     // e.g. <4 x float> has a mask of <0,5,2,7> i.e we need to extract from
71     // index 0 of first vector, index 1 of second vector,index 2 of first
72     // vector and finally index 3 of second vector and insert them at index
73     // <0,1,2,3> of result vector.
74     for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
75       Cost += static_cast<T *>(this)
76                   ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
77       Cost += static_cast<T *>(this)
78                   ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
79     }
80     return Cost;
81   }
82
83   /// \brief Local query method delegates up to T which *must* implement this!
84   const TargetSubtargetInfo *getST() const {
85     return static_cast<const T *>(this)->getST();
86   }
87
88   /// \brief Local query method delegates up to T which *must* implement this!
89   const TargetLoweringBase *getTLI() const {
90     return static_cast<const T *>(this)->getTLI();
91   }
92
93 protected:
94   explicit BasicTTIImplBase(const TargetMachine *TM)
95       : BaseT(TM->getDataLayout()) {}
96
97 public:
98   // Provide value semantics. MSVC requires that we spell all of these out.
99   BasicTTIImplBase(const BasicTTIImplBase &Arg)
100       : BaseT(static_cast<const BaseT &>(Arg)) {}
101   BasicTTIImplBase(BasicTTIImplBase &&Arg)
102       : BaseT(std::move(static_cast<BaseT &>(Arg))) {}
103   BasicTTIImplBase &operator=(const BasicTTIImplBase &RHS) {
104     BaseT::operator=(static_cast<const BaseT &>(RHS));
105     return *this;
106   }
107   BasicTTIImplBase &operator=(BasicTTIImplBase &&RHS) {
108     BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
109     return *this;
110   }
111
112   /// \name Scalar TTI Implementations
113   /// @{
114
115   bool hasBranchDivergence() { return false; }
116
117   bool isSourceOfDivergence(const Value *V) { return false; }
118
119   bool isLegalAddImmediate(int64_t imm) {
120     return getTLI()->isLegalAddImmediate(imm);
121   }
122
123   bool isLegalICmpImmediate(int64_t imm) {
124     return getTLI()->isLegalICmpImmediate(imm);
125   }
126
127   bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
128                              bool HasBaseReg, int64_t Scale,
129                              unsigned AddrSpace) {
130     TargetLoweringBase::AddrMode AM;
131     AM.BaseGV = BaseGV;
132     AM.BaseOffs = BaseOffset;
133     AM.HasBaseReg = HasBaseReg;
134     AM.Scale = Scale;
135     return getTLI()->isLegalAddressingMode(AM, Ty, AddrSpace);
136   }
137
138   int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
139                            bool HasBaseReg, int64_t Scale, unsigned AddrSpace) {
140     TargetLoweringBase::AddrMode AM;
141     AM.BaseGV = BaseGV;
142     AM.BaseOffs = BaseOffset;
143     AM.HasBaseReg = HasBaseReg;
144     AM.Scale = Scale;
145     return getTLI()->getScalingFactorCost(AM, Ty, AddrSpace);
146   }
147
148   bool isTruncateFree(Type *Ty1, Type *Ty2) {
149     return getTLI()->isTruncateFree(Ty1, Ty2);
150   }
151
152   bool isProfitableToHoist(Instruction *I) {
153     return getTLI()->isProfitableToHoist(I);
154   }
155
156   bool isTypeLegal(Type *Ty) {
157     EVT VT = getTLI()->getValueType(Ty);
158     return getTLI()->isTypeLegal(VT);
159   }
160
161   unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
162                             ArrayRef<const Value *> Arguments) {
163     return BaseT::getIntrinsicCost(IID, RetTy, Arguments);
164   }
165
166   unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
167                             ArrayRef<Type *> ParamTys) {
168     if (IID == Intrinsic::cttz) {
169       if (getTLI()->isCheapToSpeculateCttz())
170         return TargetTransformInfo::TCC_Basic;
171       return TargetTransformInfo::TCC_Expensive;
172     }
173
174     if (IID == Intrinsic::ctlz) {
175        if (getTLI()->isCheapToSpeculateCtlz())
176         return TargetTransformInfo::TCC_Basic;
177       return TargetTransformInfo::TCC_Expensive;
178     }
179
180     return BaseT::getIntrinsicCost(IID, RetTy, ParamTys);
181   }
182
183   unsigned getJumpBufAlignment() { return getTLI()->getJumpBufAlignment(); }
184
185   unsigned getJumpBufSize() { return getTLI()->getJumpBufSize(); }
186
187   bool shouldBuildLookupTables() {
188     const TargetLoweringBase *TLI = getTLI();
189     return TLI->isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
190            TLI->isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
191   }
192
193   bool haveFastSqrt(Type *Ty) {
194     const TargetLoweringBase *TLI = getTLI();
195     EVT VT = TLI->getValueType(Ty);
196     return TLI->isTypeLegal(VT) &&
197            TLI->isOperationLegalOrCustom(ISD::FSQRT, VT);
198   }
199
200   unsigned getFPOpCost(Type *Ty) {
201     // By default, FP instructions are no more expensive since they are
202     // implemented in HW.  Target specific TTI can override this.
203     return TargetTransformInfo::TCC_Basic;
204   }
205
206   unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) {
207     const TargetLoweringBase *TLI = getTLI();
208     switch (Opcode) {
209     default: break;
210     case Instruction::Trunc: {
211       if (TLI->isTruncateFree(OpTy, Ty))
212         return TargetTransformInfo::TCC_Free;
213       return TargetTransformInfo::TCC_Basic;
214     }
215     case Instruction::ZExt: {
216       if (TLI->isZExtFree(OpTy, Ty))
217         return TargetTransformInfo::TCC_Free;
218       return TargetTransformInfo::TCC_Basic;
219     }
220     }
221
222     return BaseT::getOperationCost(Opcode, Ty, OpTy);
223   }
224
225   void getUnrollingPreferences(Loop *L, TTI::UnrollingPreferences &UP) {
226     // This unrolling functionality is target independent, but to provide some
227     // motivation for its intended use, for x86:
228
229     // According to the Intel 64 and IA-32 Architectures Optimization Reference
230     // Manual, Intel Core models and later have a loop stream detector (and
231     // associated uop queue) that can benefit from partial unrolling.
232     // The relevant requirements are:
233     //  - The loop must have no more than 4 (8 for Nehalem and later) branches
234     //    taken, and none of them may be calls.
235     //  - The loop can have no more than 18 (28 for Nehalem and later) uops.
236
237     // According to the Software Optimization Guide for AMD Family 15h
238     // Processors, models 30h-4fh (Steamroller and later) have a loop predictor
239     // and loop buffer which can benefit from partial unrolling.
240     // The relevant requirements are:
241     //  - The loop must have fewer than 16 branches
242     //  - The loop must have less than 40 uops in all executed loop branches
243
244     // The number of taken branches in a loop is hard to estimate here, and
245     // benchmarking has revealed that it is better not to be conservative when
246     // estimating the branch count. As a result, we'll ignore the branch limits
247     // until someone finds a case where it matters in practice.
248
249     unsigned MaxOps;
250     const TargetSubtargetInfo *ST = getST();
251     if (PartialUnrollingThreshold.getNumOccurrences() > 0)
252       MaxOps = PartialUnrollingThreshold;
253     else if (ST->getSchedModel().LoopMicroOpBufferSize > 0)
254       MaxOps = ST->getSchedModel().LoopMicroOpBufferSize;
255     else
256       return;
257
258     // Scan the loop: don't unroll loops with calls.
259     for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
260          ++I) {
261       BasicBlock *BB = *I;
262
263       for (BasicBlock::iterator J = BB->begin(), JE = BB->end(); J != JE; ++J)
264         if (isa<CallInst>(J) || isa<InvokeInst>(J)) {
265           ImmutableCallSite CS(J);
266           if (const Function *F = CS.getCalledFunction()) {
267             if (!static_cast<T *>(this)->isLoweredToCall(F))
268               continue;
269           }
270
271           return;
272         }
273     }
274
275     // Enable runtime and partial unrolling up to the specified size.
276     UP.Partial = UP.Runtime = true;
277     UP.PartialThreshold = UP.PartialOptSizeThreshold = MaxOps;
278   }
279
280   /// @}
281
282   /// \name Vector TTI Implementations
283   /// @{
284
285   unsigned getNumberOfRegisters(bool Vector) { return 1; }
286
287   unsigned getRegisterBitWidth(bool Vector) { return 32; }
288
289   unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
290
291   unsigned getArithmeticInstrCost(
292       unsigned Opcode, Type *Ty,
293       TTI::OperandValueKind Opd1Info = TTI::OK_AnyValue,
294       TTI::OperandValueKind Opd2Info = TTI::OK_AnyValue,
295       TTI::OperandValueProperties Opd1PropInfo = TTI::OP_None,
296       TTI::OperandValueProperties Opd2PropInfo = TTI::OP_None) {
297     // Check if any of the operands are vector operands.
298     const TargetLoweringBase *TLI = getTLI();
299     int ISD = TLI->InstructionOpcodeToISD(Opcode);
300     assert(ISD && "Invalid opcode");
301
302     std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(Ty);
303
304     bool IsFloat = Ty->getScalarType()->isFloatingPointTy();
305     // Assume that floating point arithmetic operations cost twice as much as
306     // integer operations.
307     unsigned OpCost = (IsFloat ? 2 : 1);
308
309     if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
310       // The operation is legal. Assume it costs 1.
311       // If the type is split to multiple registers, assume that there is some
312       // overhead to this.
313       // TODO: Once we have extract/insert subvector cost we need to use them.
314       if (LT.first > 1)
315         return LT.first * 2 * OpCost;
316       return LT.first * 1 * OpCost;
317     }
318
319     if (!TLI->isOperationExpand(ISD, LT.second)) {
320       // If the operation is custom lowered then assume
321       // thare the code is twice as expensive.
322       return LT.first * 2 * OpCost;
323     }
324
325     // Else, assume that we need to scalarize this op.
326     if (Ty->isVectorTy()) {
327       unsigned Num = Ty->getVectorNumElements();
328       unsigned Cost = static_cast<T *>(this)
329                           ->getArithmeticInstrCost(Opcode, Ty->getScalarType());
330       // return the cost of multiple scalar invocation plus the cost of
331       // inserting
332       // and extracting the values.
333       return getScalarizationOverhead(Ty, true, true) + Num * Cost;
334     }
335
336     // We don't know anything about this scalar instruction.
337     return OpCost;
338   }
339
340   unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
341                           Type *SubTp) {
342     if (Kind == TTI::SK_Alternate) {
343       return getAltShuffleOverhead(Tp);
344     }
345     return 1;
346   }
347
348   unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) {
349     const TargetLoweringBase *TLI = getTLI();
350     int ISD = TLI->InstructionOpcodeToISD(Opcode);
351     assert(ISD && "Invalid opcode");
352
353     std::pair<unsigned, MVT> SrcLT = TLI->getTypeLegalizationCost(Src);
354     std::pair<unsigned, MVT> DstLT = TLI->getTypeLegalizationCost(Dst);
355
356     // Check for NOOP conversions.
357     if (SrcLT.first == DstLT.first &&
358         SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
359
360       // Bitcast between types that are legalized to the same type are free.
361       if (Opcode == Instruction::BitCast || Opcode == Instruction::Trunc)
362         return 0;
363     }
364
365     if (Opcode == Instruction::Trunc &&
366         TLI->isTruncateFree(SrcLT.second, DstLT.second))
367       return 0;
368
369     if (Opcode == Instruction::ZExt &&
370         TLI->isZExtFree(SrcLT.second, DstLT.second))
371       return 0;
372
373     // If the cast is marked as legal (or promote) then assume low cost.
374     if (SrcLT.first == DstLT.first &&
375         TLI->isOperationLegalOrPromote(ISD, DstLT.second))
376       return 1;
377
378     // Handle scalar conversions.
379     if (!Src->isVectorTy() && !Dst->isVectorTy()) {
380
381       // Scalar bitcasts are usually free.
382       if (Opcode == Instruction::BitCast)
383         return 0;
384
385       // Just check the op cost. If the operation is legal then assume it costs
386       // 1.
387       if (!TLI->isOperationExpand(ISD, DstLT.second))
388         return 1;
389
390       // Assume that illegal scalar instruction are expensive.
391       return 4;
392     }
393
394     // Check vector-to-vector casts.
395     if (Dst->isVectorTy() && Src->isVectorTy()) {
396
397       // If the cast is between same-sized registers, then the check is simple.
398       if (SrcLT.first == DstLT.first &&
399           SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
400
401         // Assume that Zext is done using AND.
402         if (Opcode == Instruction::ZExt)
403           return 1;
404
405         // Assume that sext is done using SHL and SRA.
406         if (Opcode == Instruction::SExt)
407           return 2;
408
409         // Just check the op cost. If the operation is legal then assume it
410         // costs
411         // 1 and multiply by the type-legalization overhead.
412         if (!TLI->isOperationExpand(ISD, DstLT.second))
413           return SrcLT.first * 1;
414       }
415
416       // If we are converting vectors and the operation is illegal, or
417       // if the vectors are legalized to different types, estimate the
418       // scalarization costs.
419       unsigned Num = Dst->getVectorNumElements();
420       unsigned Cost = static_cast<T *>(this)->getCastInstrCost(
421           Opcode, Dst->getScalarType(), Src->getScalarType());
422
423       // Return the cost of multiple scalar invocation plus the cost of
424       // inserting and extracting the values.
425       return getScalarizationOverhead(Dst, true, true) + Num * Cost;
426     }
427
428     // We already handled vector-to-vector and scalar-to-scalar conversions.
429     // This
430     // is where we handle bitcast between vectors and scalars. We need to assume
431     //  that the conversion is scalarized in one way or another.
432     if (Opcode == Instruction::BitCast)
433       // Illegal bitcasts are done by storing and loading from a stack slot.
434       return (Src->isVectorTy() ? getScalarizationOverhead(Src, false, true)
435                                 : 0) +
436              (Dst->isVectorTy() ? getScalarizationOverhead(Dst, true, false)
437                                 : 0);
438
439     llvm_unreachable("Unhandled cast");
440   }
441
442   unsigned getCFInstrCost(unsigned Opcode) {
443     // Branches are assumed to be predicted.
444     return 0;
445   }
446
447   unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy) {
448     const TargetLoweringBase *TLI = getTLI();
449     int ISD = TLI->InstructionOpcodeToISD(Opcode);
450     assert(ISD && "Invalid opcode");
451
452     // Selects on vectors are actually vector selects.
453     if (ISD == ISD::SELECT) {
454       assert(CondTy && "CondTy must exist");
455       if (CondTy->isVectorTy())
456         ISD = ISD::VSELECT;
457     }
458
459     std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(ValTy);
460
461     if (!(ValTy->isVectorTy() && !LT.second.isVector()) &&
462         !TLI->isOperationExpand(ISD, LT.second)) {
463       // The operation is legal. Assume it costs 1. Multiply
464       // by the type-legalization overhead.
465       return LT.first * 1;
466     }
467
468     // Otherwise, assume that the cast is scalarized.
469     if (ValTy->isVectorTy()) {
470       unsigned Num = ValTy->getVectorNumElements();
471       if (CondTy)
472         CondTy = CondTy->getScalarType();
473       unsigned Cost = static_cast<T *>(this)->getCmpSelInstrCost(
474           Opcode, ValTy->getScalarType(), CondTy);
475
476       // Return the cost of multiple scalar invocation plus the cost of
477       // inserting
478       // and extracting the values.
479       return getScalarizationOverhead(ValTy, true, false) + Num * Cost;
480     }
481
482     // Unknown scalar opcode.
483     return 1;
484   }
485
486   unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
487     std::pair<unsigned, MVT> LT =
488         getTLI()->getTypeLegalizationCost(Val->getScalarType());
489
490     return LT.first;
491   }
492
493   unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
494                            unsigned AddressSpace) {
495     assert(!Src->isVoidTy() && "Invalid type");
496     std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(Src);
497
498     // Assuming that all loads of legal types cost 1.
499     unsigned Cost = LT.first;
500
501     if (Src->isVectorTy() &&
502         Src->getPrimitiveSizeInBits() < LT.second.getSizeInBits()) {
503       // This is a vector load that legalizes to a larger type than the vector
504       // itself. Unless the corresponding extending load or truncating store is
505       // legal, then this will scalarize.
506       TargetLowering::LegalizeAction LA = TargetLowering::Expand;
507       EVT MemVT = getTLI()->getValueType(Src, true);
508       if (MemVT.isSimple() && MemVT != MVT::Other) {
509         if (Opcode == Instruction::Store)
510           LA = getTLI()->getTruncStoreAction(LT.second, MemVT.getSimpleVT());
511         else
512           LA = getTLI()->getLoadExtAction(ISD::EXTLOAD, LT.second, MemVT);
513       }
514
515       if (LA != TargetLowering::Legal && LA != TargetLowering::Custom) {
516         // This is a vector load/store for some illegal type that is scalarized.
517         // We must account for the cost of building or decomposing the vector.
518         Cost += getScalarizationOverhead(Src, Opcode != Instruction::Store,
519                                          Opcode == Instruction::Store);
520       }
521     }
522
523     return Cost;
524   }
525
526   unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
527                                       unsigned Factor,
528                                       ArrayRef<unsigned> Indices,
529                                       unsigned Alignment,
530                                       unsigned AddressSpace) {
531     VectorType *VT = dyn_cast<VectorType>(VecTy);
532     assert(VT && "Expect a vector type for interleaved memory op");
533
534     unsigned NumElts = VT->getNumElements();
535     assert(Factor > 1 && NumElts % Factor == 0 && "Invalid interleave factor");
536
537     unsigned NumSubElts = NumElts / Factor;
538     VectorType *SubVT = VectorType::get(VT->getElementType(), NumSubElts);
539
540     // Firstly, the cost of load/store operation.
541     unsigned Cost = getMemoryOpCost(Opcode, VecTy, Alignment, AddressSpace);
542
543     // Then plus the cost of interleave operation.
544     if (Opcode == Instruction::Load) {
545       // The interleave cost is similar to extract sub vectors' elements
546       // from the wide vector, and insert them into sub vectors.
547       //
548       // E.g. An interleaved load of factor 2 (with one member of index 0):
549       //      %vec = load <8 x i32>, <8 x i32>* %ptr
550       //      %v0 = shuffle %vec, undef, <0, 2, 4, 6>         ; Index 0
551       // The cost is estimated as extract elements at 0, 2, 4, 6 from the
552       // <8 x i32> vector and insert them into a <4 x i32> vector.
553
554       assert(Indices.size() <= Factor &&
555              "Interleaved memory op has too many members");
556       for (unsigned Index : Indices) {
557         assert(Index < Factor && "Invalid index for interleaved memory op");
558
559         // Extract elements from loaded vector for each sub vector.
560         for (unsigned i = 0; i < NumSubElts; i++)
561           Cost += getVectorInstrCost(Instruction::ExtractElement, VT,
562                                      Index + i * Factor);
563       }
564
565       unsigned InsSubCost = 0;
566       for (unsigned i = 0; i < NumSubElts; i++)
567         InsSubCost += getVectorInstrCost(Instruction::InsertElement, SubVT, i);
568
569       Cost += Indices.size() * InsSubCost;
570     } else {
571       // The interleave cost is extract all elements from sub vectors, and
572       // insert them into the wide vector.
573       //
574       // E.g. An interleaved store of factor 2:
575       //      %v0_v1 = shuffle %v0, %v1, <0, 4, 1, 5, 2, 6, 3, 7>
576       //      store <8 x i32> %interleaved.vec, <8 x i32>* %ptr
577       // The cost is estimated as extract all elements from both <4 x i32>
578       // vectors and insert into the <8 x i32> vector.
579
580       unsigned ExtSubCost = 0;
581       for (unsigned i = 0; i < NumSubElts; i++)
582         ExtSubCost += getVectorInstrCost(Instruction::ExtractElement, SubVT, i);
583
584       Cost += Factor * ExtSubCost;
585
586       for (unsigned i = 0; i < NumElts; i++)
587         Cost += getVectorInstrCost(Instruction::InsertElement, VT, i);
588     }
589
590     return Cost;
591   }
592
593   unsigned getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
594                                  ArrayRef<Type *> Tys) {
595     unsigned ISD = 0;
596     switch (IID) {
597     default: {
598       // Assume that we need to scalarize this intrinsic.
599       unsigned ScalarizationCost = 0;
600       unsigned ScalarCalls = 1;
601       Type *ScalarRetTy = RetTy;
602       if (RetTy->isVectorTy()) {
603         ScalarizationCost = getScalarizationOverhead(RetTy, true, false);
604         ScalarCalls = std::max(ScalarCalls, RetTy->getVectorNumElements());
605         ScalarRetTy = RetTy->getScalarType();
606       }
607       SmallVector<Type *, 4> ScalarTys;
608       for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
609         Type *Ty = Tys[i];
610         if (Ty->isVectorTy()) {
611           ScalarizationCost += getScalarizationOverhead(Ty, false, true);
612           ScalarCalls = std::max(ScalarCalls, Ty->getVectorNumElements());
613           Ty = Ty->getScalarType();
614         }
615         ScalarTys.push_back(Ty);
616       }
617       if (ScalarCalls == 1)
618         return 1; // Return cost of a scalar intrinsic. Assume it to be cheap.
619
620       unsigned ScalarCost = static_cast<T *>(this)->getIntrinsicInstrCost(
621           IID, ScalarRetTy, ScalarTys);
622
623       return ScalarCalls * ScalarCost + ScalarizationCost;
624     }
625     // Look for intrinsics that can be lowered directly or turned into a scalar
626     // intrinsic call.
627     case Intrinsic::sqrt:
628       ISD = ISD::FSQRT;
629       break;
630     case Intrinsic::sin:
631       ISD = ISD::FSIN;
632       break;
633     case Intrinsic::cos:
634       ISD = ISD::FCOS;
635       break;
636     case Intrinsic::exp:
637       ISD = ISD::FEXP;
638       break;
639     case Intrinsic::exp2:
640       ISD = ISD::FEXP2;
641       break;
642     case Intrinsic::log:
643       ISD = ISD::FLOG;
644       break;
645     case Intrinsic::log10:
646       ISD = ISD::FLOG10;
647       break;
648     case Intrinsic::log2:
649       ISD = ISD::FLOG2;
650       break;
651     case Intrinsic::fabs:
652       ISD = ISD::FABS;
653       break;
654     case Intrinsic::minnum:
655       ISD = ISD::FMINNUM;
656       break;
657     case Intrinsic::maxnum:
658       ISD = ISD::FMAXNUM;
659       break;
660     case Intrinsic::copysign:
661       ISD = ISD::FCOPYSIGN;
662       break;
663     case Intrinsic::floor:
664       ISD = ISD::FFLOOR;
665       break;
666     case Intrinsic::ceil:
667       ISD = ISD::FCEIL;
668       break;
669     case Intrinsic::trunc:
670       ISD = ISD::FTRUNC;
671       break;
672     case Intrinsic::nearbyint:
673       ISD = ISD::FNEARBYINT;
674       break;
675     case Intrinsic::rint:
676       ISD = ISD::FRINT;
677       break;
678     case Intrinsic::round:
679       ISD = ISD::FROUND;
680       break;
681     case Intrinsic::pow:
682       ISD = ISD::FPOW;
683       break;
684     case Intrinsic::fma:
685       ISD = ISD::FMA;
686       break;
687     case Intrinsic::fmuladd:
688       ISD = ISD::FMA;
689       break;
690     // FIXME: We should return 0 whenever getIntrinsicCost == TCC_Free.
691     case Intrinsic::lifetime_start:
692     case Intrinsic::lifetime_end:
693       return 0;
694     case Intrinsic::masked_store:
695       return static_cast<T *>(this)
696           ->getMaskedMemoryOpCost(Instruction::Store, Tys[0], 0, 0);
697     case Intrinsic::masked_load:
698       return static_cast<T *>(this)
699           ->getMaskedMemoryOpCost(Instruction::Load, RetTy, 0, 0);
700     }
701
702     const TargetLoweringBase *TLI = getTLI();
703     std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(RetTy);
704
705     if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
706       // The operation is legal. Assume it costs 1.
707       // If the type is split to multiple registers, assume that there is some
708       // overhead to this.
709       // TODO: Once we have extract/insert subvector cost we need to use them.
710       if (LT.first > 1)
711         return LT.first * 2;
712       return LT.first * 1;
713     }
714
715     if (!TLI->isOperationExpand(ISD, LT.second)) {
716       // If the operation is custom lowered then assume
717       // thare the code is twice as expensive.
718       return LT.first * 2;
719     }
720
721     // If we can't lower fmuladd into an FMA estimate the cost as a floating
722     // point mul followed by an add.
723     if (IID == Intrinsic::fmuladd)
724       return static_cast<T *>(this)
725                  ->getArithmeticInstrCost(BinaryOperator::FMul, RetTy) +
726              static_cast<T *>(this)
727                  ->getArithmeticInstrCost(BinaryOperator::FAdd, RetTy);
728
729     // Else, assume that we need to scalarize this intrinsic. For math builtins
730     // this will emit a costly libcall, adding call overhead and spills. Make it
731     // very expensive.
732     if (RetTy->isVectorTy()) {
733       unsigned ScalarizationCost = getScalarizationOverhead(RetTy, true, false);
734       unsigned ScalarCalls = RetTy->getVectorNumElements();
735       SmallVector<Type *, 4> ScalarTys;
736       for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
737         Type *Ty = Tys[i];
738         if (Ty->isVectorTy())
739           Ty = Ty->getScalarType();
740         ScalarTys.push_back(Ty);
741       }
742       unsigned ScalarCost = static_cast<T *>(this)->getIntrinsicInstrCost(
743           IID, RetTy->getScalarType(), ScalarTys);
744       for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
745         if (Tys[i]->isVectorTy()) {
746           ScalarizationCost += getScalarizationOverhead(Tys[i], false, true);
747           ScalarCalls = std::max(ScalarCalls, Tys[i]->getVectorNumElements());
748         }
749       }
750
751       return ScalarCalls * ScalarCost + ScalarizationCost;
752     }
753
754     // This is going to be turned into a library call, make it expensive.
755     return 10;
756   }
757
758   /// \brief Compute a cost of the given call instruction.
759   ///
760   /// Compute the cost of calling function F with return type RetTy and
761   /// argument types Tys. F might be nullptr, in this case the cost of an
762   /// arbitrary call with the specified signature will be returned.
763   /// This is used, for instance,  when we estimate call of a vector
764   /// counterpart of the given function.
765   /// \param F Called function, might be nullptr.
766   /// \param RetTy Return value types.
767   /// \param Tys Argument types.
768   /// \returns The cost of Call instruction.
769   unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) {
770     return 10;
771   }
772
773   unsigned getNumberOfParts(Type *Tp) {
774     std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(Tp);
775     return LT.first;
776   }
777
778   unsigned getAddressComputationCost(Type *Ty, bool IsComplex) { return 0; }
779
780   unsigned getReductionCost(unsigned Opcode, Type *Ty, bool IsPairwise) {
781     assert(Ty->isVectorTy() && "Expect a vector type");
782     unsigned NumVecElts = Ty->getVectorNumElements();
783     unsigned NumReduxLevels = Log2_32(NumVecElts);
784     unsigned ArithCost =
785         NumReduxLevels *
786         static_cast<T *>(this)->getArithmeticInstrCost(Opcode, Ty);
787     // Assume the pairwise shuffles add a cost.
788     unsigned ShuffleCost =
789         NumReduxLevels * (IsPairwise + 1) *
790         static_cast<T *>(this)
791             ->getShuffleCost(TTI::SK_ExtractSubvector, Ty, NumVecElts / 2, Ty);
792     return ShuffleCost + ArithCost + getScalarizationOverhead(Ty, false, true);
793   }
794
795   /// @}
796 };
797
798 /// \brief Concrete BasicTTIImpl that can be used if no further customization
799 /// is needed.
800 class BasicTTIImpl : public BasicTTIImplBase<BasicTTIImpl> {
801   typedef BasicTTIImplBase<BasicTTIImpl> BaseT;
802   friend class BasicTTIImplBase<BasicTTIImpl>;
803
804   const TargetSubtargetInfo *ST;
805   const TargetLoweringBase *TLI;
806
807   const TargetSubtargetInfo *getST() const { return ST; }
808   const TargetLoweringBase *getTLI() const { return TLI; }
809
810 public:
811   explicit BasicTTIImpl(const TargetMachine *ST, Function &F);
812
813   // Provide value semantics. MSVC requires that we spell all of these out.
814   BasicTTIImpl(const BasicTTIImpl &Arg)
815       : BaseT(static_cast<const BaseT &>(Arg)), ST(Arg.ST), TLI(Arg.TLI) {}
816   BasicTTIImpl(BasicTTIImpl &&Arg)
817       : BaseT(std::move(static_cast<BaseT &>(Arg))), ST(std::move(Arg.ST)),
818         TLI(std::move(Arg.TLI)) {}
819   BasicTTIImpl &operator=(const BasicTTIImpl &RHS) {
820     BaseT::operator=(static_cast<const BaseT &>(RHS));
821     ST = RHS.ST;
822     TLI = RHS.TLI;
823     return *this;
824   }
825   BasicTTIImpl &operator=(BasicTTIImpl &&RHS) {
826     BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
827     ST = std::move(RHS.ST);
828     TLI = std::move(RHS.TLI);
829     return *this;
830   }
831 };
832
833 }
834
835 #endif