BasicTargetTransformInfo.cpp revision 6bf4f676413b8f7d97aaff289997aab344180957
1//===- BasicTargetTransformInfo.cpp - Basic target-independent TTI impl ---===//
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 the implementation of a basic TargetTransformInfo pass
11/// predicated on the target abstractions present in the target independent
12/// code generator. It uses these (primarily TargetLowering) to model as much
13/// of the TTI query interface as possible. It is included by most targets so
14/// that they can specialize only a small subset of the query space.
15///
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "basictti"
19#include "llvm/CodeGen/Passes.h"
20#include "llvm/Analysis/TargetTransformInfo.h"
21#include "llvm/Target/TargetLowering.h"
22#include <utility>
23
24using namespace llvm;
25
26namespace {
27
28class BasicTTI : public ImmutablePass, public TargetTransformInfo {
29  const TargetLoweringBase *TLI;
30
31  /// Estimate the overhead of scalarizing an instruction. Insert and Extract
32  /// are set if the result needs to be inserted and/or extracted from vectors.
33  unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) const;
34
35public:
36  BasicTTI() : ImmutablePass(ID), TLI(0) {
37    llvm_unreachable("This pass cannot be directly constructed");
38  }
39
40  BasicTTI(const TargetLoweringBase *TLI) : ImmutablePass(ID), TLI(TLI) {
41    initializeBasicTTIPass(*PassRegistry::getPassRegistry());
42  }
43
44  virtual void initializePass() {
45    pushTTIStack(this);
46  }
47
48  virtual void finalizePass() {
49    popTTIStack();
50  }
51
52  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
53    TargetTransformInfo::getAnalysisUsage(AU);
54  }
55
56  /// Pass identification.
57  static char ID;
58
59  /// Provide necessary pointer adjustments for the two base classes.
60  virtual void *getAdjustedAnalysisPointer(const void *ID) {
61    if (ID == &TargetTransformInfo::ID)
62      return (TargetTransformInfo*)this;
63    return this;
64  }
65
66  /// \name Scalar TTI Implementations
67  /// @{
68
69  virtual bool isLegalAddImmediate(int64_t imm) const;
70  virtual bool isLegalICmpImmediate(int64_t imm) const;
71  virtual bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
72                                     int64_t BaseOffset, bool HasBaseReg,
73                                     int64_t Scale) const;
74  virtual bool isTruncateFree(Type *Ty1, Type *Ty2) const;
75  virtual bool isTypeLegal(Type *Ty) const;
76  virtual unsigned getJumpBufAlignment() const;
77  virtual unsigned getJumpBufSize() const;
78  virtual bool shouldBuildLookupTables() const;
79
80  /// @}
81
82  /// \name Vector TTI Implementations
83  /// @{
84
85  virtual unsigned getNumberOfRegisters(bool Vector) const;
86  virtual unsigned getMaximumUnrollFactor() const;
87  virtual unsigned getRegisterBitWidth(bool Vector) const;
88  virtual unsigned getArithmeticInstrCost(unsigned Opcode, Type *Ty,
89                                          OperandValueKind,
90                                          OperandValueKind) const;
91  virtual unsigned getShuffleCost(ShuffleKind Kind, Type *Tp,
92                                  int Index, Type *SubTp) const;
93  virtual unsigned getCastInstrCost(unsigned Opcode, Type *Dst,
94                                    Type *Src) const;
95  virtual unsigned getCFInstrCost(unsigned Opcode) const;
96  virtual unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
97                                      Type *CondTy) const;
98  virtual unsigned getVectorInstrCost(unsigned Opcode, Type *Val,
99                                      unsigned Index) const;
100  virtual unsigned getMemoryOpCost(unsigned Opcode, Type *Src,
101                                   unsigned Alignment,
102                                   unsigned AddressSpace) const;
103  virtual unsigned getIntrinsicInstrCost(Intrinsic::ID, Type *RetTy,
104                                         ArrayRef<Type*> Tys) const;
105  virtual unsigned getNumberOfParts(Type *Tp) const;
106  virtual unsigned getAddressComputationCost(Type *Ty) const;
107
108  /// @}
109};
110
111}
112
113INITIALIZE_AG_PASS(BasicTTI, TargetTransformInfo, "basictti",
114                   "Target independent code generator's TTI", true, true, false)
115char BasicTTI::ID = 0;
116
117ImmutablePass *
118llvm::createBasicTargetTransformInfoPass(const TargetLoweringBase *TLI) {
119  return new BasicTTI(TLI);
120}
121
122
123bool BasicTTI::isLegalAddImmediate(int64_t imm) const {
124  return TLI->isLegalAddImmediate(imm);
125}
126
127bool BasicTTI::isLegalICmpImmediate(int64_t imm) const {
128  return TLI->isLegalICmpImmediate(imm);
129}
130
131bool BasicTTI::isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
132                                     int64_t BaseOffset, bool HasBaseReg,
133                                     int64_t Scale) const {
134  TargetLoweringBase::AddrMode AM;
135  AM.BaseGV = BaseGV;
136  AM.BaseOffs = BaseOffset;
137  AM.HasBaseReg = HasBaseReg;
138  AM.Scale = Scale;
139  return TLI->isLegalAddressingMode(AM, Ty);
140}
141
142bool BasicTTI::isTruncateFree(Type *Ty1, Type *Ty2) const {
143  return TLI->isTruncateFree(Ty1, Ty2);
144}
145
146bool BasicTTI::isTypeLegal(Type *Ty) const {
147  EVT T = TLI->getValueType(Ty);
148  return TLI->isTypeLegal(T);
149}
150
151unsigned BasicTTI::getJumpBufAlignment() const {
152  return TLI->getJumpBufAlignment();
153}
154
155unsigned BasicTTI::getJumpBufSize() const {
156  return TLI->getJumpBufSize();
157}
158
159bool BasicTTI::shouldBuildLookupTables() const {
160  return TLI->supportJumpTables() &&
161      (TLI->isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
162       TLI->isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
163}
164
165//===----------------------------------------------------------------------===//
166//
167// Calls used by the vectorizers.
168//
169//===----------------------------------------------------------------------===//
170
171unsigned BasicTTI::getScalarizationOverhead(Type *Ty, bool Insert,
172                                            bool Extract) const {
173  assert (Ty->isVectorTy() && "Can only scalarize vectors");
174  unsigned Cost = 0;
175
176  for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
177    if (Insert)
178      Cost += TopTTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
179    if (Extract)
180      Cost += TopTTI->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
181  }
182
183  return Cost;
184}
185
186unsigned BasicTTI::getNumberOfRegisters(bool Vector) const {
187  return 1;
188}
189
190unsigned BasicTTI::getRegisterBitWidth(bool Vector) const {
191  return 32;
192}
193
194unsigned BasicTTI::getMaximumUnrollFactor() const {
195  return 1;
196}
197
198unsigned BasicTTI::getArithmeticInstrCost(unsigned Opcode, Type *Ty,
199                                          OperandValueKind,
200                                          OperandValueKind) const {
201  // Check if any of the operands are vector operands.
202  int ISD = TLI->InstructionOpcodeToISD(Opcode);
203  assert(ISD && "Invalid opcode");
204
205  std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(Ty);
206
207  if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
208    // The operation is legal. Assume it costs 1.
209    // If the type is split to multiple registers, assume that thre is some
210    // overhead to this.
211    // TODO: Once we have extract/insert subvector cost we need to use them.
212    if (LT.first > 1)
213      return LT.first * 2;
214    return LT.first * 1;
215  }
216
217  if (!TLI->isOperationExpand(ISD, LT.second)) {
218    // If the operation is custom lowered then assume
219    // thare the code is twice as expensive.
220    return LT.first * 2;
221  }
222
223  // Else, assume that we need to scalarize this op.
224  if (Ty->isVectorTy()) {
225    unsigned Num = Ty->getVectorNumElements();
226    unsigned Cost = TopTTI->getArithmeticInstrCost(Opcode, Ty->getScalarType());
227    // return the cost of multiple scalar invocation plus the cost of inserting
228    // and extracting the values.
229    return getScalarizationOverhead(Ty, true, true) + Num * Cost;
230  }
231
232  // We don't know anything about this scalar instruction.
233  return 1;
234}
235
236unsigned BasicTTI::getShuffleCost(ShuffleKind Kind, Type *Tp, int Index,
237                                  Type *SubTp) const {
238  return 1;
239}
240
241unsigned BasicTTI::getCastInstrCost(unsigned Opcode, Type *Dst,
242                                    Type *Src) const {
243  int ISD = TLI->InstructionOpcodeToISD(Opcode);
244  assert(ISD && "Invalid opcode");
245
246  std::pair<unsigned, MVT> SrcLT = TLI->getTypeLegalizationCost(Src);
247  std::pair<unsigned, MVT> DstLT = TLI->getTypeLegalizationCost(Dst);
248
249  // Check for NOOP conversions.
250  if (SrcLT.first == DstLT.first &&
251      SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
252
253      // Bitcast between types that are legalized to the same type are free.
254      if (Opcode == Instruction::BitCast || Opcode == Instruction::Trunc)
255        return 0;
256  }
257
258  if (Opcode == Instruction::Trunc &&
259      TLI->isTruncateFree(SrcLT.second, DstLT.second))
260    return 0;
261
262  if (Opcode == Instruction::ZExt &&
263      TLI->isZExtFree(SrcLT.second, DstLT.second))
264    return 0;
265
266  // If the cast is marked as legal (or promote) then assume low cost.
267  if (TLI->isOperationLegalOrPromote(ISD, DstLT.second))
268    return 1;
269
270  // Handle scalar conversions.
271  if (!Src->isVectorTy() && !Dst->isVectorTy()) {
272
273    // Scalar bitcasts are usually free.
274    if (Opcode == Instruction::BitCast)
275      return 0;
276
277    // Just check the op cost. If the operation is legal then assume it costs 1.
278    if (!TLI->isOperationExpand(ISD, DstLT.second))
279      return  1;
280
281    // Assume that illegal scalar instruction are expensive.
282    return 4;
283  }
284
285  // Check vector-to-vector casts.
286  if (Dst->isVectorTy() && Src->isVectorTy()) {
287
288    // If the cast is between same-sized registers, then the check is simple.
289    if (SrcLT.first == DstLT.first &&
290        SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
291
292      // Assume that Zext is done using AND.
293      if (Opcode == Instruction::ZExt)
294        return 1;
295
296      // Assume that sext is done using SHL and SRA.
297      if (Opcode == Instruction::SExt)
298        return 2;
299
300      // Just check the op cost. If the operation is legal then assume it costs
301      // 1 and multiply by the type-legalization overhead.
302      if (!TLI->isOperationExpand(ISD, DstLT.second))
303        return SrcLT.first * 1;
304    }
305
306    // If we are converting vectors and the operation is illegal, or
307    // if the vectors are legalized to different types, estimate the
308    // scalarization costs.
309    unsigned Num = Dst->getVectorNumElements();
310    unsigned Cost = TopTTI->getCastInstrCost(Opcode, Dst->getScalarType(),
311                                             Src->getScalarType());
312
313    // Return the cost of multiple scalar invocation plus the cost of
314    // inserting and extracting the values.
315    return getScalarizationOverhead(Dst, true, true) + Num * Cost;
316  }
317
318  // We already handled vector-to-vector and scalar-to-scalar conversions. This
319  // is where we handle bitcast between vectors and scalars. We need to assume
320  //  that the conversion is scalarized in one way or another.
321  if (Opcode == Instruction::BitCast)
322    // Illegal bitcasts are done by storing and loading from a stack slot.
323    return (Src->isVectorTy()? getScalarizationOverhead(Src, false, true):0) +
324           (Dst->isVectorTy()? getScalarizationOverhead(Dst, true, false):0);
325
326  llvm_unreachable("Unhandled cast");
327 }
328
329unsigned BasicTTI::getCFInstrCost(unsigned Opcode) const {
330  // Branches are assumed to be predicted.
331  return 0;
332}
333
334unsigned BasicTTI::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
335                                      Type *CondTy) const {
336  int ISD = TLI->InstructionOpcodeToISD(Opcode);
337  assert(ISD && "Invalid opcode");
338
339  // Selects on vectors are actually vector selects.
340  if (ISD == ISD::SELECT) {
341    assert(CondTy && "CondTy must exist");
342    if (CondTy->isVectorTy())
343      ISD = ISD::VSELECT;
344  }
345
346  std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(ValTy);
347
348  if (!TLI->isOperationExpand(ISD, LT.second)) {
349    // The operation is legal. Assume it costs 1. Multiply
350    // by the type-legalization overhead.
351    return LT.first * 1;
352  }
353
354  // Otherwise, assume that the cast is scalarized.
355  if (ValTy->isVectorTy()) {
356    unsigned Num = ValTy->getVectorNumElements();
357    if (CondTy)
358      CondTy = CondTy->getScalarType();
359    unsigned Cost = TopTTI->getCmpSelInstrCost(Opcode, ValTy->getScalarType(),
360                                               CondTy);
361
362    // Return the cost of multiple scalar invocation plus the cost of inserting
363    // and extracting the values.
364    return getScalarizationOverhead(ValTy, true, false) + Num * Cost;
365  }
366
367  // Unknown scalar opcode.
368  return 1;
369}
370
371unsigned BasicTTI::getVectorInstrCost(unsigned Opcode, Type *Val,
372                                      unsigned Index) const {
373  return 1;
374}
375
376unsigned BasicTTI::getMemoryOpCost(unsigned Opcode, Type *Src,
377                                   unsigned Alignment,
378                                   unsigned AddressSpace) const {
379  assert(!Src->isVoidTy() && "Invalid type");
380  std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(Src);
381
382  // Assume that all loads of legal types cost 1.
383  return LT.first;
384}
385
386unsigned BasicTTI::getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
387                                         ArrayRef<Type *> Tys) const {
388  unsigned ISD = 0;
389  switch (IID) {
390  default: {
391    // Assume that we need to scalarize this intrinsic.
392    unsigned ScalarizationCost = 0;
393    unsigned ScalarCalls = 1;
394    if (RetTy->isVectorTy()) {
395      ScalarizationCost = getScalarizationOverhead(RetTy, true, false);
396      ScalarCalls = std::max(ScalarCalls, RetTy->getVectorNumElements());
397    }
398    for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
399      if (Tys[i]->isVectorTy()) {
400        ScalarizationCost += getScalarizationOverhead(Tys[i], false, true);
401        ScalarCalls = std::max(ScalarCalls, RetTy->getVectorNumElements());
402      }
403    }
404
405    return ScalarCalls + ScalarizationCost;
406  }
407  // Look for intrinsics that can be lowered directly or turned into a scalar
408  // intrinsic call.
409  case Intrinsic::sqrt:    ISD = ISD::FSQRT;  break;
410  case Intrinsic::sin:     ISD = ISD::FSIN;   break;
411  case Intrinsic::cos:     ISD = ISD::FCOS;   break;
412  case Intrinsic::exp:     ISD = ISD::FEXP;   break;
413  case Intrinsic::exp2:    ISD = ISD::FEXP2;  break;
414  case Intrinsic::log:     ISD = ISD::FLOG;   break;
415  case Intrinsic::log10:   ISD = ISD::FLOG10; break;
416  case Intrinsic::log2:    ISD = ISD::FLOG2;  break;
417  case Intrinsic::fabs:    ISD = ISD::FABS;   break;
418  case Intrinsic::floor:   ISD = ISD::FFLOOR; break;
419  case Intrinsic::ceil:    ISD = ISD::FCEIL;  break;
420  case Intrinsic::trunc:   ISD = ISD::FTRUNC; break;
421  case Intrinsic::rint:    ISD = ISD::FRINT;  break;
422  case Intrinsic::pow:     ISD = ISD::FPOW;   break;
423  case Intrinsic::fma:     ISD = ISD::FMA;    break;
424  case Intrinsic::fmuladd: ISD = ISD::FMA;    break; // FIXME: mul + add?
425  }
426
427  std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(RetTy);
428
429  if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
430    // The operation is legal. Assume it costs 1.
431    // If the type is split to multiple registers, assume that thre is some
432    // overhead to this.
433    // TODO: Once we have extract/insert subvector cost we need to use them.
434    if (LT.first > 1)
435      return LT.first * 2;
436    return LT.first * 1;
437  }
438
439  if (!TLI->isOperationExpand(ISD, LT.second)) {
440    // If the operation is custom lowered then assume
441    // thare the code is twice as expensive.
442    return LT.first * 2;
443  }
444
445  // Else, assume that we need to scalarize this intrinsic. For math builtins
446  // this will emit a costly libcall, adding call overhead and spills. Make it
447  // very expensive.
448  if (RetTy->isVectorTy()) {
449    unsigned Num = RetTy->getVectorNumElements();
450    unsigned Cost = TopTTI->getIntrinsicInstrCost(IID, RetTy->getScalarType(),
451                                                  Tys);
452    return 10 * Cost * Num;
453  }
454
455  // This is going to be turned into a library call, make it expensive.
456  return 10;
457}
458
459unsigned BasicTTI::getNumberOfParts(Type *Tp) const {
460  std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(Tp);
461  return LT.first;
462}
463
464unsigned BasicTTI::getAddressComputationCost(Type *Ty) const {
465  return 0;
466}
467