]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304149, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / include / llvm / Analysis / TargetTransformInfoImpl.h
1 //===- TargetTransformInfoImpl.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 helpers for the implementation of
11 /// a TargetTransformInfo-conforming class.
12 ///
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_ANALYSIS_TARGETTRANSFORMINFOIMPL_H
16 #define LLVM_ANALYSIS_TARGETTRANSFORMINFOIMPL_H
17
18 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
19 #include "llvm/Analysis/TargetTransformInfo.h"
20 #include "llvm/IR/CallSite.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/GetElementPtrTypeIterator.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/IR/Type.h"
26 #include "llvm/Analysis/VectorUtils.h"
27
28 namespace llvm {
29
30 /// \brief Base class for use as a mix-in that aids implementing
31 /// a TargetTransformInfo-compatible class.
32 class TargetTransformInfoImplBase {
33 protected:
34   typedef TargetTransformInfo TTI;
35
36   const DataLayout &DL;
37
38   explicit TargetTransformInfoImplBase(const DataLayout &DL) : DL(DL) {}
39
40 public:
41   // Provide value semantics. MSVC requires that we spell all of these out.
42   TargetTransformInfoImplBase(const TargetTransformInfoImplBase &Arg)
43       : DL(Arg.DL) {}
44   TargetTransformInfoImplBase(TargetTransformInfoImplBase &&Arg) : DL(Arg.DL) {}
45
46   const DataLayout &getDataLayout() const { return DL; }
47
48   unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) {
49     switch (Opcode) {
50     default:
51       // By default, just classify everything as 'basic'.
52       return TTI::TCC_Basic;
53
54     case Instruction::GetElementPtr:
55       llvm_unreachable("Use getGEPCost for GEP operations!");
56
57     case Instruction::BitCast:
58       assert(OpTy && "Cast instructions must provide the operand type");
59       if (Ty == OpTy || (Ty->isPointerTy() && OpTy->isPointerTy()))
60         // Identity and pointer-to-pointer casts are free.
61         return TTI::TCC_Free;
62
63       // Otherwise, the default basic cost is used.
64       return TTI::TCC_Basic;
65
66     case Instruction::FDiv:
67     case Instruction::FRem:
68     case Instruction::SDiv:
69     case Instruction::SRem:
70     case Instruction::UDiv:
71     case Instruction::URem:
72       return TTI::TCC_Expensive;
73
74     case Instruction::IntToPtr: {
75       // An inttoptr cast is free so long as the input is a legal integer type
76       // which doesn't contain values outside the range of a pointer.
77       unsigned OpSize = OpTy->getScalarSizeInBits();
78       if (DL.isLegalInteger(OpSize) &&
79           OpSize <= DL.getPointerTypeSizeInBits(Ty))
80         return TTI::TCC_Free;
81
82       // Otherwise it's not a no-op.
83       return TTI::TCC_Basic;
84     }
85     case Instruction::PtrToInt: {
86       // A ptrtoint cast is free so long as the result is large enough to store
87       // the pointer, and a legal integer type.
88       unsigned DestSize = Ty->getScalarSizeInBits();
89       if (DL.isLegalInteger(DestSize) &&
90           DestSize >= DL.getPointerTypeSizeInBits(OpTy))
91         return TTI::TCC_Free;
92
93       // Otherwise it's not a no-op.
94       return TTI::TCC_Basic;
95     }
96     case Instruction::Trunc:
97       // trunc to a native type is free (assuming the target has compare and
98       // shift-right of the same width).
99       if (DL.isLegalInteger(DL.getTypeSizeInBits(Ty)))
100         return TTI::TCC_Free;
101
102       return TTI::TCC_Basic;
103     }
104   }
105
106   int getGEPCost(Type *PointeeType, const Value *Ptr,
107                  ArrayRef<const Value *> Operands) {
108     // In the basic model, we just assume that all-constant GEPs will be folded
109     // into their uses via addressing modes.
110     for (unsigned Idx = 0, Size = Operands.size(); Idx != Size; ++Idx)
111       if (!isa<Constant>(Operands[Idx]))
112         return TTI::TCC_Basic;
113
114     return TTI::TCC_Free;
115   }
116
117   unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
118                                             unsigned &JTSize) {
119     JTSize = 0;
120     return SI.getNumCases();
121   }
122
123   unsigned getCallCost(FunctionType *FTy, int NumArgs) {
124     assert(FTy && "FunctionType must be provided to this routine.");
125
126     // The target-independent implementation just measures the size of the
127     // function by approximating that each argument will take on average one
128     // instruction to prepare.
129
130     if (NumArgs < 0)
131       // Set the argument number to the number of explicit arguments in the
132       // function.
133       NumArgs = FTy->getNumParams();
134
135     return TTI::TCC_Basic * (NumArgs + 1);
136   }
137
138   unsigned getInliningThresholdMultiplier() { return 1; }
139
140   unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
141                             ArrayRef<Type *> ParamTys) {
142     switch (IID) {
143     default:
144       // Intrinsics rarely (if ever) have normal argument setup constraints.
145       // Model them as having a basic instruction cost.
146       // FIXME: This is wrong for libc intrinsics.
147       return TTI::TCC_Basic;
148
149     case Intrinsic::annotation:
150     case Intrinsic::assume:
151     case Intrinsic::dbg_declare:
152     case Intrinsic::dbg_value:
153     case Intrinsic::invariant_start:
154     case Intrinsic::invariant_end:
155     case Intrinsic::lifetime_start:
156     case Intrinsic::lifetime_end:
157     case Intrinsic::objectsize:
158     case Intrinsic::ptr_annotation:
159     case Intrinsic::var_annotation:
160     case Intrinsic::experimental_gc_result:
161     case Intrinsic::experimental_gc_relocate:
162     case Intrinsic::coro_alloc:
163     case Intrinsic::coro_begin:
164     case Intrinsic::coro_free:
165     case Intrinsic::coro_end:
166     case Intrinsic::coro_frame:
167     case Intrinsic::coro_size:
168     case Intrinsic::coro_suspend:
169     case Intrinsic::coro_param:
170     case Intrinsic::coro_subfn_addr:
171       // These intrinsics don't actually represent code after lowering.
172       return TTI::TCC_Free;
173     }
174   }
175
176   bool hasBranchDivergence() { return false; }
177
178   bool isSourceOfDivergence(const Value *V) { return false; }
179
180   unsigned getFlatAddressSpace () {
181     return -1;
182   }
183
184   bool isLoweredToCall(const Function *F) {
185     // FIXME: These should almost certainly not be handled here, and instead
186     // handled with the help of TLI or the target itself. This was largely
187     // ported from existing analysis heuristics here so that such refactorings
188     // can take place in the future.
189
190     if (F->isIntrinsic())
191       return false;
192
193     if (F->hasLocalLinkage() || !F->hasName())
194       return true;
195
196     StringRef Name = F->getName();
197
198     // These will all likely lower to a single selection DAG node.
199     if (Name == "copysign" || Name == "copysignf" || Name == "copysignl" ||
200         Name == "fabs" || Name == "fabsf" || Name == "fabsl" || Name == "sin" ||
201         Name == "fmin" || Name == "fminf" || Name == "fminl" ||
202         Name == "fmax" || Name == "fmaxf" || Name == "fmaxl" ||
203         Name == "sinf" || Name == "sinl" || Name == "cos" || Name == "cosf" ||
204         Name == "cosl" || Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl")
205       return false;
206
207     // These are all likely to be optimized into something smaller.
208     if (Name == "pow" || Name == "powf" || Name == "powl" || Name == "exp2" ||
209         Name == "exp2l" || Name == "exp2f" || Name == "floor" ||
210         Name == "floorf" || Name == "ceil" || Name == "round" ||
211         Name == "ffs" || Name == "ffsl" || Name == "abs" || Name == "labs" ||
212         Name == "llabs")
213       return false;
214
215     return true;
216   }
217
218   void getUnrollingPreferences(Loop *, TTI::UnrollingPreferences &) {}
219
220   bool isLegalAddImmediate(int64_t Imm) { return false; }
221
222   bool isLegalICmpImmediate(int64_t Imm) { return false; }
223
224   bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
225                              bool HasBaseReg, int64_t Scale,
226                              unsigned AddrSpace) {
227     // Guess that only reg and reg+reg addressing is allowed. This heuristic is
228     // taken from the implementation of LSR.
229     return !BaseGV && BaseOffset == 0 && (Scale == 0 || Scale == 1);
230   }
231
232   bool isLegalMaskedStore(Type *DataType) { return false; }
233
234   bool isLegalMaskedLoad(Type *DataType) { return false; }
235
236   bool isLegalMaskedScatter(Type *DataType) { return false; }
237
238   bool isLegalMaskedGather(Type *DataType) { return false; }
239
240   bool prefersVectorizedAddressing() { return true; }
241
242   int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
243                            bool HasBaseReg, int64_t Scale, unsigned AddrSpace) {
244     // Guess that all legal addressing mode are free.
245     if (isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg,
246                               Scale, AddrSpace))
247       return 0;
248     return -1;
249   }
250
251   bool isFoldableMemAccessOffset(Instruction *I, int64_t Offset) { return true; }
252
253   bool isTruncateFree(Type *Ty1, Type *Ty2) { return false; }
254
255   bool isProfitableToHoist(Instruction *I) { return true; }
256
257   bool isTypeLegal(Type *Ty) { return false; }
258
259   unsigned getJumpBufAlignment() { return 0; }
260
261   unsigned getJumpBufSize() { return 0; }
262
263   bool shouldBuildLookupTables() { return true; }
264   bool shouldBuildLookupTablesForConstant(Constant *C) { return true; }
265
266   unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) {
267     return 0;
268   }
269
270   unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
271                                             unsigned VF) { return 0; }
272
273   bool supportsEfficientVectorElementLoadStore() { return false; }
274
275   bool enableAggressiveInterleaving(bool LoopHasReductions) { return false; }
276
277   bool enableInterleavedAccessVectorization() { return false; }
278
279   bool isFPVectorizationPotentiallyUnsafe() { return false; }
280
281   bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
282                                       unsigned BitWidth,
283                                       unsigned AddressSpace,
284                                       unsigned Alignment,
285                                       bool *Fast) { return false; }
286
287   TTI::PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) {
288     return TTI::PSK_Software;
289   }
290
291   bool haveFastSqrt(Type *Ty) { return false; }
292
293   unsigned getFPOpCost(Type *Ty) { return TargetTransformInfo::TCC_Basic; }
294
295   int getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
296                             Type *Ty) {
297     return 0;
298   }
299
300   unsigned getIntImmCost(const APInt &Imm, Type *Ty) { return TTI::TCC_Basic; }
301
302   unsigned getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
303                          Type *Ty) {
304     return TTI::TCC_Free;
305   }
306
307   unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
308                          Type *Ty) {
309     return TTI::TCC_Free;
310   }
311
312   unsigned getNumberOfRegisters(bool Vector) { return 8; }
313
314   unsigned getRegisterBitWidth(bool Vector) { return 32; }
315
316   unsigned getMinVectorRegisterBitWidth() { return 128; }
317
318   bool
319   shouldConsiderAddressTypePromotion(const Instruction &I,
320                                      bool &AllowPromotionWithoutCommonHeader) {
321     AllowPromotionWithoutCommonHeader = false;
322     return false;
323   }
324
325   unsigned getCacheLineSize() { return 0; }
326
327   unsigned getPrefetchDistance() { return 0; }
328
329   unsigned getMinPrefetchStride() { return 1; }
330
331   unsigned getMaxPrefetchIterationsAhead() { return UINT_MAX; }
332
333   unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
334
335   unsigned getArithmeticInstrCost(unsigned Opcode, Type *Ty,
336                                   TTI::OperandValueKind Opd1Info,
337                                   TTI::OperandValueKind Opd2Info,
338                                   TTI::OperandValueProperties Opd1PropInfo,
339                                   TTI::OperandValueProperties Opd2PropInfo,
340                                   ArrayRef<const Value *> Args) {
341     return 1;
342   }
343
344   unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Ty, int Index,
345                           Type *SubTp) {
346     return 1;
347   }
348
349   unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
350                             const Instruction *I) { return 1; }
351
352   unsigned getExtractWithExtendCost(unsigned Opcode, Type *Dst,
353                                     VectorType *VecTy, unsigned Index) {
354     return 1;
355   }
356
357   unsigned getCFInstrCost(unsigned Opcode) { return 1; }
358
359   unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
360                               const Instruction *I) {
361     return 1;
362   }
363
364   unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
365     return 1;
366   }
367
368   unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
369                            unsigned AddressSpace, const Instruction *I) {
370     return 1;
371   }
372
373   unsigned getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
374                                  unsigned AddressSpace) {
375     return 1;
376   }
377
378   unsigned getGatherScatterOpCost(unsigned Opcode, Type *DataTy, Value *Ptr,
379                                   bool VariableMask,
380                                   unsigned Alignment) {
381     return 1;
382   }
383
384   unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
385                                       unsigned Factor,
386                                       ArrayRef<unsigned> Indices,
387                                       unsigned Alignment,
388                                       unsigned AddressSpace) {
389     return 1;
390   }
391
392   unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
393                                  ArrayRef<Type *> Tys, FastMathFlags FMF,
394                                  unsigned ScalarizationCostPassed) {
395     return 1;
396   }
397   unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
398             ArrayRef<Value *> Args, FastMathFlags FMF, unsigned VF) {
399     return 1;
400   }
401
402   unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) {
403     return 1;
404   }
405
406   unsigned getNumberOfParts(Type *Tp) { return 0; }
407
408   unsigned getAddressComputationCost(Type *Tp, ScalarEvolution *,
409                                      const SCEV *) {
410     return 0; 
411   }
412
413   unsigned getReductionCost(unsigned, Type *, bool) { return 1; }
414
415   unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) { return 0; }
416
417   bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) {
418     return false;
419   }
420
421   Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
422                                            Type *ExpectedType) {
423     return nullptr;
424   }
425
426   bool areInlineCompatible(const Function *Caller,
427                            const Function *Callee) const {
428     return (Caller->getFnAttribute("target-cpu") ==
429             Callee->getFnAttribute("target-cpu")) &&
430            (Caller->getFnAttribute("target-features") ==
431             Callee->getFnAttribute("target-features"));
432   }
433
434   unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const { return 128; }
435
436   bool isLegalToVectorizeLoad(LoadInst *LI) const { return true; }
437
438   bool isLegalToVectorizeStore(StoreInst *SI) const { return true; }
439
440   bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
441                                    unsigned Alignment,
442                                    unsigned AddrSpace) const {
443     return true;
444   }
445
446   bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
447                                     unsigned Alignment,
448                                     unsigned AddrSpace) const {
449     return true;
450   }
451
452   unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
453                                unsigned ChainSizeInBytes,
454                                VectorType *VecTy) const {
455     return VF;
456   }
457
458   unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
459                                 unsigned ChainSizeInBytes,
460                                 VectorType *VecTy) const {
461     return VF;
462   }
463
464   bool useReductionIntrinsic(unsigned Opcode, Type *Ty,
465                              TTI::ReductionFlags Flags) const {
466     return false;
467   }
468
469   bool shouldExpandReduction(const IntrinsicInst *II) const {
470     return true;
471   }
472
473 protected:
474   // Obtain the minimum required size to hold the value (without the sign)
475   // In case of a vector it returns the min required size for one element.
476   unsigned minRequiredElementSize(const Value* Val, bool &isSigned) {
477     if (isa<ConstantDataVector>(Val) || isa<ConstantVector>(Val)) {
478       const auto* VectorValue = cast<Constant>(Val);
479
480       // In case of a vector need to pick the max between the min
481       // required size for each element
482       auto *VT = cast<VectorType>(Val->getType());
483
484       // Assume unsigned elements
485       isSigned = false;
486
487       // The max required size is the total vector width divided by num
488       // of elements in the vector
489       unsigned MaxRequiredSize = VT->getBitWidth() / VT->getNumElements();
490
491       unsigned MinRequiredSize = 0;
492       for(unsigned i = 0, e = VT->getNumElements(); i < e; ++i) {
493         if (auto* IntElement =
494               dyn_cast<ConstantInt>(VectorValue->getAggregateElement(i))) {
495           bool signedElement = IntElement->getValue().isNegative();
496           // Get the element min required size.
497           unsigned ElementMinRequiredSize =
498             IntElement->getValue().getMinSignedBits() - 1;
499           // In case one element is signed then all the vector is signed.
500           isSigned |= signedElement;
501           // Save the max required bit size between all the elements.
502           MinRequiredSize = std::max(MinRequiredSize, ElementMinRequiredSize);
503         }
504         else {
505           // not an int constant element
506           return MaxRequiredSize;
507         }
508       }
509       return MinRequiredSize;
510     }
511
512     if (const auto* CI = dyn_cast<ConstantInt>(Val)) {
513       isSigned = CI->getValue().isNegative();
514       return CI->getValue().getMinSignedBits() - 1;
515     }
516
517     if (const auto* Cast = dyn_cast<SExtInst>(Val)) {
518       isSigned = true;
519       return Cast->getSrcTy()->getScalarSizeInBits() - 1;
520     }
521
522     if (const auto* Cast = dyn_cast<ZExtInst>(Val)) {
523       isSigned = false;
524       return Cast->getSrcTy()->getScalarSizeInBits();
525     }
526
527     isSigned = false;
528     return Val->getType()->getScalarSizeInBits();
529   }
530
531   bool isStridedAccess(const SCEV *Ptr) {
532     return Ptr && isa<SCEVAddRecExpr>(Ptr);
533   }
534
535   const SCEVConstant *getConstantStrideStep(ScalarEvolution *SE,
536                                             const SCEV *Ptr) {
537     if (!isStridedAccess(Ptr))
538       return nullptr;
539     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ptr);
540     return dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(*SE));
541   }
542
543   bool isConstantStridedAccessLessThan(ScalarEvolution *SE, const SCEV *Ptr,
544                                        int64_t MergeDistance) {
545     const SCEVConstant *Step = getConstantStrideStep(SE, Ptr);
546     if (!Step)
547       return false;
548     APInt StrideVal = Step->getAPInt();
549     if (StrideVal.getBitWidth() > 64)
550       return false;
551     // FIXME: need to take absolute value for negtive stride case  
552     return StrideVal.getSExtValue() < MergeDistance;
553   }
554 };
555
556 /// \brief CRTP base class for use as a mix-in that aids implementing
557 /// a TargetTransformInfo-compatible class.
558 template <typename T>
559 class TargetTransformInfoImplCRTPBase : public TargetTransformInfoImplBase {
560 private:
561   typedef TargetTransformInfoImplBase BaseT;
562
563 protected:
564   explicit TargetTransformInfoImplCRTPBase(const DataLayout &DL) : BaseT(DL) {}
565
566 public:
567   using BaseT::getCallCost;
568
569   unsigned getCallCost(const Function *F, int NumArgs) {
570     assert(F && "A concrete function must be provided to this routine.");
571
572     if (NumArgs < 0)
573       // Set the argument number to the number of explicit arguments in the
574       // function.
575       NumArgs = F->arg_size();
576
577     if (Intrinsic::ID IID = F->getIntrinsicID()) {
578       FunctionType *FTy = F->getFunctionType();
579       SmallVector<Type *, 8> ParamTys(FTy->param_begin(), FTy->param_end());
580       return static_cast<T *>(this)
581           ->getIntrinsicCost(IID, FTy->getReturnType(), ParamTys);
582     }
583
584     if (!static_cast<T *>(this)->isLoweredToCall(F))
585       return TTI::TCC_Basic; // Give a basic cost if it will be lowered
586                              // directly.
587
588     return static_cast<T *>(this)->getCallCost(F->getFunctionType(), NumArgs);
589   }
590
591   unsigned getCallCost(const Function *F, ArrayRef<const Value *> Arguments) {
592     // Simply delegate to generic handling of the call.
593     // FIXME: We should use instsimplify or something else to catch calls which
594     // will constant fold with these arguments.
595     return static_cast<T *>(this)->getCallCost(F, Arguments.size());
596   }
597
598   using BaseT::getGEPCost;
599
600   int getGEPCost(Type *PointeeType, const Value *Ptr,
601                  ArrayRef<const Value *> Operands) {
602     const GlobalValue *BaseGV = nullptr;
603     if (Ptr != nullptr) {
604       // TODO: will remove this when pointers have an opaque type.
605       assert(Ptr->getType()->getScalarType()->getPointerElementType() ==
606                  PointeeType &&
607              "explicit pointee type doesn't match operand's pointee type");
608       BaseGV = dyn_cast<GlobalValue>(Ptr->stripPointerCasts());
609     }
610     bool HasBaseReg = (BaseGV == nullptr);
611     int64_t BaseOffset = 0;
612     int64_t Scale = 0;
613
614     auto GTI = gep_type_begin(PointeeType, Operands);
615     Type *TargetType;
616     for (auto I = Operands.begin(); I != Operands.end(); ++I, ++GTI) {
617       TargetType = GTI.getIndexedType();
618       // We assume that the cost of Scalar GEP with constant index and the
619       // cost of Vector GEP with splat constant index are the same.
620       const ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I);
621       if (!ConstIdx)
622         if (auto Splat = getSplatValue(*I))
623           ConstIdx = dyn_cast<ConstantInt>(Splat);
624       if (StructType *STy = GTI.getStructTypeOrNull()) {
625         // For structures the index is always splat or scalar constant
626         assert(ConstIdx && "Unexpected GEP index");
627         uint64_t Field = ConstIdx->getZExtValue();
628         BaseOffset += DL.getStructLayout(STy)->getElementOffset(Field);
629       } else {
630         int64_t ElementSize = DL.getTypeAllocSize(GTI.getIndexedType());
631         if (ConstIdx)
632           BaseOffset += ConstIdx->getSExtValue() * ElementSize;
633         else {
634           // Needs scale register.
635           if (Scale != 0)
636             // No addressing mode takes two scale registers.
637             return TTI::TCC_Basic;
638           Scale = ElementSize;
639         }
640       }
641     }
642
643     // Assumes the address space is 0 when Ptr is nullptr.
644     unsigned AS =
645         (Ptr == nullptr ? 0 : Ptr->getType()->getPointerAddressSpace());
646     if (static_cast<T *>(this)->isLegalAddressingMode(
647             TargetType, const_cast<GlobalValue *>(BaseGV), BaseOffset,
648             HasBaseReg, Scale, AS))
649       return TTI::TCC_Free;
650     return TTI::TCC_Basic;
651   }
652
653   using BaseT::getIntrinsicCost;
654
655   unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
656                             ArrayRef<const Value *> Arguments) {
657     // Delegate to the generic intrinsic handling code. This mostly provides an
658     // opportunity for targets to (for example) special case the cost of
659     // certain intrinsics based on constants used as arguments.
660     SmallVector<Type *, 8> ParamTys;
661     ParamTys.reserve(Arguments.size());
662     for (unsigned Idx = 0, Size = Arguments.size(); Idx != Size; ++Idx)
663       ParamTys.push_back(Arguments[Idx]->getType());
664     return static_cast<T *>(this)->getIntrinsicCost(IID, RetTy, ParamTys);
665   }
666
667   unsigned getUserCost(const User *U) {
668     if (isa<PHINode>(U))
669       return TTI::TCC_Free; // Model all PHI nodes as free.
670
671     if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
672       SmallVector<Value *, 4> Indices(GEP->idx_begin(), GEP->idx_end());
673       return static_cast<T *>(this)->getGEPCost(
674           GEP->getSourceElementType(), GEP->getPointerOperand(), Indices);
675     }
676
677     if (auto CS = ImmutableCallSite(U)) {
678       const Function *F = CS.getCalledFunction();
679       if (!F) {
680         // Just use the called value type.
681         Type *FTy = CS.getCalledValue()->getType()->getPointerElementType();
682         return static_cast<T *>(this)
683             ->getCallCost(cast<FunctionType>(FTy), CS.arg_size());
684       }
685
686       SmallVector<const Value *, 8> Arguments(CS.arg_begin(), CS.arg_end());
687       return static_cast<T *>(this)->getCallCost(F, Arguments);
688     }
689
690     if (const CastInst *CI = dyn_cast<CastInst>(U)) {
691       // Result of a cmp instruction is often extended (to be used by other
692       // cmp instructions, logical or return instructions). These are usually
693       // nop on most sane targets.
694       if (isa<CmpInst>(CI->getOperand(0)))
695         return TTI::TCC_Free;
696     }
697
698     return static_cast<T *>(this)->getOperationCost(
699         Operator::getOpcode(U), U->getType(),
700         U->getNumOperands() == 1 ? U->getOperand(0)->getType() : nullptr);
701   }
702 };
703 }
704
705 #endif