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