1//===- llvm/Analysis/TargetTransformInfo.cpp ------------------------------===//
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
10#include "llvm/Analysis/TargetTransformInfo.h"
11#include "llvm/IR/CallSite.h"
12#include "llvm/IR/DataLayout.h"
13#include "llvm/IR/Instruction.h"
14#include "llvm/IR/Instructions.h"
15#include "llvm/IR/IntrinsicInst.h"
16#include "llvm/IR/Operator.h"
17#include "llvm/Support/ErrorHandling.h"
18
19using namespace llvm;
20
21#define DEBUG_TYPE "tti"
22
23// Setup the analysis group to manage the TargetTransformInfo passes.
24INITIALIZE_ANALYSIS_GROUP(TargetTransformInfo, "Target Information", NoTTI)
25char TargetTransformInfo::ID = 0;
26
27TargetTransformInfo::~TargetTransformInfo() {
28}
29
30void TargetTransformInfo::pushTTIStack(Pass *P) {
31  TopTTI = this;
32  PrevTTI = &P->getAnalysis<TargetTransformInfo>();
33
34  // Walk up the chain and update the top TTI pointer.
35  for (TargetTransformInfo *PTTI = PrevTTI; PTTI; PTTI = PTTI->PrevTTI)
36    PTTI->TopTTI = this;
37}
38
39void TargetTransformInfo::getAnalysisUsage(AnalysisUsage &AU) const {
40  AU.addRequired<TargetTransformInfo>();
41}
42
43unsigned TargetTransformInfo::getOperationCost(unsigned Opcode, Type *Ty,
44                                               Type *OpTy) const {
45  return PrevTTI->getOperationCost(Opcode, Ty, OpTy);
46}
47
48unsigned TargetTransformInfo::getGEPCost(
49    const Value *Ptr, ArrayRef<const Value *> Operands) const {
50  return PrevTTI->getGEPCost(Ptr, Operands);
51}
52
53unsigned TargetTransformInfo::getCallCost(FunctionType *FTy,
54                                          int NumArgs) const {
55  return PrevTTI->getCallCost(FTy, NumArgs);
56}
57
58unsigned TargetTransformInfo::getCallCost(const Function *F,
59                                          int NumArgs) const {
60  return PrevTTI->getCallCost(F, NumArgs);
61}
62
63unsigned TargetTransformInfo::getCallCost(
64    const Function *F, ArrayRef<const Value *> Arguments) const {
65  return PrevTTI->getCallCost(F, Arguments);
66}
67
68unsigned TargetTransformInfo::getIntrinsicCost(
69    Intrinsic::ID IID, Type *RetTy, ArrayRef<Type *> ParamTys) const {
70  return PrevTTI->getIntrinsicCost(IID, RetTy, ParamTys);
71}
72
73unsigned TargetTransformInfo::getIntrinsicCost(
74    Intrinsic::ID IID, Type *RetTy, ArrayRef<const Value *> Arguments) const {
75  return PrevTTI->getIntrinsicCost(IID, RetTy, Arguments);
76}
77
78unsigned TargetTransformInfo::getUserCost(const User *U) const {
79  return PrevTTI->getUserCost(U);
80}
81
82bool TargetTransformInfo::hasBranchDivergence() const {
83  return PrevTTI->hasBranchDivergence();
84}
85
86bool TargetTransformInfo::isLoweredToCall(const Function *F) const {
87  return PrevTTI->isLoweredToCall(F);
88}
89
90void TargetTransformInfo::getUnrollingPreferences(Loop *L,
91                            UnrollingPreferences &UP) const {
92  PrevTTI->getUnrollingPreferences(L, UP);
93}
94
95bool TargetTransformInfo::isLegalAddImmediate(int64_t Imm) const {
96  return PrevTTI->isLegalAddImmediate(Imm);
97}
98
99bool TargetTransformInfo::isLegalICmpImmediate(int64_t Imm) const {
100  return PrevTTI->isLegalICmpImmediate(Imm);
101}
102
103bool TargetTransformInfo::isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
104                                                int64_t BaseOffset,
105                                                bool HasBaseReg,
106                                                int64_t Scale) const {
107  return PrevTTI->isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg,
108                                        Scale);
109}
110
111int TargetTransformInfo::getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
112                                              int64_t BaseOffset,
113                                              bool HasBaseReg,
114                                              int64_t Scale) const {
115  return PrevTTI->getScalingFactorCost(Ty, BaseGV, BaseOffset, HasBaseReg,
116                                       Scale);
117}
118
119bool TargetTransformInfo::isTruncateFree(Type *Ty1, Type *Ty2) const {
120  return PrevTTI->isTruncateFree(Ty1, Ty2);
121}
122
123bool TargetTransformInfo::isTypeLegal(Type *Ty) const {
124  return PrevTTI->isTypeLegal(Ty);
125}
126
127unsigned TargetTransformInfo::getJumpBufAlignment() const {
128  return PrevTTI->getJumpBufAlignment();
129}
130
131unsigned TargetTransformInfo::getJumpBufSize() const {
132  return PrevTTI->getJumpBufSize();
133}
134
135bool TargetTransformInfo::shouldBuildLookupTables() const {
136  return PrevTTI->shouldBuildLookupTables();
137}
138
139TargetTransformInfo::PopcntSupportKind
140TargetTransformInfo::getPopcntSupport(unsigned IntTyWidthInBit) const {
141  return PrevTTI->getPopcntSupport(IntTyWidthInBit);
142}
143
144bool TargetTransformInfo::haveFastSqrt(Type *Ty) const {
145  return PrevTTI->haveFastSqrt(Ty);
146}
147
148unsigned TargetTransformInfo::getIntImmCost(const APInt &Imm, Type *Ty) const {
149  return PrevTTI->getIntImmCost(Imm, Ty);
150}
151
152unsigned TargetTransformInfo::getIntImmCost(unsigned Opc, unsigned Idx,
153                                            const APInt &Imm, Type *Ty) const {
154  return PrevTTI->getIntImmCost(Opc, Idx, Imm, Ty);
155}
156
157unsigned TargetTransformInfo::getIntImmCost(Intrinsic::ID IID, unsigned Idx,
158                                            const APInt &Imm, Type *Ty) const {
159  return PrevTTI->getIntImmCost(IID, Idx, Imm, Ty);
160}
161
162unsigned TargetTransformInfo::getNumberOfRegisters(bool Vector) const {
163  return PrevTTI->getNumberOfRegisters(Vector);
164}
165
166unsigned TargetTransformInfo::getRegisterBitWidth(bool Vector) const {
167  return PrevTTI->getRegisterBitWidth(Vector);
168}
169
170unsigned TargetTransformInfo::getMaximumUnrollFactor() const {
171  return PrevTTI->getMaximumUnrollFactor();
172}
173
174unsigned TargetTransformInfo::getArithmeticInstrCost(unsigned Opcode,
175                                                Type *Ty,
176                                                OperandValueKind Op1Info,
177                                                OperandValueKind Op2Info) const {
178  return PrevTTI->getArithmeticInstrCost(Opcode, Ty, Op1Info, Op2Info);
179}
180
181unsigned TargetTransformInfo::getShuffleCost(ShuffleKind Kind, Type *Tp,
182                                             int Index, Type *SubTp) const {
183  return PrevTTI->getShuffleCost(Kind, Tp, Index, SubTp);
184}
185
186unsigned TargetTransformInfo::getCastInstrCost(unsigned Opcode, Type *Dst,
187                                               Type *Src) const {
188  return PrevTTI->getCastInstrCost(Opcode, Dst, Src);
189}
190
191unsigned TargetTransformInfo::getCFInstrCost(unsigned Opcode) const {
192  return PrevTTI->getCFInstrCost(Opcode);
193}
194
195unsigned TargetTransformInfo::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
196                                                 Type *CondTy) const {
197  return PrevTTI->getCmpSelInstrCost(Opcode, ValTy, CondTy);
198}
199
200unsigned TargetTransformInfo::getVectorInstrCost(unsigned Opcode, Type *Val,
201                                                 unsigned Index) const {
202  return PrevTTI->getVectorInstrCost(Opcode, Val, Index);
203}
204
205unsigned TargetTransformInfo::getMemoryOpCost(unsigned Opcode, Type *Src,
206                                              unsigned Alignment,
207                                              unsigned AddressSpace) const {
208  return PrevTTI->getMemoryOpCost(Opcode, Src, Alignment, AddressSpace);
209  ;
210}
211
212unsigned
213TargetTransformInfo::getIntrinsicInstrCost(Intrinsic::ID ID,
214                                           Type *RetTy,
215                                           ArrayRef<Type *> Tys) const {
216  return PrevTTI->getIntrinsicInstrCost(ID, RetTy, Tys);
217}
218
219unsigned TargetTransformInfo::getNumberOfParts(Type *Tp) const {
220  return PrevTTI->getNumberOfParts(Tp);
221}
222
223unsigned TargetTransformInfo::getAddressComputationCost(Type *Tp,
224                                                        bool IsComplex) const {
225  return PrevTTI->getAddressComputationCost(Tp, IsComplex);
226}
227
228unsigned TargetTransformInfo::getReductionCost(unsigned Opcode, Type *Ty,
229                                               bool IsPairwise) const {
230  return PrevTTI->getReductionCost(Opcode, Ty, IsPairwise);
231}
232
233namespace {
234
235struct NoTTI final : ImmutablePass, TargetTransformInfo {
236  const DataLayout *DL;
237
238  NoTTI() : ImmutablePass(ID), DL(nullptr) {
239    initializeNoTTIPass(*PassRegistry::getPassRegistry());
240  }
241
242  virtual void initializePass() override {
243    // Note that this subclass is special, and must *not* call initializeTTI as
244    // it does not chain.
245    TopTTI = this;
246    PrevTTI = nullptr;
247    DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
248    DL = DLP ? &DLP->getDataLayout() : nullptr;
249  }
250
251  virtual void getAnalysisUsage(AnalysisUsage &AU) const override {
252    // Note that this subclass is special, and must *not* call
253    // TTI::getAnalysisUsage as it breaks the recursion.
254  }
255
256  /// Pass identification.
257  static char ID;
258
259  /// Provide necessary pointer adjustments for the two base classes.
260  virtual void *getAdjustedAnalysisPointer(const void *ID) override {
261    if (ID == &TargetTransformInfo::ID)
262      return (TargetTransformInfo*)this;
263    return this;
264  }
265
266  unsigned getOperationCost(unsigned Opcode, Type *Ty,
267                            Type *OpTy) const override {
268    switch (Opcode) {
269    default:
270      // By default, just classify everything as 'basic'.
271      return TCC_Basic;
272
273    case Instruction::GetElementPtr:
274      llvm_unreachable("Use getGEPCost for GEP operations!");
275
276    case Instruction::BitCast:
277      assert(OpTy && "Cast instructions must provide the operand type");
278      if (Ty == OpTy || (Ty->isPointerTy() && OpTy->isPointerTy()))
279        // Identity and pointer-to-pointer casts are free.
280        return TCC_Free;
281
282      // Otherwise, the default basic cost is used.
283      return TCC_Basic;
284
285    case Instruction::IntToPtr: {
286      if (!DL)
287        return TCC_Basic;
288
289      // An inttoptr cast is free so long as the input is a legal integer type
290      // which doesn't contain values outside the range of a pointer.
291      unsigned OpSize = OpTy->getScalarSizeInBits();
292      if (DL->isLegalInteger(OpSize) &&
293          OpSize <= DL->getPointerTypeSizeInBits(Ty))
294        return TCC_Free;
295
296      // Otherwise it's not a no-op.
297      return TCC_Basic;
298    }
299    case Instruction::PtrToInt: {
300      if (!DL)
301        return TCC_Basic;
302
303      // A ptrtoint cast is free so long as the result is large enough to store
304      // the pointer, and a legal integer type.
305      unsigned DestSize = Ty->getScalarSizeInBits();
306      if (DL->isLegalInteger(DestSize) &&
307          DestSize >= DL->getPointerTypeSizeInBits(OpTy))
308        return TCC_Free;
309
310      // Otherwise it's not a no-op.
311      return TCC_Basic;
312    }
313    case Instruction::Trunc:
314      // trunc to a native type is free (assuming the target has compare and
315      // shift-right of the same width).
316      if (DL && DL->isLegalInteger(DL->getTypeSizeInBits(Ty)))
317        return TCC_Free;
318
319      return TCC_Basic;
320    }
321  }
322
323  unsigned getGEPCost(const Value *Ptr,
324                      ArrayRef<const Value *> Operands) const override {
325    // In the basic model, we just assume that all-constant GEPs will be folded
326    // into their uses via addressing modes.
327    for (unsigned Idx = 0, Size = Operands.size(); Idx != Size; ++Idx)
328      if (!isa<Constant>(Operands[Idx]))
329        return TCC_Basic;
330
331    return TCC_Free;
332  }
333
334  unsigned getCallCost(FunctionType *FTy, int NumArgs = -1) const override
335  {
336    assert(FTy && "FunctionType must be provided to this routine.");
337
338    // The target-independent implementation just measures the size of the
339    // function by approximating that each argument will take on average one
340    // instruction to prepare.
341
342    if (NumArgs < 0)
343      // Set the argument number to the number of explicit arguments in the
344      // function.
345      NumArgs = FTy->getNumParams();
346
347    return TCC_Basic * (NumArgs + 1);
348  }
349
350  unsigned getCallCost(const Function *F, int NumArgs = -1) const override
351  {
352    assert(F && "A concrete function must be provided to this routine.");
353
354    if (NumArgs < 0)
355      // Set the argument number to the number of explicit arguments in the
356      // function.
357      NumArgs = F->arg_size();
358
359    if (Intrinsic::ID IID = (Intrinsic::ID)F->getIntrinsicID()) {
360      FunctionType *FTy = F->getFunctionType();
361      SmallVector<Type *, 8> ParamTys(FTy->param_begin(), FTy->param_end());
362      return TopTTI->getIntrinsicCost(IID, FTy->getReturnType(), ParamTys);
363    }
364
365    if (!TopTTI->isLoweredToCall(F))
366      return TCC_Basic; // Give a basic cost if it will be lowered directly.
367
368    return TopTTI->getCallCost(F->getFunctionType(), NumArgs);
369  }
370
371  unsigned getCallCost(const Function *F,
372                       ArrayRef<const Value *> Arguments) const override {
373    // Simply delegate to generic handling of the call.
374    // FIXME: We should use instsimplify or something else to catch calls which
375    // will constant fold with these arguments.
376    return TopTTI->getCallCost(F, Arguments.size());
377  }
378
379  unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
380                            ArrayRef<Type *> ParamTys) const override {
381    switch (IID) {
382    default:
383      // Intrinsics rarely (if ever) have normal argument setup constraints.
384      // Model them as having a basic instruction cost.
385      // FIXME: This is wrong for libc intrinsics.
386      return TCC_Basic;
387
388    case Intrinsic::dbg_declare:
389    case Intrinsic::dbg_value:
390    case Intrinsic::invariant_start:
391    case Intrinsic::invariant_end:
392    case Intrinsic::lifetime_start:
393    case Intrinsic::lifetime_end:
394    case Intrinsic::objectsize:
395    case Intrinsic::ptr_annotation:
396    case Intrinsic::var_annotation:
397      // These intrinsics don't actually represent code after lowering.
398      return TCC_Free;
399    }
400  }
401
402  unsigned
403  getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
404                   ArrayRef<const Value *> Arguments) const override {
405    // Delegate to the generic intrinsic handling code. This mostly provides an
406    // opportunity for targets to (for example) special case the cost of
407    // certain intrinsics based on constants used as arguments.
408    SmallVector<Type *, 8> ParamTys;
409    ParamTys.reserve(Arguments.size());
410    for (unsigned Idx = 0, Size = Arguments.size(); Idx != Size; ++Idx)
411      ParamTys.push_back(Arguments[Idx]->getType());
412    return TopTTI->getIntrinsicCost(IID, RetTy, ParamTys);
413  }
414
415  unsigned getUserCost(const User *U) const override {
416    if (isa<PHINode>(U))
417      return TCC_Free; // Model all PHI nodes as free.
418
419    if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
420      SmallVector<const Value *, 4> Indices(GEP->idx_begin(), GEP->idx_end());
421      return TopTTI->getGEPCost(GEP->getPointerOperand(), Indices);
422    }
423
424    if (ImmutableCallSite CS = U) {
425      const Function *F = CS.getCalledFunction();
426      if (!F) {
427        // Just use the called value type.
428        Type *FTy = CS.getCalledValue()->getType()->getPointerElementType();
429        return TopTTI->getCallCost(cast<FunctionType>(FTy), CS.arg_size());
430      }
431
432      SmallVector<const Value *, 8> Arguments(CS.arg_begin(), CS.arg_end());
433      return TopTTI->getCallCost(F, Arguments);
434    }
435
436    if (const CastInst *CI = dyn_cast<CastInst>(U)) {
437      // Result of a cmp instruction is often extended (to be used by other
438      // cmp instructions, logical or return instructions). These are usually
439      // nop on most sane targets.
440      if (isa<CmpInst>(CI->getOperand(0)))
441        return TCC_Free;
442    }
443
444    // Otherwise delegate to the fully generic implementations.
445    return getOperationCost(Operator::getOpcode(U), U->getType(),
446                            U->getNumOperands() == 1 ?
447                                U->getOperand(0)->getType() : nullptr);
448  }
449
450  bool hasBranchDivergence() const override { return false; }
451
452  bool isLoweredToCall(const Function *F) const override {
453    // FIXME: These should almost certainly not be handled here, and instead
454    // handled with the help of TLI or the target itself. This was largely
455    // ported from existing analysis heuristics here so that such refactorings
456    // can take place in the future.
457
458    if (F->isIntrinsic())
459      return false;
460
461    if (F->hasLocalLinkage() || !F->hasName())
462      return true;
463
464    StringRef Name = F->getName();
465
466    // These will all likely lower to a single selection DAG node.
467    if (Name == "copysign" || Name == "copysignf" || Name == "copysignl" ||
468        Name == "fabs" || Name == "fabsf" || Name == "fabsl" || Name == "sin" ||
469        Name == "sinf" || Name == "sinl" || Name == "cos" || Name == "cosf" ||
470        Name == "cosl" || Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl")
471      return false;
472
473    // These are all likely to be optimized into something smaller.
474    if (Name == "pow" || Name == "powf" || Name == "powl" || Name == "exp2" ||
475        Name == "exp2l" || Name == "exp2f" || Name == "floor" || Name ==
476        "floorf" || Name == "ceil" || Name == "round" || Name == "ffs" ||
477        Name == "ffsl" || Name == "abs" || Name == "labs" || Name == "llabs")
478      return false;
479
480    return true;
481  }
482
483  void getUnrollingPreferences(Loop *, UnrollingPreferences &) const override {
484  }
485
486  bool isLegalAddImmediate(int64_t Imm) const override {
487    return false;
488  }
489
490  bool isLegalICmpImmediate(int64_t Imm) const override {
491    return false;
492  }
493
494  bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
495                             bool HasBaseReg, int64_t Scale) const override
496  {
497    // Guess that reg+reg addressing is allowed. This heuristic is taken from
498    // the implementation of LSR.
499    return !BaseGV && BaseOffset == 0 && Scale <= 1;
500  }
501
502  int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
503                           bool HasBaseReg, int64_t Scale) const override {
504    // Guess that all legal addressing mode are free.
505    if(isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg, Scale))
506      return 0;
507    return -1;
508  }
509
510  bool isTruncateFree(Type *Ty1, Type *Ty2) const override {
511    return false;
512  }
513
514  bool isTypeLegal(Type *Ty) const override {
515    return false;
516  }
517
518  unsigned getJumpBufAlignment() const override {
519    return 0;
520  }
521
522  unsigned getJumpBufSize() const override {
523    return 0;
524  }
525
526  bool shouldBuildLookupTables() const override {
527    return true;
528  }
529
530  PopcntSupportKind
531  getPopcntSupport(unsigned IntTyWidthInBit) const override {
532    return PSK_Software;
533  }
534
535  bool haveFastSqrt(Type *Ty) const override {
536    return false;
537  }
538
539  unsigned getIntImmCost(const APInt &Imm, Type *Ty) const override {
540    return TCC_Basic;
541  }
542
543  unsigned getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
544                         Type *Ty) const override {
545    return TCC_Free;
546  }
547
548  unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
549                         Type *Ty) const override {
550    return TCC_Free;
551  }
552
553  unsigned getNumberOfRegisters(bool Vector) const override {
554    return 8;
555  }
556
557  unsigned  getRegisterBitWidth(bool Vector) const override {
558    return 32;
559  }
560
561  unsigned getMaximumUnrollFactor() const override {
562    return 1;
563  }
564
565  unsigned getArithmeticInstrCost(unsigned Opcode, Type *Ty, OperandValueKind,
566                                  OperandValueKind) const override {
567    return 1;
568  }
569
570  unsigned getShuffleCost(ShuffleKind Kind, Type *Ty,
571                          int Index = 0, Type *SubTp = nullptr) const override {
572    return 1;
573  }
574
575  unsigned getCastInstrCost(unsigned Opcode, Type *Dst,
576                            Type *Src) const override {
577    return 1;
578  }
579
580  unsigned getCFInstrCost(unsigned Opcode) const override {
581    return 1;
582  }
583
584  unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
585                              Type *CondTy = nullptr) const override {
586    return 1;
587  }
588
589  unsigned getVectorInstrCost(unsigned Opcode, Type *Val,
590                              unsigned Index = -1) const override {
591    return 1;
592  }
593
594  unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
595                           unsigned AddressSpace) const override {
596    return 1;
597  }
598
599  unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
600                                 ArrayRef<Type*> Tys) const override {
601    return 1;
602  }
603
604  unsigned getNumberOfParts(Type *Tp) const override {
605    return 0;
606  }
607
608  unsigned getAddressComputationCost(Type *Tp, bool) const override {
609    return 0;
610  }
611
612  unsigned getReductionCost(unsigned, Type *, bool) const override {
613    return 1;
614  }
615};
616
617} // end anonymous namespace
618
619INITIALIZE_AG_PASS(NoTTI, TargetTransformInfo, "notti",
620                   "No target information", true, true, true)
621char NoTTI::ID = 0;
622
623ImmutablePass *llvm::createNoTargetTransformInfoPass() {
624  return new NoTTI();
625}
626