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