415a85e990696cef36491862da8e348a96ff2d24
[oota-llvm.git] / 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/TargetTransformInfo.h"
19 #include "llvm/IR/CallSite.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/GetElementPtrTypeIterator.h"
23 #include "llvm/IR/Operator.h"
24 #include "llvm/IR/Type.h"
25
26 namespace llvm {
27
28 /// \brief Base class for use as a mix-in that aids implementing
29 /// a TargetTransformInfo-compatible class.
30 class TargetTransformInfoImplBase {
31 protected:
32   typedef TargetTransformInfo TTI;
33
34   const DataLayout &DL;
35
36   explicit TargetTransformInfoImplBase(const DataLayout &DL) : DL(DL) {}
37
38 public:
39   // Provide value semantics. MSVC requires that we spell all of these out.
40   TargetTransformInfoImplBase(const TargetTransformInfoImplBase &Arg)
41       : DL(Arg.DL) {}
42   TargetTransformInfoImplBase(TargetTransformInfoImplBase &&Arg) : DL(Arg.DL) {}
43
44   const DataLayout &getDataLayout() const { return DL; }
45
46   unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) {
47     switch (Opcode) {
48     default:
49       // By default, just classify everything as 'basic'.
50       return TTI::TCC_Basic;
51
52     case Instruction::GetElementPtr:
53       llvm_unreachable("Use getGEPCost for GEP operations!");
54
55     case Instruction::BitCast:
56       assert(OpTy && "Cast instructions must provide the operand type");
57       if (Ty == OpTy || (Ty->isPointerTy() && OpTy->isPointerTy()))
58         // Identity and pointer-to-pointer casts are free.
59         return TTI::TCC_Free;
60
61       // Otherwise, the default basic cost is used.
62       return TTI::TCC_Basic;
63
64     case Instruction::FDiv:
65     case Instruction::FRem:
66     case Instruction::SDiv:
67     case Instruction::SRem:
68     case Instruction::UDiv:
69     case Instruction::URem:
70       return TTI::TCC_Expensive;
71
72     case Instruction::IntToPtr: {
73       // An inttoptr cast is free so long as the input is a legal integer type
74       // which doesn't contain values outside the range of a pointer.
75       unsigned OpSize = OpTy->getScalarSizeInBits();
76       if (DL.isLegalInteger(OpSize) &&
77           OpSize <= DL.getPointerTypeSizeInBits(Ty))
78         return TTI::TCC_Free;
79
80       // Otherwise it's not a no-op.
81       return TTI::TCC_Basic;
82     }
83     case Instruction::PtrToInt: {
84       // A ptrtoint cast is free so long as the result is large enough to store
85       // the pointer, and a legal integer type.
86       unsigned DestSize = Ty->getScalarSizeInBits();
87       if (DL.isLegalInteger(DestSize) &&
88           DestSize >= DL.getPointerTypeSizeInBits(OpTy))
89         return TTI::TCC_Free;
90
91       // Otherwise it's not a no-op.
92       return TTI::TCC_Basic;
93     }
94     case Instruction::Trunc:
95       // trunc to a native type is free (assuming the target has compare and
96       // shift-right of the same width).
97       if (DL.isLegalInteger(DL.getTypeSizeInBits(Ty)))
98         return TTI::TCC_Free;
99
100       return TTI::TCC_Basic;
101     }
102   }
103
104   unsigned getGEPCost(Type *PointeeType, const Value *Ptr,
105                       ArrayRef<const Value *> Operands) {
106     // In the basic model, we just assume that all-constant GEPs will be folded
107     // into their uses via addressing modes.
108     for (unsigned Idx = 0, Size = Operands.size(); Idx != Size; ++Idx)
109       if (!isa<Constant>(Operands[Idx]))
110         return TTI::TCC_Basic;
111
112     return TTI::TCC_Free;
113   }
114
115   unsigned getCallCost(FunctionType *FTy, int NumArgs) {
116     assert(FTy && "FunctionType must be provided to this routine.");
117
118     // The target-independent implementation just measures the size of the
119     // function by approximating that each argument will take on average one
120     // instruction to prepare.
121
122     if (NumArgs < 0)
123       // Set the argument number to the number of explicit arguments in the
124       // function.
125       NumArgs = FTy->getNumParams();
126
127     return TTI::TCC_Basic * (NumArgs + 1);
128   }
129
130   unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
131                             ArrayRef<Type *> ParamTys) {
132     switch (IID) {
133     default:
134       // Intrinsics rarely (if ever) have normal argument setup constraints.
135       // Model them as having a basic instruction cost.
136       // FIXME: This is wrong for libc intrinsics.
137       return TTI::TCC_Basic;
138
139     case Intrinsic::annotation:
140     case Intrinsic::assume:
141     case Intrinsic::dbg_declare:
142     case Intrinsic::dbg_value:
143     case Intrinsic::invariant_start:
144     case Intrinsic::invariant_end:
145     case Intrinsic::lifetime_start:
146     case Intrinsic::lifetime_end:
147     case Intrinsic::objectsize:
148     case Intrinsic::ptr_annotation:
149     case Intrinsic::var_annotation:
150     case Intrinsic::experimental_gc_result_int:
151     case Intrinsic::experimental_gc_result_float:
152     case Intrinsic::experimental_gc_result_ptr:
153     case Intrinsic::experimental_gc_result:
154     case Intrinsic::experimental_gc_relocate:
155       // These intrinsics don't actually represent code after lowering.
156       return TTI::TCC_Free;
157     }
158   }
159
160   bool hasBranchDivergence() { return false; }
161
162   bool isSourceOfDivergence(const Value *V) { return false; }
163
164   bool isLoweredToCall(const Function *F) {
165     // FIXME: These should almost certainly not be handled here, and instead
166     // handled with the help of TLI or the target itself. This was largely
167     // ported from existing analysis heuristics here so that such refactorings
168     // can take place in the future.
169
170     if (F->isIntrinsic())
171       return false;
172
173     if (F->hasLocalLinkage() || !F->hasName())
174       return true;
175
176     StringRef Name = F->getName();
177
178     // These will all likely lower to a single selection DAG node.
179     if (Name == "copysign" || Name == "copysignf" || Name == "copysignl" ||
180         Name == "fabs" || Name == "fabsf" || Name == "fabsl" || Name == "sin" ||
181         Name == "fmin" || Name == "fminf" || Name == "fminl" ||
182         Name == "fmax" || Name == "fmaxf" || Name == "fmaxl" ||
183         Name == "sinf" || Name == "sinl" || Name == "cos" || Name == "cosf" ||
184         Name == "cosl" || Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl")
185       return false;
186
187     // These are all likely to be optimized into something smaller.
188     if (Name == "pow" || Name == "powf" || Name == "powl" || Name == "exp2" ||
189         Name == "exp2l" || Name == "exp2f" || Name == "floor" ||
190         Name == "floorf" || Name == "ceil" || Name == "round" ||
191         Name == "ffs" || Name == "ffsl" || Name == "abs" || Name == "labs" ||
192         Name == "llabs")
193       return false;
194
195     return true;
196   }
197
198   void getUnrollingPreferences(Loop *, TTI::UnrollingPreferences &) {}
199
200   bool isLegalAddImmediate(int64_t Imm) { return false; }
201
202   bool isLegalICmpImmediate(int64_t Imm) { return false; }
203
204   bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
205                              bool HasBaseReg, int64_t Scale,
206                              unsigned AddrSpace) {
207     // Guess that only reg and reg+reg addressing is allowed. This heuristic is
208     // taken from the implementation of LSR.
209     return !BaseGV && BaseOffset == 0 && (Scale == 0 || Scale == 1);
210   }
211
212   bool isLegalMaskedStore(Type *DataType) { return false; }
213
214   bool isLegalMaskedLoad(Type *DataType) { return false; }
215
216   bool isLegalMaskedScatter(Type *DataType) { return false; }
217
218   bool isLegalMaskedGather(Type *DataType) { return false; }
219
220   int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
221                            bool HasBaseReg, int64_t Scale, unsigned AddrSpace) {
222     // Guess that all legal addressing mode are free.
223     if (isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg,
224                               Scale, AddrSpace))
225       return 0;
226     return -1;
227   }
228
229   bool isTruncateFree(Type *Ty1, Type *Ty2) { return false; }
230
231   bool isProfitableToHoist(Instruction *I) { return true; }
232
233   bool isTypeLegal(Type *Ty) { return false; }
234
235   unsigned getJumpBufAlignment() { return 0; }
236
237   unsigned getJumpBufSize() { return 0; }
238
239   bool shouldBuildLookupTables() { return true; }
240
241   bool enableAggressiveInterleaving(bool LoopHasReductions) { return false; }
242
243   bool enableInterleavedAccessVectorization() { return false; }
244
245   TTI::PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) {
246     return TTI::PSK_Software;
247   }
248
249   bool haveFastSqrt(Type *Ty) { return false; }
250
251   unsigned getFPOpCost(Type *Ty) { return TargetTransformInfo::TCC_Basic; }
252
253   unsigned getIntImmCost(const APInt &Imm, Type *Ty) { return TTI::TCC_Basic; }
254
255   unsigned getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
256                          Type *Ty) {
257     return TTI::TCC_Free;
258   }
259
260   unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
261                          Type *Ty) {
262     return TTI::TCC_Free;
263   }
264
265   unsigned getNumberOfRegisters(bool Vector) { return 8; }
266
267   unsigned getRegisterBitWidth(bool Vector) { return 32; }
268
269   unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
270
271   unsigned getArithmeticInstrCost(unsigned Opcode, Type *Ty,
272                                   TTI::OperandValueKind Opd1Info,
273                                   TTI::OperandValueKind Opd2Info,
274                                   TTI::OperandValueProperties Opd1PropInfo,
275                                   TTI::OperandValueProperties Opd2PropInfo) {
276     return 1;
277   }
278
279   unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Ty, int Index,
280                           Type *SubTp) {
281     return 1;
282   }
283
284   unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) { return 1; }
285
286   unsigned getCFInstrCost(unsigned Opcode) { return 1; }
287
288   unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy) {
289     return 1;
290   }
291
292   unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
293     return 1;
294   }
295
296   unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
297                            unsigned AddressSpace) {
298     return 1;
299   }
300
301   unsigned getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
302                                  unsigned AddressSpace) {
303     return 1;
304   }
305
306   unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
307                                       unsigned Factor,
308                                       ArrayRef<unsigned> Indices,
309                                       unsigned Alignment,
310                                       unsigned AddressSpace) {
311     return 1;
312   }
313
314   unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
315                                  ArrayRef<Type *> Tys) {
316     return 1;
317   }
318
319   unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) {
320     return 1;
321   }
322
323   unsigned getNumberOfParts(Type *Tp) { return 0; }
324
325   unsigned getAddressComputationCost(Type *Tp, bool) { return 0; }
326
327   unsigned getReductionCost(unsigned, Type *, bool) { return 1; }
328
329   unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) { return 0; }
330
331   bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) {
332     return false;
333   }
334
335   Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
336                                            Type *ExpectedType) {
337     return nullptr;
338   }
339
340   bool areInlineCompatible(const Function *Caller,
341                            const Function *Callee) const {
342     return (Caller->getFnAttribute("target-cpu") ==
343             Callee->getFnAttribute("target-cpu")) &&
344            (Caller->getFnAttribute("target-features") ==
345             Callee->getFnAttribute("target-features"));
346   }
347 };
348
349 /// \brief CRTP base class for use as a mix-in that aids implementing
350 /// a TargetTransformInfo-compatible class.
351 template <typename T>
352 class TargetTransformInfoImplCRTPBase : public TargetTransformInfoImplBase {
353 private:
354   typedef TargetTransformInfoImplBase BaseT;
355
356 protected:
357   explicit TargetTransformInfoImplCRTPBase(const DataLayout &DL) : BaseT(DL) {}
358
359 public:
360   // Provide value semantics. MSVC requires that we spell all of these out.
361   TargetTransformInfoImplCRTPBase(const TargetTransformInfoImplCRTPBase &Arg)
362       : BaseT(static_cast<const BaseT &>(Arg)) {}
363   TargetTransformInfoImplCRTPBase(TargetTransformInfoImplCRTPBase &&Arg)
364       : BaseT(std::move(static_cast<BaseT &>(Arg))) {}
365
366   using BaseT::getCallCost;
367
368   unsigned getCallCost(const Function *F, int NumArgs) {
369     assert(F && "A concrete function must be provided to this routine.");
370
371     if (NumArgs < 0)
372       // Set the argument number to the number of explicit arguments in the
373       // function.
374       NumArgs = F->arg_size();
375
376     if (Intrinsic::ID IID = F->getIntrinsicID()) {
377       FunctionType *FTy = F->getFunctionType();
378       SmallVector<Type *, 8> ParamTys(FTy->param_begin(), FTy->param_end());
379       return static_cast<T *>(this)
380           ->getIntrinsicCost(IID, FTy->getReturnType(), ParamTys);
381     }
382
383     if (!static_cast<T *>(this)->isLoweredToCall(F))
384       return TTI::TCC_Basic; // Give a basic cost if it will be lowered
385                              // directly.
386
387     return static_cast<T *>(this)->getCallCost(F->getFunctionType(), NumArgs);
388   }
389
390   unsigned getCallCost(const Function *F, ArrayRef<const Value *> Arguments) {
391     // Simply delegate to generic handling of the call.
392     // FIXME: We should use instsimplify or something else to catch calls which
393     // will constant fold with these arguments.
394     return static_cast<T *>(this)->getCallCost(F, Arguments.size());
395   }
396
397   using BaseT::getGEPCost;
398
399   unsigned getGEPCost(Type *PointeeType, const Value *Ptr,
400                       ArrayRef<const Value *> Operands) {
401     const GlobalValue *BaseGV = nullptr;
402     if (Ptr != nullptr) {
403       // TODO: will remove this when pointers have an opaque type.
404       assert(Ptr->getType()->getScalarType()->getPointerElementType() ==
405                  PointeeType &&
406              "explicit pointee type doesn't match operand's pointee type");
407       BaseGV = dyn_cast<GlobalValue>(Ptr->stripPointerCasts());
408     }
409     bool HasBaseReg = (BaseGV == nullptr);
410     int64_t BaseOffset = 0;
411     int64_t Scale = 0;
412
413     // Assumes the address space is 0 when Ptr is nullptr.
414     unsigned AS =
415         (Ptr == nullptr ? 0 : Ptr->getType()->getPointerAddressSpace());
416     auto GTI = gep_type_begin(PointerType::get(PointeeType, AS), Operands);
417     for (auto I = Operands.begin(); I != Operands.end(); ++I, ++GTI) {
418       if (isa<SequentialType>(*GTI)) {
419         int64_t ElementSize = DL.getTypeAllocSize(GTI.getIndexedType());
420         if (const ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I)) {
421           BaseOffset += ConstIdx->getSExtValue() * ElementSize;
422         } else {
423           // Needs scale register.
424           if (Scale != 0) {
425             // No addressing mode takes two scale registers.
426             return TTI::TCC_Basic;
427           }
428           Scale = ElementSize;
429         }
430       } else {
431         StructType *STy = cast<StructType>(*GTI);
432         uint64_t Field = cast<ConstantInt>(*I)->getZExtValue();
433         BaseOffset += DL.getStructLayout(STy)->getElementOffset(Field);
434       }
435     }
436
437     if (static_cast<T *>(this)->isLegalAddressingMode(
438             PointerType::get(*GTI, AS), const_cast<GlobalValue *>(BaseGV),
439             BaseOffset, HasBaseReg, Scale, AS)) {
440       return TTI::TCC_Free;
441     }
442     return TTI::TCC_Basic;
443   }
444
445   using BaseT::getIntrinsicCost;
446
447   unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
448                             ArrayRef<const Value *> Arguments) {
449     // Delegate to the generic intrinsic handling code. This mostly provides an
450     // opportunity for targets to (for example) special case the cost of
451     // certain intrinsics based on constants used as arguments.
452     SmallVector<Type *, 8> ParamTys;
453     ParamTys.reserve(Arguments.size());
454     for (unsigned Idx = 0, Size = Arguments.size(); Idx != Size; ++Idx)
455       ParamTys.push_back(Arguments[Idx]->getType());
456     return static_cast<T *>(this)->getIntrinsicCost(IID, RetTy, ParamTys);
457   }
458
459   unsigned getUserCost(const User *U) {
460     if (isa<PHINode>(U))
461       return TTI::TCC_Free; // Model all PHI nodes as free.
462
463     if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
464       SmallVector<Value *, 4> Indices(GEP->idx_begin(), GEP->idx_end());
465       return static_cast<T *>(this)->getGEPCost(
466           GEP->getSourceElementType(), GEP->getPointerOperand(), Indices);
467     }
468
469     if (auto CS = ImmutableCallSite(U)) {
470       const Function *F = CS.getCalledFunction();
471       if (!F) {
472         // Just use the called value type.
473         Type *FTy = CS.getCalledValue()->getType()->getPointerElementType();
474         return static_cast<T *>(this)
475             ->getCallCost(cast<FunctionType>(FTy), CS.arg_size());
476       }
477
478       SmallVector<const Value *, 8> Arguments(CS.arg_begin(), CS.arg_end());
479       return static_cast<T *>(this)->getCallCost(F, Arguments);
480     }
481
482     if (const CastInst *CI = dyn_cast<CastInst>(U)) {
483       // Result of a cmp instruction is often extended (to be used by other
484       // cmp instructions, logical or return instructions). These are usually
485       // nop on most sane targets.
486       if (isa<CmpInst>(CI->getOperand(0)))
487         return TTI::TCC_Free;
488     }
489
490     return static_cast<T *>(this)->getOperationCost(
491         Operator::getOpcode(U), U->getType(),
492         U->getNumOperands() == 1 ? U->getOperand(0)->getType() : nullptr);
493   }
494 };
495 }
496
497 #endif