]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304460, 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 expandMemCmp(Instruction *I, unsigned &MaxLoadSize) { return false; }
278
279   bool enableInterleavedAccessVectorization() { return false; }
280
281   bool isFPVectorizationPotentiallyUnsafe() { return false; }
282
283   bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
284                                       unsigned BitWidth,
285                                       unsigned AddressSpace,
286                                       unsigned Alignment,
287                                       bool *Fast) { return false; }
288
289   TTI::PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) {
290     return TTI::PSK_Software;
291   }
292
293   bool haveFastSqrt(Type *Ty) { return false; }
294
295   unsigned getFPOpCost(Type *Ty) { return TargetTransformInfo::TCC_Basic; }
296
297   int getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
298                             Type *Ty) {
299     return 0;
300   }
301
302   unsigned getIntImmCost(const APInt &Imm, Type *Ty) { return TTI::TCC_Basic; }
303
304   unsigned getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
305                          Type *Ty) {
306     return TTI::TCC_Free;
307   }
308
309   unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
310                          Type *Ty) {
311     return TTI::TCC_Free;
312   }
313
314   unsigned getNumberOfRegisters(bool Vector) { return 8; }
315
316   unsigned getRegisterBitWidth(bool Vector) { return 32; }
317
318   unsigned getMinVectorRegisterBitWidth() { return 128; }
319
320   bool
321   shouldConsiderAddressTypePromotion(const Instruction &I,
322                                      bool &AllowPromotionWithoutCommonHeader) {
323     AllowPromotionWithoutCommonHeader = false;
324     return false;
325   }
326
327   unsigned getCacheLineSize() { return 0; }
328
329   unsigned getPrefetchDistance() { return 0; }
330
331   unsigned getMinPrefetchStride() { return 1; }
332
333   unsigned getMaxPrefetchIterationsAhead() { return UINT_MAX; }
334
335   unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
336
337   unsigned getArithmeticInstrCost(unsigned Opcode, Type *Ty,
338                                   TTI::OperandValueKind Opd1Info,
339                                   TTI::OperandValueKind Opd2Info,
340                                   TTI::OperandValueProperties Opd1PropInfo,
341                                   TTI::OperandValueProperties Opd2PropInfo,
342                                   ArrayRef<const Value *> Args) {
343     return 1;
344   }
345
346   unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Ty, int Index,
347                           Type *SubTp) {
348     return 1;
349   }
350
351   unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
352                             const Instruction *I) { return 1; }
353
354   unsigned getExtractWithExtendCost(unsigned Opcode, Type *Dst,
355                                     VectorType *VecTy, unsigned Index) {
356     return 1;
357   }
358
359   unsigned getCFInstrCost(unsigned Opcode) { return 1; }
360
361   unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
362                               const Instruction *I) {
363     return 1;
364   }
365
366   unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
367     return 1;
368   }
369
370   unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
371                            unsigned AddressSpace, const Instruction *I) {
372     return 1;
373   }
374
375   unsigned getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
376                                  unsigned AddressSpace) {
377     return 1;
378   }
379
380   unsigned getGatherScatterOpCost(unsigned Opcode, Type *DataTy, Value *Ptr,
381                                   bool VariableMask,
382                                   unsigned Alignment) {
383     return 1;
384   }
385
386   unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
387                                       unsigned Factor,
388                                       ArrayRef<unsigned> Indices,
389                                       unsigned Alignment,
390                                       unsigned AddressSpace) {
391     return 1;
392   }
393
394   unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
395                                  ArrayRef<Type *> Tys, FastMathFlags FMF,
396                                  unsigned ScalarizationCostPassed) {
397     return 1;
398   }
399   unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
400             ArrayRef<Value *> Args, FastMathFlags FMF, unsigned VF) {
401     return 1;
402   }
403
404   unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) {
405     return 1;
406   }
407
408   unsigned getNumberOfParts(Type *Tp) { return 0; }
409
410   unsigned getAddressComputationCost(Type *Tp, ScalarEvolution *,
411                                      const SCEV *) {
412     return 0; 
413   }
414
415   unsigned getReductionCost(unsigned, Type *, bool) { return 1; }
416
417   unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) { return 0; }
418
419   bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) {
420     return false;
421   }
422
423   Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
424                                            Type *ExpectedType) {
425     return nullptr;
426   }
427
428   bool areInlineCompatible(const Function *Caller,
429                            const Function *Callee) const {
430     return (Caller->getFnAttribute("target-cpu") ==
431             Callee->getFnAttribute("target-cpu")) &&
432            (Caller->getFnAttribute("target-features") ==
433             Callee->getFnAttribute("target-features"));
434   }
435
436   unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const { return 128; }
437
438   bool isLegalToVectorizeLoad(LoadInst *LI) const { return true; }
439
440   bool isLegalToVectorizeStore(StoreInst *SI) const { return true; }
441
442   bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
443                                    unsigned Alignment,
444                                    unsigned AddrSpace) const {
445     return true;
446   }
447
448   bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
449                                     unsigned Alignment,
450                                     unsigned AddrSpace) const {
451     return true;
452   }
453
454   unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
455                                unsigned ChainSizeInBytes,
456                                VectorType *VecTy) const {
457     return VF;
458   }
459
460   unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
461                                 unsigned ChainSizeInBytes,
462                                 VectorType *VecTy) const {
463     return VF;
464   }
465
466   bool useReductionIntrinsic(unsigned Opcode, Type *Ty,
467                              TTI::ReductionFlags Flags) const {
468     return false;
469   }
470
471   bool shouldExpandReduction(const IntrinsicInst *II) const {
472     return true;
473   }
474
475 protected:
476   // Obtain the minimum required size to hold the value (without the sign)
477   // In case of a vector it returns the min required size for one element.
478   unsigned minRequiredElementSize(const Value* Val, bool &isSigned) {
479     if (isa<ConstantDataVector>(Val) || isa<ConstantVector>(Val)) {
480       const auto* VectorValue = cast<Constant>(Val);
481
482       // In case of a vector need to pick the max between the min
483       // required size for each element
484       auto *VT = cast<VectorType>(Val->getType());
485
486       // Assume unsigned elements
487       isSigned = false;
488
489       // The max required size is the total vector width divided by num
490       // of elements in the vector
491       unsigned MaxRequiredSize = VT->getBitWidth() / VT->getNumElements();
492
493       unsigned MinRequiredSize = 0;
494       for(unsigned i = 0, e = VT->getNumElements(); i < e; ++i) {
495         if (auto* IntElement =
496               dyn_cast<ConstantInt>(VectorValue->getAggregateElement(i))) {
497           bool signedElement = IntElement->getValue().isNegative();
498           // Get the element min required size.
499           unsigned ElementMinRequiredSize =
500             IntElement->getValue().getMinSignedBits() - 1;
501           // In case one element is signed then all the vector is signed.
502           isSigned |= signedElement;
503           // Save the max required bit size between all the elements.
504           MinRequiredSize = std::max(MinRequiredSize, ElementMinRequiredSize);
505         }
506         else {
507           // not an int constant element
508           return MaxRequiredSize;
509         }
510       }
511       return MinRequiredSize;
512     }
513
514     if (const auto* CI = dyn_cast<ConstantInt>(Val)) {
515       isSigned = CI->getValue().isNegative();
516       return CI->getValue().getMinSignedBits() - 1;
517     }
518
519     if (const auto* Cast = dyn_cast<SExtInst>(Val)) {
520       isSigned = true;
521       return Cast->getSrcTy()->getScalarSizeInBits() - 1;
522     }
523
524     if (const auto* Cast = dyn_cast<ZExtInst>(Val)) {
525       isSigned = false;
526       return Cast->getSrcTy()->getScalarSizeInBits();
527     }
528
529     isSigned = false;
530     return Val->getType()->getScalarSizeInBits();
531   }
532
533   bool isStridedAccess(const SCEV *Ptr) {
534     return Ptr && isa<SCEVAddRecExpr>(Ptr);
535   }
536
537   const SCEVConstant *getConstantStrideStep(ScalarEvolution *SE,
538                                             const SCEV *Ptr) {
539     if (!isStridedAccess(Ptr))
540       return nullptr;
541     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ptr);
542     return dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(*SE));
543   }
544
545   bool isConstantStridedAccessLessThan(ScalarEvolution *SE, const SCEV *Ptr,
546                                        int64_t MergeDistance) {
547     const SCEVConstant *Step = getConstantStrideStep(SE, Ptr);
548     if (!Step)
549       return false;
550     APInt StrideVal = Step->getAPInt();
551     if (StrideVal.getBitWidth() > 64)
552       return false;
553     // FIXME: need to take absolute value for negtive stride case  
554     return StrideVal.getSExtValue() < MergeDistance;
555   }
556 };
557
558 /// \brief CRTP base class for use as a mix-in that aids implementing
559 /// a TargetTransformInfo-compatible class.
560 template <typename T>
561 class TargetTransformInfoImplCRTPBase : public TargetTransformInfoImplBase {
562 private:
563   typedef TargetTransformInfoImplBase BaseT;
564
565 protected:
566   explicit TargetTransformInfoImplCRTPBase(const DataLayout &DL) : BaseT(DL) {}
567
568 public:
569   using BaseT::getCallCost;
570
571   unsigned getCallCost(const Function *F, int NumArgs) {
572     assert(F && "A concrete function must be provided to this routine.");
573
574     if (NumArgs < 0)
575       // Set the argument number to the number of explicit arguments in the
576       // function.
577       NumArgs = F->arg_size();
578
579     if (Intrinsic::ID IID = F->getIntrinsicID()) {
580       FunctionType *FTy = F->getFunctionType();
581       SmallVector<Type *, 8> ParamTys(FTy->param_begin(), FTy->param_end());
582       return static_cast<T *>(this)
583           ->getIntrinsicCost(IID, FTy->getReturnType(), ParamTys);
584     }
585
586     if (!static_cast<T *>(this)->isLoweredToCall(F))
587       return TTI::TCC_Basic; // Give a basic cost if it will be lowered
588                              // directly.
589
590     return static_cast<T *>(this)->getCallCost(F->getFunctionType(), NumArgs);
591   }
592
593   unsigned getCallCost(const Function *F, ArrayRef<const Value *> Arguments) {
594     // Simply delegate to generic handling of the call.
595     // FIXME: We should use instsimplify or something else to catch calls which
596     // will constant fold with these arguments.
597     return static_cast<T *>(this)->getCallCost(F, Arguments.size());
598   }
599
600   using BaseT::getGEPCost;
601
602   int getGEPCost(Type *PointeeType, const Value *Ptr,
603                  ArrayRef<const Value *> Operands) {
604     const GlobalValue *BaseGV = nullptr;
605     if (Ptr != nullptr) {
606       // TODO: will remove this when pointers have an opaque type.
607       assert(Ptr->getType()->getScalarType()->getPointerElementType() ==
608                  PointeeType &&
609              "explicit pointee type doesn't match operand's pointee type");
610       BaseGV = dyn_cast<GlobalValue>(Ptr->stripPointerCasts());
611     }
612     bool HasBaseReg = (BaseGV == nullptr);
613     int64_t BaseOffset = 0;
614     int64_t Scale = 0;
615
616     auto GTI = gep_type_begin(PointeeType, Operands);
617     Type *TargetType;
618     for (auto I = Operands.begin(); I != Operands.end(); ++I, ++GTI) {
619       TargetType = GTI.getIndexedType();
620       // We assume that the cost of Scalar GEP with constant index and the
621       // cost of Vector GEP with splat constant index are the same.
622       const ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I);
623       if (!ConstIdx)
624         if (auto Splat = getSplatValue(*I))
625           ConstIdx = dyn_cast<ConstantInt>(Splat);
626       if (StructType *STy = GTI.getStructTypeOrNull()) {
627         // For structures the index is always splat or scalar constant
628         assert(ConstIdx && "Unexpected GEP index");
629         uint64_t Field = ConstIdx->getZExtValue();
630         BaseOffset += DL.getStructLayout(STy)->getElementOffset(Field);
631       } else {
632         int64_t ElementSize = DL.getTypeAllocSize(GTI.getIndexedType());
633         if (ConstIdx)
634           BaseOffset += ConstIdx->getSExtValue() * ElementSize;
635         else {
636           // Needs scale register.
637           if (Scale != 0)
638             // No addressing mode takes two scale registers.
639             return TTI::TCC_Basic;
640           Scale = ElementSize;
641         }
642       }
643     }
644
645     // Assumes the address space is 0 when Ptr is nullptr.
646     unsigned AS =
647         (Ptr == nullptr ? 0 : Ptr->getType()->getPointerAddressSpace());
648     if (static_cast<T *>(this)->isLegalAddressingMode(
649             TargetType, const_cast<GlobalValue *>(BaseGV), BaseOffset,
650             HasBaseReg, Scale, AS))
651       return TTI::TCC_Free;
652     return TTI::TCC_Basic;
653   }
654
655   using BaseT::getIntrinsicCost;
656
657   unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
658                             ArrayRef<const Value *> Arguments) {
659     // Delegate to the generic intrinsic handling code. This mostly provides an
660     // opportunity for targets to (for example) special case the cost of
661     // certain intrinsics based on constants used as arguments.
662     SmallVector<Type *, 8> ParamTys;
663     ParamTys.reserve(Arguments.size());
664     for (unsigned Idx = 0, Size = Arguments.size(); Idx != Size; ++Idx)
665       ParamTys.push_back(Arguments[Idx]->getType());
666     return static_cast<T *>(this)->getIntrinsicCost(IID, RetTy, ParamTys);
667   }
668
669   unsigned getUserCost(const User *U) {
670     if (isa<PHINode>(U))
671       return TTI::TCC_Free; // Model all PHI nodes as free.
672
673     if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
674       SmallVector<Value *, 4> Indices(GEP->idx_begin(), GEP->idx_end());
675       return static_cast<T *>(this)->getGEPCost(
676           GEP->getSourceElementType(), GEP->getPointerOperand(), Indices);
677     }
678
679     if (auto CS = ImmutableCallSite(U)) {
680       const Function *F = CS.getCalledFunction();
681       if (!F) {
682         // Just use the called value type.
683         Type *FTy = CS.getCalledValue()->getType()->getPointerElementType();
684         return static_cast<T *>(this)
685             ->getCallCost(cast<FunctionType>(FTy), CS.arg_size());
686       }
687
688       SmallVector<const Value *, 8> Arguments(CS.arg_begin(), CS.arg_end());
689       return static_cast<T *>(this)->getCallCost(F, Arguments);
690     }
691
692     if (const CastInst *CI = dyn_cast<CastInst>(U)) {
693       // Result of a cmp instruction is often extended (to be used by other
694       // cmp instructions, logical or return instructions). These are usually
695       // nop on most sane targets.
696       if (isa<CmpInst>(CI->getOperand(0)))
697         return TTI::TCC_Free;
698     }
699
700     return static_cast<T *>(this)->getOperationCost(
701         Operator::getOpcode(U), U->getType(),
702         U->getNumOperands() == 1 ? U->getOperand(0)->getType() : nullptr);
703   }
704 };
705 }
706
707 #endif