Bug Summary

File:lib/Target/Hexagon/HexagonTargetTransformInfo.cpp
Warning:line 77, column 25
Called C++ object pointer is null

Annotated Source Code

/build/llvm-toolchain-snapshot-6.0~svn318801/lib/Target/Hexagon/HexagonTargetTransformInfo.cpp

1//===- HexagonTargetTransformInfo.cpp - Hexagon specific TTI pass ---------===//
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/// \file
9/// This file implements a TargetTransformInfo analysis pass specific to the
10/// Hexagon target machine. It uses the target's detailed information to provide
11/// more precise answers to certain TTI queries, while letting the target
12/// independent and default TTI implementations handle the rest.
13///
14//===----------------------------------------------------------------------===//
15
16#include "HexagonTargetTransformInfo.h"
17#include "HexagonSubtarget.h"
18#include "llvm/Analysis/TargetTransformInfo.h"
19#include "llvm/IR/InstrTypes.h"
20#include "llvm/IR/Instructions.h"
21#include "llvm/IR/User.h"
22#include "llvm/Support/Casting.h"
23#include "llvm/Support/CommandLine.h"
24
25using namespace llvm;
26
27#define DEBUG_TYPE"hexagontti" "hexagontti"
28
29static cl::opt<bool> EmitLookupTables("hexagon-emit-lookup-tables",
30 cl::init(true), cl::Hidden,
31 cl::desc("Control lookup table emission on Hexagon target"));
32
33TargetTransformInfo::PopcntSupportKind
34HexagonTTIImpl::getPopcntSupport(unsigned IntTyWidthInBit) const {
35 // Return Fast Hardware support as every input < 64 bits will be promoted
36 // to 64 bits.
37 return TargetTransformInfo::PSK_FastHardware;
38}
39
40// The Hexagon target can unroll loops with run-time trip counts.
41void HexagonTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
42 TTI::UnrollingPreferences &UP) {
43 UP.Runtime = UP.Partial = true;
44}
45
46unsigned HexagonTTIImpl::getNumberOfRegisters(bool vector) const {
47 return vector ? 0 : 32;
48}
49
50unsigned HexagonTTIImpl::getPrefetchDistance() const {
51 return getST()->getL1PrefetchDistance();
52}
53
54unsigned HexagonTTIImpl::getCacheLineSize() const {
55 return getST()->getL1CacheLineSize();
56}
57
58int HexagonTTIImpl::getUserCost(const User *U,
59 ArrayRef<const Value *> Operands) {
60 auto isCastFoldedIntoLoad = [](const CastInst *CI) -> bool {
61 if (!CI->isIntegerCast())
62 return false;
63 const LoadInst *LI = dyn_cast<const LoadInst>(CI->getOperand(0));
64 // Technically, this code could allow multiple uses of the load, and
65 // check if all the uses are the same extension operation, but this
66 // should be sufficient for most cases.
67 if (!LI || !LI->hasOneUse())
68 return false;
69
70 // Only extensions from an integer type shorter than 32-bit to i32
71 // can be folded into the load.
72 unsigned SBW = CI->getSrcTy()->getIntegerBitWidth();
73 unsigned DBW = CI->getDestTy()->getIntegerBitWidth();
74 return DBW == 32 && (SBW < DBW);
75 };
76
77 if (const CastInst *CI = dyn_cast<const CastInst>(U))
1
Taking false branch
78 if (isCastFoldedIntoLoad(CI))
79 return TargetTransformInfo::TCC_Free;
80 return BaseT::getUserCost(U, Operands);
2
Calling 'TargetTransformInfoImplCRTPBase::getUserCost'
81}
82
83bool HexagonTTIImpl::shouldBuildLookupTables() const {
84 return EmitLookupTables;
85}

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

/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/CodeGen/BasicTTIImpl.h

1//===- BasicTTIImpl.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//
10/// \file
11/// This file provides a helper that implements much of the TTI interface in
12/// terms of the target-independent code generator and TargetLowering
13/// interfaces.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_CODEGEN_BASICTTIIMPL_H
18#define LLVM_CODEGEN_BASICTTIIMPL_H
19
20#include "llvm/ADT/APInt.h"
21#include "llvm/ADT/ArrayRef.h"
22#include "llvm/ADT/BitVector.h"
23#include "llvm/ADT/SmallPtrSet.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/Analysis/LoopInfo.h"
26#include "llvm/Analysis/TargetTransformInfo.h"
27#include "llvm/Analysis/TargetTransformInfoImpl.h"
28#include "llvm/CodeGen/ISDOpcodes.h"
29#include "llvm/CodeGen/MachineValueType.h"
30#include "llvm/CodeGen/TargetLowering.h"
31#include "llvm/CodeGen/TargetSubtargetInfo.h"
32#include "llvm/CodeGen/ValueTypes.h"
33#include "llvm/IR/BasicBlock.h"
34#include "llvm/IR/CallSite.h"
35#include "llvm/IR/Constant.h"
36#include "llvm/IR/Constants.h"
37#include "llvm/IR/DataLayout.h"
38#include "llvm/IR/DerivedTypes.h"
39#include "llvm/IR/InstrTypes.h"
40#include "llvm/IR/Instruction.h"
41#include "llvm/IR/Instructions.h"
42#include "llvm/IR/Intrinsics.h"
43#include "llvm/IR/Operator.h"
44#include "llvm/IR/Type.h"
45#include "llvm/IR/Value.h"
46#include "llvm/MC/MCSchedule.h"
47#include "llvm/Support/Casting.h"
48#include "llvm/Support/CommandLine.h"
49#include "llvm/Support/ErrorHandling.h"
50#include "llvm/Support/MathExtras.h"
51#include <algorithm>
52#include <cassert>
53#include <cstdint>
54#include <limits>
55#include <utility>
56
57namespace llvm {
58
59class Function;
60class GlobalValue;
61class LLVMContext;
62class ScalarEvolution;
63class SCEV;
64class TargetMachine;
65
66extern cl::opt<unsigned> PartialUnrollingThreshold;
67
68/// \brief Base class which can be used to help build a TTI implementation.
69///
70/// This class provides as much implementation of the TTI interface as is
71/// possible using the target independent parts of the code generator.
72///
73/// In order to subclass it, your class must implement a getST() method to
74/// return the subtarget, and a getTLI() method to return the target lowering.
75/// We need these methods implemented in the derived class so that this class
76/// doesn't have to duplicate storage for them.
77template <typename T>
78class BasicTTIImplBase : public TargetTransformInfoImplCRTPBase<T> {
79private:
80 using BaseT = TargetTransformInfoImplCRTPBase<T>;
81 using TTI = TargetTransformInfo;
82
83 /// Estimate a cost of shuffle as a sequence of extract and insert
84 /// operations.
85 unsigned getPermuteShuffleOverhead(Type *Ty) {
86 assert(Ty->isVectorTy() && "Can only shuffle vectors")(static_cast <bool> (Ty->isVectorTy() && "Can only shuffle vectors"
) ? void (0) : __assert_fail ("Ty->isVectorTy() && \"Can only shuffle vectors\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/CodeGen/BasicTTIImpl.h"
, 86, __extension__ __PRETTY_FUNCTION__))
;
87 unsigned Cost = 0;
88 // Shuffle cost is equal to the cost of extracting element from its argument
89 // plus the cost of inserting them onto the result vector.
90
91 // e.g. <4 x float> has a mask of <0,5,2,7> i.e we need to extract from
92 // index 0 of first vector, index 1 of second vector,index 2 of first
93 // vector and finally index 3 of second vector and insert them at index
94 // <0,1,2,3> of result vector.
95 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
96 Cost += static_cast<T *>(this)
97 ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
98 Cost += static_cast<T *>(this)
99 ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
100 }
101 return Cost;
102 }
103
104 /// \brief Local query method delegates up to T which *must* implement this!
105 const TargetSubtargetInfo *getST() const {
106 return static_cast<const T *>(this)->getST();
107 }
108
109 /// \brief Local query method delegates up to T which *must* implement this!
110 const TargetLoweringBase *getTLI() const {
111 return static_cast<const T *>(this)->getTLI();
112 }
113
114protected:
115 explicit BasicTTIImplBase(const TargetMachine *TM, const DataLayout &DL)
116 : BaseT(DL) {}
117
118 using TargetTransformInfoImplBase::DL;
119
120public:
121 /// \name Scalar TTI Implementations
122 /// @{
123 bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
124 unsigned BitWidth, unsigned AddressSpace,
125 unsigned Alignment, bool *Fast) const {
126 EVT E = EVT::getIntegerVT(Context, BitWidth);
127 return getTLI()->allowsMisalignedMemoryAccesses(E, AddressSpace, Alignment, Fast);
128 }
129
130 bool hasBranchDivergence() { return false; }
131
132 bool isSourceOfDivergence(const Value *V) { return false; }
133
134 bool isAlwaysUniform(const Value *V) { return false; }
135
136 unsigned getFlatAddressSpace() {
137 // Return an invalid address space.
138 return -1;
139 }
140
141 bool isLegalAddImmediate(int64_t imm) {
142 return getTLI()->isLegalAddImmediate(imm);
143 }
144
145 bool isLegalICmpImmediate(int64_t imm) {
146 return getTLI()->isLegalICmpImmediate(imm);
147 }
148
149 bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
150 bool HasBaseReg, int64_t Scale,
151 unsigned AddrSpace, Instruction *I = nullptr) {
152 TargetLoweringBase::AddrMode AM;
153 AM.BaseGV = BaseGV;
154 AM.BaseOffs = BaseOffset;
155 AM.HasBaseReg = HasBaseReg;
156 AM.Scale = Scale;
157 return getTLI()->isLegalAddressingMode(DL, AM, Ty, AddrSpace, I);
158 }
159
160 bool isLSRCostLess(TTI::LSRCost C1, TTI::LSRCost C2) {
161 return TargetTransformInfoImplBase::isLSRCostLess(C1, C2);
162 }
163
164 int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
165 bool HasBaseReg, int64_t Scale, unsigned AddrSpace) {
166 TargetLoweringBase::AddrMode AM;
167 AM.BaseGV = BaseGV;
168 AM.BaseOffs = BaseOffset;
169 AM.HasBaseReg = HasBaseReg;
170 AM.Scale = Scale;
171 return getTLI()->getScalingFactorCost(DL, AM, Ty, AddrSpace);
172 }
173
174 bool isTruncateFree(Type *Ty1, Type *Ty2) {
175 return getTLI()->isTruncateFree(Ty1, Ty2);
176 }
177
178 bool isProfitableToHoist(Instruction *I) {
179 return getTLI()->isProfitableToHoist(I);
180 }
181
182 bool isTypeLegal(Type *Ty) {
183 EVT VT = getTLI()->getValueType(DL, Ty);
184 return getTLI()->isTypeLegal(VT);
185 }
186
187 int getGEPCost(Type *PointeeType, const Value *Ptr,
188 ArrayRef<const Value *> Operands) {
189 return BaseT::getGEPCost(PointeeType, Ptr, Operands);
190 }
191
192 int getExtCost(const Instruction *I, const Value *Src) {
193 if (getTLI()->isExtFree(I))
194 return TargetTransformInfo::TCC_Free;
195
196 if (isa<ZExtInst>(I) || isa<SExtInst>(I))
197 if (const LoadInst *LI = dyn_cast<LoadInst>(Src))
198 if (getTLI()->isExtLoad(LI, I, DL))
199 return TargetTransformInfo::TCC_Free;
200
201 return TargetTransformInfo::TCC_Basic;
202 }
203
204 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
205 ArrayRef<const Value *> Arguments) {
206 return BaseT::getIntrinsicCost(IID, RetTy, Arguments);
207 }
208
209 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
210 ArrayRef<Type *> ParamTys) {
211 if (IID == Intrinsic::cttz) {
212 if (getTLI()->isCheapToSpeculateCttz())
213 return TargetTransformInfo::TCC_Basic;
214 return TargetTransformInfo::TCC_Expensive;
215 }
216
217 if (IID == Intrinsic::ctlz) {
218 if (getTLI()->isCheapToSpeculateCtlz())
219 return TargetTransformInfo::TCC_Basic;
220 return TargetTransformInfo::TCC_Expensive;
221 }
222
223 return BaseT::getIntrinsicCost(IID, RetTy, ParamTys);
224 }
225
226 unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
227 unsigned &JumpTableSize) {
228 /// Try to find the estimated number of clusters. Note that the number of
229 /// clusters identified in this function could be different from the actural
230 /// numbers found in lowering. This function ignore switches that are
231 /// lowered with a mix of jump table / bit test / BTree. This function was
232 /// initially intended to be used when estimating the cost of switch in
233 /// inline cost heuristic, but it's a generic cost model to be used in other
234 /// places (e.g., in loop unrolling).
235 unsigned N = SI.getNumCases();
236 const TargetLoweringBase *TLI = getTLI();
237 const DataLayout &DL = this->getDataLayout();
238
239 JumpTableSize = 0;
240 bool IsJTAllowed = TLI->areJTsAllowed(SI.getParent()->getParent());
241
242 // Early exit if both a jump table and bit test are not allowed.
243 if (N < 1 || (!IsJTAllowed && DL.getPointerSizeInBits() < N))
244 return N;
245
246 APInt MaxCaseVal = SI.case_begin()->getCaseValue()->getValue();
247 APInt MinCaseVal = MaxCaseVal;
248 for (auto CI : SI.cases()) {
249 const APInt &CaseVal = CI.getCaseValue()->getValue();
250 if (CaseVal.sgt(MaxCaseVal))
251 MaxCaseVal = CaseVal;
252 if (CaseVal.slt(MinCaseVal))
253 MinCaseVal = CaseVal;
254 }
255
256 // Check if suitable for a bit test
257 if (N <= DL.getPointerSizeInBits()) {
258 SmallPtrSet<const BasicBlock *, 4> Dests;
259 for (auto I : SI.cases())
260 Dests.insert(I.getCaseSuccessor());
261
262 if (TLI->isSuitableForBitTests(Dests.size(), N, MinCaseVal, MaxCaseVal,
263 DL))
264 return 1;
265 }
266
267 // Check if suitable for a jump table.
268 if (IsJTAllowed) {
269 if (N < 2 || N < TLI->getMinimumJumpTableEntries())
270 return N;
271 uint64_t Range =
272 (MaxCaseVal - MinCaseVal)
273 .getLimitedValue(std::numeric_limits<uint64_t>::max() - 1) + 1;
274 // Check whether a range of clusters is dense enough for a jump table
275 if (TLI->isSuitableForJumpTable(&SI, N, Range)) {
276 JumpTableSize = Range;
277 return 1;
278 }
279 }
280 return N;
281 }
282
283 unsigned getJumpBufAlignment() { return getTLI()->getJumpBufAlignment(); }
284
285 unsigned getJumpBufSize() { return getTLI()->getJumpBufSize(); }
286
287 bool shouldBuildLookupTables() {
288 const TargetLoweringBase *TLI = getTLI();
289 return TLI->isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
290 TLI->isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
291 }
292
293 bool haveFastSqrt(Type *Ty) {
294 const TargetLoweringBase *TLI = getTLI();
295 EVT VT = TLI->getValueType(DL, Ty);
296 return TLI->isTypeLegal(VT) &&
297 TLI->isOperationLegalOrCustom(ISD::FSQRT, VT);
298 }
299
300 unsigned getFPOpCost(Type *Ty) {
301 // By default, FP instructions are no more expensive since they are
302 // implemented in HW. Target specific TTI can override this.
303 return TargetTransformInfo::TCC_Basic;
304 }
305
306 unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) {
307 const TargetLoweringBase *TLI = getTLI();
308 switch (Opcode) {
12
Control jumps to the 'default' case at line 309
309 default: break;
13
Execution continues on line 320
310 case Instruction::Trunc:
311 if (TLI->isTruncateFree(OpTy, Ty))
312 return TargetTransformInfo::TCC_Free;
313 return TargetTransformInfo::TCC_Basic;
314 case Instruction::ZExt:
315 if (TLI->isZExtFree(OpTy, Ty))
316 return TargetTransformInfo::TCC_Free;
317 return TargetTransformInfo::TCC_Basic;
318 }
319
320 return BaseT::getOperationCost(Opcode, Ty, OpTy);
14
Passing null pointer value via 3rd parameter 'OpTy'
15
Calling 'TargetTransformInfoImplBase::getOperationCost'
321 }
322
323 unsigned getInliningThresholdMultiplier() { return 1; }
324
325 void getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
326 TTI::UnrollingPreferences &UP) {
327 // This unrolling functionality is target independent, but to provide some
328 // motivation for its intended use, for x86:
329
330 // According to the Intel 64 and IA-32 Architectures Optimization Reference
331 // Manual, Intel Core models and later have a loop stream detector (and
332 // associated uop queue) that can benefit from partial unrolling.
333 // The relevant requirements are:
334 // - The loop must have no more than 4 (8 for Nehalem and later) branches
335 // taken, and none of them may be calls.
336 // - The loop can have no more than 18 (28 for Nehalem and later) uops.
337
338 // According to the Software Optimization Guide for AMD Family 15h
339 // Processors, models 30h-4fh (Steamroller and later) have a loop predictor
340 // and loop buffer which can benefit from partial unrolling.
341 // The relevant requirements are:
342 // - The loop must have fewer than 16 branches
343 // - The loop must have less than 40 uops in all executed loop branches
344
345 // The number of taken branches in a loop is hard to estimate here, and
346 // benchmarking has revealed that it is better not to be conservative when
347 // estimating the branch count. As a result, we'll ignore the branch limits
348 // until someone finds a case where it matters in practice.
349
350 unsigned MaxOps;
351 const TargetSubtargetInfo *ST = getST();
352 if (PartialUnrollingThreshold.getNumOccurrences() > 0)
353 MaxOps = PartialUnrollingThreshold;
354 else if (ST->getSchedModel().LoopMicroOpBufferSize > 0)
355 MaxOps = ST->getSchedModel().LoopMicroOpBufferSize;
356 else
357 return;
358
359 // Scan the loop: don't unroll loops with calls.
360 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
361 ++I) {
362 BasicBlock *BB = *I;
363
364 for (BasicBlock::iterator J = BB->begin(), JE = BB->end(); J != JE; ++J)
365 if (isa<CallInst>(J) || isa<InvokeInst>(J)) {
366 ImmutableCallSite CS(&*J);
367 if (const Function *F = CS.getCalledFunction()) {
368 if (!static_cast<T *>(this)->isLoweredToCall(F))
369 continue;
370 }
371
372 return;
373 }
374 }
375
376 // Enable runtime and partial unrolling up to the specified size.
377 // Enable using trip count upper bound to unroll loops.
378 UP.Partial = UP.Runtime = UP.UpperBound = true;
379 UP.PartialThreshold = MaxOps;
380
381 // Avoid unrolling when optimizing for size.
382 UP.OptSizeThreshold = 0;
383 UP.PartialOptSizeThreshold = 0;
384
385 // Set number of instructions optimized when "back edge"
386 // becomes "fall through" to default value of 2.
387 UP.BEInsns = 2;
388 }
389
390 int getInstructionLatency(const Instruction *I) {
391 if (isa<LoadInst>(I))
392 return getST()->getSchedModel().DefaultLoadLatency;
393
394 return BaseT::getInstructionLatency(I);
395 }
396
397 /// @}
398
399 /// \name Vector TTI Implementations
400 /// @{
401
402 unsigned getNumberOfRegisters(bool Vector) { return Vector ? 0 : 1; }
403
404 unsigned getRegisterBitWidth(bool Vector) const { return 32; }
405
406 /// Estimate the overhead of scalarizing an instruction. Insert and Extract
407 /// are set if the result needs to be inserted and/or extracted from vectors.
408 unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) {
409 assert(Ty->isVectorTy() && "Can only scalarize vectors")(static_cast <bool> (Ty->isVectorTy() && "Can only scalarize vectors"
) ? void (0) : __assert_fail ("Ty->isVectorTy() && \"Can only scalarize vectors\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/CodeGen/BasicTTIImpl.h"
, 409, __extension__ __PRETTY_FUNCTION__))
;
410 unsigned Cost = 0;
411
412 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
413 if (Insert)
414 Cost += static_cast<T *>(this)
415 ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
416 if (Extract)
417 Cost += static_cast<T *>(this)
418 ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
419 }
420
421 return Cost;
422 }
423
424 /// Estimate the overhead of scalarizing an instructions unique
425 /// non-constant operands. The types of the arguments are ordinarily
426 /// scalar, in which case the costs are multiplied with VF.
427 unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
428 unsigned VF) {
429 unsigned Cost = 0;
430 SmallPtrSet<const Value*, 4> UniqueOperands;
431 for (const Value *A : Args) {
432 if (!isa<Constant>(A) && UniqueOperands.insert(A).second) {
433 Type *VecTy = nullptr;
434 if (A->getType()->isVectorTy()) {
435 VecTy = A->getType();
436 // If A is a vector operand, VF should be 1 or correspond to A.
437 assert((VF == 1 || VF == VecTy->getVectorNumElements()) &&(static_cast <bool> ((VF == 1 || VF == VecTy->getVectorNumElements
()) && "Vector argument does not match VF") ? void (0
) : __assert_fail ("(VF == 1 || VF == VecTy->getVectorNumElements()) && \"Vector argument does not match VF\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/CodeGen/BasicTTIImpl.h"
, 438, __extension__ __PRETTY_FUNCTION__))
438 "Vector argument does not match VF")(static_cast <bool> ((VF == 1 || VF == VecTy->getVectorNumElements
()) && "Vector argument does not match VF") ? void (0
) : __assert_fail ("(VF == 1 || VF == VecTy->getVectorNumElements()) && \"Vector argument does not match VF\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/CodeGen/BasicTTIImpl.h"
, 438, __extension__ __PRETTY_FUNCTION__))
;
439 }
440 else
441 VecTy = VectorType::get(A->getType(), VF);
442
443 Cost += getScalarizationOverhead(VecTy, false, true);
444 }
445 }
446
447 return Cost;
448 }
449
450 unsigned getScalarizationOverhead(Type *VecTy, ArrayRef<const Value *> Args) {
451 assert(VecTy->isVectorTy())(static_cast <bool> (VecTy->isVectorTy()) ? void (0)
: __assert_fail ("VecTy->isVectorTy()", "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/CodeGen/BasicTTIImpl.h"
, 451, __extension__ __PRETTY_FUNCTION__))
;
452
453 unsigned Cost = 0;
454
455 Cost += getScalarizationOverhead(VecTy, true, false);
456 if (!Args.empty())
457 Cost += getOperandsScalarizationOverhead(Args,
458 VecTy->getVectorNumElements());
459 else
460 // When no information on arguments is provided, we add the cost
461 // associated with one argument as a heuristic.
462 Cost += getScalarizationOverhead(VecTy, false, true);
463
464 return Cost;
465 }
466
467 unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
468
469 unsigned getArithmeticInstrCost(
470 unsigned Opcode, Type *Ty,
471 TTI::OperandValueKind Opd1Info = TTI::OK_AnyValue,
472 TTI::OperandValueKind Opd2Info = TTI::OK_AnyValue,
473 TTI::OperandValueProperties Opd1PropInfo = TTI::OP_None,
474 TTI::OperandValueProperties Opd2PropInfo = TTI::OP_None,
475 ArrayRef<const Value *> Args = ArrayRef<const Value *>()) {
476 // Check if any of the operands are vector operands.
477 const TargetLoweringBase *TLI = getTLI();
478 int ISD = TLI->InstructionOpcodeToISD(Opcode);
479 assert(ISD && "Invalid opcode")(static_cast <bool> (ISD && "Invalid opcode") ?
void (0) : __assert_fail ("ISD && \"Invalid opcode\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/CodeGen/BasicTTIImpl.h"
, 479, __extension__ __PRETTY_FUNCTION__))
;
480
481 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
482
483 bool IsFloat = Ty->isFPOrFPVectorTy();
484 // Assume that floating point arithmetic operations cost twice as much as
485 // integer operations.
486 unsigned OpCost = (IsFloat ? 2 : 1);
487
488 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
489 // The operation is legal. Assume it costs 1.
490 // TODO: Once we have extract/insert subvector cost we need to use them.
491 return LT.first * OpCost;
492 }
493
494 if (!TLI->isOperationExpand(ISD, LT.second)) {
495 // If the operation is custom lowered, then assume that the code is twice
496 // as expensive.
497 return LT.first * 2 * OpCost;
498 }
499
500 // Else, assume that we need to scalarize this op.
501 // TODO: If one of the types get legalized by splitting, handle this
502 // similarly to what getCastInstrCost() does.
503 if (Ty->isVectorTy()) {
504 unsigned Num = Ty->getVectorNumElements();
505 unsigned Cost = static_cast<T *>(this)
506 ->getArithmeticInstrCost(Opcode, Ty->getScalarType());
507 // Return the cost of multiple scalar invocation plus the cost of
508 // inserting and extracting the values.
509 return getScalarizationOverhead(Ty, Args) + Num * Cost;
510 }
511
512 // We don't know anything about this scalar instruction.
513 return OpCost;
514 }
515
516 unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
517 Type *SubTp) {
518 if (Kind == TTI::SK_Alternate || Kind == TTI::SK_PermuteTwoSrc ||
519 Kind == TTI::SK_PermuteSingleSrc) {
520 return getPermuteShuffleOverhead(Tp);
521 }
522 return 1;
523 }
524
525 unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
526 const Instruction *I = nullptr) {
527 const TargetLoweringBase *TLI = getTLI();
528 int ISD = TLI->InstructionOpcodeToISD(Opcode);
529 assert(ISD && "Invalid opcode")(static_cast <bool> (ISD && "Invalid opcode") ?
void (0) : __assert_fail ("ISD && \"Invalid opcode\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/CodeGen/BasicTTIImpl.h"
, 529, __extension__ __PRETTY_FUNCTION__))
;
530 std::pair<unsigned, MVT> SrcLT = TLI->getTypeLegalizationCost(DL, Src);
531 std::pair<unsigned, MVT> DstLT = TLI->getTypeLegalizationCost(DL, Dst);
532
533 // Check for NOOP conversions.
534 if (SrcLT.first == DstLT.first &&
535 SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
536
537 // Bitcast between types that are legalized to the same type are free.
538 if (Opcode == Instruction::BitCast || Opcode == Instruction::Trunc)
539 return 0;
540 }
541
542 if (Opcode == Instruction::Trunc &&
543 TLI->isTruncateFree(SrcLT.second, DstLT.second))
544 return 0;
545
546 if (Opcode == Instruction::ZExt &&
547 TLI->isZExtFree(SrcLT.second, DstLT.second))
548 return 0;
549
550 if (Opcode == Instruction::AddrSpaceCast &&
551 TLI->isNoopAddrSpaceCast(Src->getPointerAddressSpace(),
552 Dst->getPointerAddressSpace()))
553 return 0;
554
555 // If this is a zext/sext of a load, return 0 if the corresponding
556 // extending load exists on target.
557 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
558 I && isa<LoadInst>(I->getOperand(0))) {
559 EVT ExtVT = EVT::getEVT(Dst);
560 EVT LoadVT = EVT::getEVT(Src);
561 unsigned LType =
562 ((Opcode == Instruction::ZExt) ? ISD::ZEXTLOAD : ISD::SEXTLOAD);
563 if (TLI->isLoadExtLegal(LType, ExtVT, LoadVT))
564 return 0;
565 }
566
567 // If the cast is marked as legal (or promote) then assume low cost.
568 if (SrcLT.first == DstLT.first &&
569 TLI->isOperationLegalOrPromote(ISD, DstLT.second))
570 return 1;
571
572 // Handle scalar conversions.
573 if (!Src->isVectorTy() && !Dst->isVectorTy()) {
574 // Scalar bitcasts are usually free.
575 if (Opcode == Instruction::BitCast)
576 return 0;
577
578 // Just check the op cost. If the operation is legal then assume it costs
579 // 1.
580 if (!TLI->isOperationExpand(ISD, DstLT.second))
581 return 1;
582
583 // Assume that illegal scalar instruction are expensive.
584 return 4;
585 }
586
587 // Check vector-to-vector casts.
588 if (Dst->isVectorTy() && Src->isVectorTy()) {
589 // If the cast is between same-sized registers, then the check is simple.
590 if (SrcLT.first == DstLT.first &&
591 SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
592
593 // Assume that Zext is done using AND.
594 if (Opcode == Instruction::ZExt)
595 return 1;
596
597 // Assume that sext is done using SHL and SRA.
598 if (Opcode == Instruction::SExt)
599 return 2;
600
601 // Just check the op cost. If the operation is legal then assume it
602 // costs
603 // 1 and multiply by the type-legalization overhead.
604 if (!TLI->isOperationExpand(ISD, DstLT.second))
605 return SrcLT.first * 1;
606 }
607
608 // If we are legalizing by splitting, query the concrete TTI for the cost
609 // of casting the original vector twice. We also need to factor int the
610 // cost of the split itself. Count that as 1, to be consistent with
611 // TLI->getTypeLegalizationCost().
612 if ((TLI->getTypeAction(Src->getContext(), TLI->getValueType(DL, Src)) ==
613 TargetLowering::TypeSplitVector) ||
614 (TLI->getTypeAction(Dst->getContext(), TLI->getValueType(DL, Dst)) ==
615 TargetLowering::TypeSplitVector)) {
616 Type *SplitDst = VectorType::get(Dst->getVectorElementType(),
617 Dst->getVectorNumElements() / 2);
618 Type *SplitSrc = VectorType::get(Src->getVectorElementType(),
619 Src->getVectorNumElements() / 2);
620 T *TTI = static_cast<T *>(this);
621 return TTI->getVectorSplitCost() +
622 (2 * TTI->getCastInstrCost(Opcode, SplitDst, SplitSrc, I));
623 }
624
625 // In other cases where the source or destination are illegal, assume
626 // the operation will get scalarized.
627 unsigned Num = Dst->getVectorNumElements();
628 unsigned Cost = static_cast<T *>(this)->getCastInstrCost(
629 Opcode, Dst->getScalarType(), Src->getScalarType(), I);
630
631 // Return the cost of multiple scalar invocation plus the cost of
632 // inserting and extracting the values.
633 return getScalarizationOverhead(Dst, true, true) + Num * Cost;
634 }
635
636 // We already handled vector-to-vector and scalar-to-scalar conversions.
637 // This
638 // is where we handle bitcast between vectors and scalars. We need to assume
639 // that the conversion is scalarized in one way or another.
640 if (Opcode == Instruction::BitCast)
641 // Illegal bitcasts are done by storing and loading from a stack slot.
642 return (Src->isVectorTy() ? getScalarizationOverhead(Src, false, true)
643 : 0) +
644 (Dst->isVectorTy() ? getScalarizationOverhead(Dst, true, false)
645 : 0);
646
647 llvm_unreachable("Unhandled cast")::llvm::llvm_unreachable_internal("Unhandled cast", "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/CodeGen/BasicTTIImpl.h"
, 647)
;
648 }
649
650 unsigned getExtractWithExtendCost(unsigned Opcode, Type *Dst,
651 VectorType *VecTy, unsigned Index) {
652 return static_cast<T *>(this)->getVectorInstrCost(
653 Instruction::ExtractElement, VecTy, Index) +
654 static_cast<T *>(this)->getCastInstrCost(Opcode, Dst,
655 VecTy->getElementType());
656 }
657
658 unsigned getCFInstrCost(unsigned Opcode) {
659 // Branches are assumed to be predicted.
660 return 0;
661 }
662
663 unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
664 const Instruction *I) {
665 const TargetLoweringBase *TLI = getTLI();
666 int ISD = TLI->InstructionOpcodeToISD(Opcode);
667 assert(ISD && "Invalid opcode")(static_cast <bool> (ISD && "Invalid opcode") ?
void (0) : __assert_fail ("ISD && \"Invalid opcode\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/CodeGen/BasicTTIImpl.h"
, 667, __extension__ __PRETTY_FUNCTION__))
;
668
669 // Selects on vectors are actually vector selects.
670 if (ISD == ISD::SELECT) {
671 assert(CondTy && "CondTy must exist")(static_cast <bool> (CondTy && "CondTy must exist"
) ? void (0) : __assert_fail ("CondTy && \"CondTy must exist\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/CodeGen/BasicTTIImpl.h"
, 671, __extension__ __PRETTY_FUNCTION__))
;
672 if (CondTy->isVectorTy())
673 ISD = ISD::VSELECT;
674 }
675 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
676
677 if (!(ValTy->isVectorTy() && !LT.second.isVector()) &&
678 !TLI->isOperationExpand(ISD, LT.second)) {
679 // The operation is legal. Assume it costs 1. Multiply
680 // by the type-legalization overhead.
681 return LT.first * 1;
682 }
683
684 // Otherwise, assume that the cast is scalarized.
685 // TODO: If one of the types get legalized by splitting, handle this
686 // similarly to what getCastInstrCost() does.
687 if (ValTy->isVectorTy()) {
688 unsigned Num = ValTy->getVectorNumElements();
689 if (CondTy)
690 CondTy = CondTy->getScalarType();
691 unsigned Cost = static_cast<T *>(this)->getCmpSelInstrCost(
692 Opcode, ValTy->getScalarType(), CondTy, I);
693
694 // Return the cost of multiple scalar invocation plus the cost of
695 // inserting and extracting the values.
696 return getScalarizationOverhead(ValTy, true, false) + Num * Cost;
697 }
698
699 // Unknown scalar opcode.
700 return 1;
701 }
702
703 unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
704 std::pair<unsigned, MVT> LT =
705 getTLI()->getTypeLegalizationCost(DL, Val->getScalarType());
706
707 return LT.first;
708 }
709
710 unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
711 unsigned AddressSpace, const Instruction *I = nullptr) {
712 assert(!Src->isVoidTy() && "Invalid type")(static_cast <bool> (!Src->isVoidTy() && "Invalid type"
) ? void (0) : __assert_fail ("!Src->isVoidTy() && \"Invalid type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/CodeGen/BasicTTIImpl.h"
, 712, __extension__ __PRETTY_FUNCTION__))
;
713 std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(DL, Src);
714
715 // Assuming that all loads of legal types cost 1.
716 unsigned Cost = LT.first;
717
718 if (Src->isVectorTy() &&
719 Src->getPrimitiveSizeInBits() < LT.second.getSizeInBits()) {
720 // This is a vector load that legalizes to a larger type than the vector
721 // itself. Unless the corresponding extending load or truncating store is
722 // legal, then this will scalarize.
723 TargetLowering::LegalizeAction LA = TargetLowering::Expand;
724 EVT MemVT = getTLI()->getValueType(DL, Src);
725 if (Opcode == Instruction::Store)
726 LA = getTLI()->getTruncStoreAction(LT.second, MemVT);
727 else
728 LA = getTLI()->getLoadExtAction(ISD::EXTLOAD, LT.second, MemVT);
729
730 if (LA != TargetLowering::Legal && LA != TargetLowering::Custom) {
731 // This is a vector load/store for some illegal type that is scalarized.
732 // We must account for the cost of building or decomposing the vector.
733 Cost += getScalarizationOverhead(Src, Opcode != Instruction::Store,
734 Opcode == Instruction::Store);
735 }
736 }
737
738 return Cost;
739 }
740
741 unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
742 unsigned Factor,
743 ArrayRef<unsigned> Indices,
744 unsigned Alignment,
745 unsigned AddressSpace) {
746 VectorType *VT = dyn_cast<VectorType>(VecTy);
747 assert(VT && "Expect a vector type for interleaved memory op")(static_cast <bool> (VT && "Expect a vector type for interleaved memory op"
) ? void (0) : __assert_fail ("VT && \"Expect a vector type for interleaved memory op\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/CodeGen/BasicTTIImpl.h"
, 747, __extension__ __PRETTY_FUNCTION__))
;
748
749 unsigned NumElts = VT->getNumElements();
750 assert(Factor > 1 && NumElts % Factor == 0 && "Invalid interleave factor")(static_cast <bool> (Factor > 1 && NumElts %
Factor == 0 && "Invalid interleave factor") ? void (
0) : __assert_fail ("Factor > 1 && NumElts % Factor == 0 && \"Invalid interleave factor\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/CodeGen/BasicTTIImpl.h"
, 750, __extension__ __PRETTY_FUNCTION__))
;
751
752 unsigned NumSubElts = NumElts / Factor;
753 VectorType *SubVT = VectorType::get(VT->getElementType(), NumSubElts);
754
755 // Firstly, the cost of load/store operation.
756 unsigned Cost = static_cast<T *>(this)->getMemoryOpCost(
757 Opcode, VecTy, Alignment, AddressSpace);
758
759 // Legalize the vector type, and get the legalized and unlegalized type
760 // sizes.
761 MVT VecTyLT = getTLI()->getTypeLegalizationCost(DL, VecTy).second;
762 unsigned VecTySize =
763 static_cast<T *>(this)->getDataLayout().getTypeStoreSize(VecTy);
764 unsigned VecTyLTSize = VecTyLT.getStoreSize();
765
766 // Return the ceiling of dividing A by B.
767 auto ceil = [](unsigned A, unsigned B) { return (A + B - 1) / B; };
768
769 // Scale the cost of the memory operation by the fraction of legalized
770 // instructions that will actually be used. We shouldn't account for the
771 // cost of dead instructions since they will be removed.
772 //
773 // E.g., An interleaved load of factor 8:
774 // %vec = load <16 x i64>, <16 x i64>* %ptr
775 // %v0 = shufflevector %vec, undef, <0, 8>
776 //
777 // If <16 x i64> is legalized to 8 v2i64 loads, only 2 of the loads will be
778 // used (those corresponding to elements [0:1] and [8:9] of the unlegalized
779 // type). The other loads are unused.
780 //
781 // We only scale the cost of loads since interleaved store groups aren't
782 // allowed to have gaps.
783 if (Opcode == Instruction::Load && VecTySize > VecTyLTSize) {
784 // The number of loads of a legal type it will take to represent a load
785 // of the unlegalized vector type.
786 unsigned NumLegalInsts = ceil(VecTySize, VecTyLTSize);
787
788 // The number of elements of the unlegalized type that correspond to a
789 // single legal instruction.
790 unsigned NumEltsPerLegalInst = ceil(NumElts, NumLegalInsts);
791
792 // Determine which legal instructions will be used.
793 BitVector UsedInsts(NumLegalInsts, false);
794 for (unsigned Index : Indices)
795 for (unsigned Elt = 0; Elt < NumSubElts; ++Elt)
796 UsedInsts.set((Index + Elt * Factor) / NumEltsPerLegalInst);
797
798 // Scale the cost of the load by the fraction of legal instructions that
799 // will be used.
800 Cost *= UsedInsts.count() / NumLegalInsts;
801 }
802
803 // Then plus the cost of interleave operation.
804 if (Opcode == Instruction::Load) {
805 // The interleave cost is similar to extract sub vectors' elements
806 // from the wide vector, and insert them into sub vectors.
807 //
808 // E.g. An interleaved load of factor 2 (with one member of index 0):
809 // %vec = load <8 x i32>, <8 x i32>* %ptr
810 // %v0 = shuffle %vec, undef, <0, 2, 4, 6> ; Index 0
811 // The cost is estimated as extract elements at 0, 2, 4, 6 from the
812 // <8 x i32> vector and insert them into a <4 x i32> vector.
813
814 assert(Indices.size() <= Factor &&(static_cast <bool> (Indices.size() <= Factor &&
"Interleaved memory op has too many members") ? void (0) : __assert_fail
("Indices.size() <= Factor && \"Interleaved memory op has too many members\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/CodeGen/BasicTTIImpl.h"
, 815, __extension__ __PRETTY_FUNCTION__))
815 "Interleaved memory op has too many members")(static_cast <bool> (Indices.size() <= Factor &&
"Interleaved memory op has too many members") ? void (0) : __assert_fail
("Indices.size() <= Factor && \"Interleaved memory op has too many members\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/CodeGen/BasicTTIImpl.h"
, 815, __extension__ __PRETTY_FUNCTION__))
;
816
817 for (unsigned Index : Indices) {
818 assert(Index < Factor && "Invalid index for interleaved memory op")(static_cast <bool> (Index < Factor && "Invalid index for interleaved memory op"
) ? void (0) : __assert_fail ("Index < Factor && \"Invalid index for interleaved memory op\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/CodeGen/BasicTTIImpl.h"
, 818, __extension__ __PRETTY_FUNCTION__))
;
819
820 // Extract elements from loaded vector for each sub vector.
821 for (unsigned i = 0; i < NumSubElts; i++)
822 Cost += static_cast<T *>(this)->getVectorInstrCost(
823 Instruction::ExtractElement, VT, Index + i * Factor);
824 }
825
826 unsigned InsSubCost = 0;
827 for (unsigned i = 0; i < NumSubElts; i++)
828 InsSubCost += static_cast<T *>(this)->getVectorInstrCost(
829 Instruction::InsertElement, SubVT, i);
830
831 Cost += Indices.size() * InsSubCost;
832 } else {
833 // The interleave cost is extract all elements from sub vectors, and
834 // insert them into the wide vector.
835 //
836 // E.g. An interleaved store of factor 2:
837 // %v0_v1 = shuffle %v0, %v1, <0, 4, 1, 5, 2, 6, 3, 7>
838 // store <8 x i32> %interleaved.vec, <8 x i32>* %ptr
839 // The cost is estimated as extract all elements from both <4 x i32>
840 // vectors and insert into the <8 x i32> vector.
841
842 unsigned ExtSubCost = 0;
843 for (unsigned i = 0; i < NumSubElts; i++)
844 ExtSubCost += static_cast<T *>(this)->getVectorInstrCost(
845 Instruction::ExtractElement, SubVT, i);
846 Cost += ExtSubCost * Factor;
847
848 for (unsigned i = 0; i < NumElts; i++)
849 Cost += static_cast<T *>(this)
850 ->getVectorInstrCost(Instruction::InsertElement, VT, i);
851 }
852
853 return Cost;
854 }
855
856 /// Get intrinsic cost based on arguments.
857 unsigned getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
858 ArrayRef<Value *> Args, FastMathFlags FMF,
859 unsigned VF = 1) {
860 unsigned RetVF = (RetTy->isVectorTy() ? RetTy->getVectorNumElements() : 1);
861 assert((RetVF == 1 || VF == 1) && "VF > 1 and RetVF is a vector type")(static_cast <bool> ((RetVF == 1 || VF == 1) &&
"VF > 1 and RetVF is a vector type") ? void (0) : __assert_fail
("(RetVF == 1 || VF == 1) && \"VF > 1 and RetVF is a vector type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/CodeGen/BasicTTIImpl.h"
, 861, __extension__ __PRETTY_FUNCTION__))
;
862
863 switch (IID) {
864 default: {
865 // Assume that we need to scalarize this intrinsic.
866 SmallVector<Type *, 4> Types;
867 for (Value *Op : Args) {
868 Type *OpTy = Op->getType();
869 assert(VF == 1 || !OpTy->isVectorTy())(static_cast <bool> (VF == 1 || !OpTy->isVectorTy())
? void (0) : __assert_fail ("VF == 1 || !OpTy->isVectorTy()"
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/CodeGen/BasicTTIImpl.h"
, 869, __extension__ __PRETTY_FUNCTION__))
;
870 Types.push_back(VF == 1 ? OpTy : VectorType::get(OpTy, VF));
871 }
872
873 if (VF > 1 && !RetTy->isVoidTy())
874 RetTy = VectorType::get(RetTy, VF);
875
876 // Compute the scalarization overhead based on Args for a vector
877 // intrinsic. A vectorizer will pass a scalar RetTy and VF > 1, while
878 // CostModel will pass a vector RetTy and VF is 1.
879 unsigned ScalarizationCost = std::numeric_limits<unsigned>::max();
880 if (RetVF > 1 || VF > 1) {
881 ScalarizationCost = 0;
882 if (!RetTy->isVoidTy())
883 ScalarizationCost += getScalarizationOverhead(RetTy, true, false);
884 ScalarizationCost += getOperandsScalarizationOverhead(Args, VF);
885 }
886
887 return static_cast<T *>(this)->
888 getIntrinsicInstrCost(IID, RetTy, Types, FMF, ScalarizationCost);
889 }
890 case Intrinsic::masked_scatter: {
891 assert(VF == 1 && "Can't vectorize types here.")(static_cast <bool> (VF == 1 && "Can't vectorize types here."
) ? void (0) : __assert_fail ("VF == 1 && \"Can't vectorize types here.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/CodeGen/BasicTTIImpl.h"
, 891, __extension__ __PRETTY_FUNCTION__))
;
892 Value *Mask = Args[3];
893 bool VarMask = !isa<Constant>(Mask);
894 unsigned Alignment = cast<ConstantInt>(Args[2])->getZExtValue();
895 return
896 static_cast<T *>(this)->getGatherScatterOpCost(Instruction::Store,
897 Args[0]->getType(),
898 Args[1], VarMask,
899 Alignment);
900 }
901 case Intrinsic::masked_gather: {
902 assert(VF == 1 && "Can't vectorize types here.")(static_cast <bool> (VF == 1 && "Can't vectorize types here."
) ? void (0) : __assert_fail ("VF == 1 && \"Can't vectorize types here.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/CodeGen/BasicTTIImpl.h"
, 902, __extension__ __PRETTY_FUNCTION__))
;
903 Value *Mask = Args[2];
904 bool VarMask = !isa<Constant>(Mask);
905 unsigned Alignment = cast<ConstantInt>(Args[1])->getZExtValue();
906 return
907 static_cast<T *>(this)->getGatherScatterOpCost(Instruction::Load,
908 RetTy, Args[0], VarMask,
909 Alignment);
910 }
911 }
912 }
913
914 /// Get intrinsic cost based on argument types.
915 /// If ScalarizationCostPassed is std::numeric_limits<unsigned>::max(), the
916 /// cost of scalarizing the arguments and the return value will be computed
917 /// based on types.
918 unsigned getIntrinsicInstrCost(
919 Intrinsic::ID IID, Type *RetTy, ArrayRef<Type *> Tys, FastMathFlags FMF,
920 unsigned ScalarizationCostPassed = std::numeric_limits<unsigned>::max()) {
921 SmallVector<unsigned, 2> ISDs;
922 unsigned SingleCallCost = 10; // Library call cost. Make it expensive.
923 switch (IID) {
924 default: {
925 // Assume that we need to scalarize this intrinsic.
926 unsigned ScalarizationCost = ScalarizationCostPassed;
927 unsigned ScalarCalls = 1;
928 Type *ScalarRetTy = RetTy;
929 if (RetTy->isVectorTy()) {
930 if (ScalarizationCostPassed == std::numeric_limits<unsigned>::max())
931 ScalarizationCost = getScalarizationOverhead(RetTy, true, false);
932 ScalarCalls = std::max(ScalarCalls, RetTy->getVectorNumElements());
933 ScalarRetTy = RetTy->getScalarType();
934 }
935 SmallVector<Type *, 4> ScalarTys;
936 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
937 Type *Ty = Tys[i];
938 if (Ty->isVectorTy()) {
939 if (ScalarizationCostPassed == std::numeric_limits<unsigned>::max())
940 ScalarizationCost += getScalarizationOverhead(Ty, false, true);
941 ScalarCalls = std::max(ScalarCalls, Ty->getVectorNumElements());
942 Ty = Ty->getScalarType();
943 }
944 ScalarTys.push_back(Ty);
945 }
946 if (ScalarCalls == 1)
947 return 1; // Return cost of a scalar intrinsic. Assume it to be cheap.
948
949 unsigned ScalarCost = static_cast<T *>(this)->getIntrinsicInstrCost(
950 IID, ScalarRetTy, ScalarTys, FMF);
951
952 return ScalarCalls * ScalarCost + ScalarizationCost;
953 }
954 // Look for intrinsics that can be lowered directly or turned into a scalar
955 // intrinsic call.
956 case Intrinsic::sqrt:
957 ISDs.push_back(ISD::FSQRT);
958 break;
959 case Intrinsic::sin:
960 ISDs.push_back(ISD::FSIN);
961 break;
962 case Intrinsic::cos:
963 ISDs.push_back(ISD::FCOS);
964 break;
965 case Intrinsic::exp:
966 ISDs.push_back(ISD::FEXP);
967 break;
968 case Intrinsic::exp2:
969 ISDs.push_back(ISD::FEXP2);
970 break;
971 case Intrinsic::log:
972 ISDs.push_back(ISD::FLOG);
973 break;
974 case Intrinsic::log10:
975 ISDs.push_back(ISD::FLOG10);
976 break;
977 case Intrinsic::log2:
978 ISDs.push_back(ISD::FLOG2);
979 break;
980 case Intrinsic::fabs:
981 ISDs.push_back(ISD::FABS);
982 break;
983 case Intrinsic::minnum:
984 ISDs.push_back(ISD::FMINNUM);
985 if (FMF.noNaNs())
986 ISDs.push_back(ISD::FMINNAN);
987 break;
988 case Intrinsic::maxnum:
989 ISDs.push_back(ISD::FMAXNUM);
990 if (FMF.noNaNs())
991 ISDs.push_back(ISD::FMAXNAN);
992 break;
993 case Intrinsic::copysign:
994 ISDs.push_back(ISD::FCOPYSIGN);
995 break;
996 case Intrinsic::floor:
997 ISDs.push_back(ISD::FFLOOR);
998 break;
999 case Intrinsic::ceil:
1000 ISDs.push_back(ISD::FCEIL);
1001 break;
1002 case Intrinsic::trunc:
1003 ISDs.push_back(ISD::FTRUNC);
1004 break;
1005 case Intrinsic::nearbyint:
1006 ISDs.push_back(ISD::FNEARBYINT);
1007 break;
1008 case Intrinsic::rint:
1009 ISDs.push_back(ISD::FRINT);
1010 break;
1011 case Intrinsic::round:
1012 ISDs.push_back(ISD::FROUND);
1013 break;
1014 case Intrinsic::pow:
1015 ISDs.push_back(ISD::FPOW);
1016 break;
1017 case Intrinsic::fma:
1018 ISDs.push_back(ISD::FMA);
1019 break;
1020 case Intrinsic::fmuladd:
1021 ISDs.push_back(ISD::FMA);
1022 break;
1023 // FIXME: We should return 0 whenever getIntrinsicCost == TCC_Free.
1024 case Intrinsic::lifetime_start:
1025 case Intrinsic::lifetime_end:
1026 case Intrinsic::sideeffect:
1027 return 0;
1028 case Intrinsic::masked_store:
1029 return static_cast<T *>(this)
1030 ->getMaskedMemoryOpCost(Instruction::Store, Tys[0], 0, 0);
1031 case Intrinsic::masked_load:
1032 return static_cast<T *>(this)
1033 ->getMaskedMemoryOpCost(Instruction::Load, RetTy, 0, 0);
1034 case Intrinsic::ctpop:
1035 ISDs.push_back(ISD::CTPOP);
1036 // In case of legalization use TCC_Expensive. This is cheaper than a
1037 // library call but still not a cheap instruction.
1038 SingleCallCost = TargetTransformInfo::TCC_Expensive;
1039 break;
1040 // FIXME: ctlz, cttz, ...
1041 }
1042
1043 const TargetLoweringBase *TLI = getTLI();
1044 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, RetTy);
1045
1046 SmallVector<unsigned, 2> LegalCost;
1047 SmallVector<unsigned, 2> CustomCost;
1048 for (unsigned ISD : ISDs) {
1049 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
1050 if (IID == Intrinsic::fabs && TLI->isFAbsFree(LT.second)) {
1051 return 0;
1052 }
1053
1054 // The operation is legal. Assume it costs 1.
1055 // If the type is split to multiple registers, assume that there is some
1056 // overhead to this.
1057 // TODO: Once we have extract/insert subvector cost we need to use them.
1058 if (LT.first > 1)
1059 LegalCost.push_back(LT.first * 2);
1060 else
1061 LegalCost.push_back(LT.first * 1);
1062 } else if (!TLI->isOperationExpand(ISD, LT.second)) {
1063 // If the operation is custom lowered then assume
1064 // that the code is twice as expensive.
1065 CustomCost.push_back(LT.first * 2);
1066 }
1067 }
1068
1069 auto MinLegalCostI = std::min_element(LegalCost.begin(), LegalCost.end());
1070 if (MinLegalCostI != LegalCost.end())
1071 return *MinLegalCostI;
1072
1073 auto MinCustomCostI = std::min_element(CustomCost.begin(), CustomCost.end());
1074 if (MinCustomCostI != CustomCost.end())
1075 return *MinCustomCostI;
1076
1077 // If we can't lower fmuladd into an FMA estimate the cost as a floating
1078 // point mul followed by an add.
1079 if (IID == Intrinsic::fmuladd)
1080 return static_cast<T *>(this)
1081 ->getArithmeticInstrCost(BinaryOperator::FMul, RetTy) +
1082 static_cast<T *>(this)
1083 ->getArithmeticInstrCost(BinaryOperator::FAdd, RetTy);
1084
1085 // Else, assume that we need to scalarize this intrinsic. For math builtins
1086 // this will emit a costly libcall, adding call overhead and spills. Make it
1087 // very expensive.
1088 if (RetTy->isVectorTy()) {
1089 unsigned ScalarizationCost =
1090 ((ScalarizationCostPassed != std::numeric_limits<unsigned>::max())
1091 ? ScalarizationCostPassed
1092 : getScalarizationOverhead(RetTy, true, false));
1093 unsigned ScalarCalls = RetTy->getVectorNumElements();
1094 SmallVector<Type *, 4> ScalarTys;
1095 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
1096 Type *Ty = Tys[i];
1097 if (Ty->isVectorTy())
1098 Ty = Ty->getScalarType();
1099 ScalarTys.push_back(Ty);
1100 }
1101 unsigned ScalarCost = static_cast<T *>(this)->getIntrinsicInstrCost(
1102 IID, RetTy->getScalarType(), ScalarTys, FMF);
1103 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
1104 if (Tys[i]->isVectorTy()) {
1105 if (ScalarizationCostPassed == std::numeric_limits<unsigned>::max())
1106 ScalarizationCost += getScalarizationOverhead(Tys[i], false, true);
1107 ScalarCalls = std::max(ScalarCalls, Tys[i]->getVectorNumElements());
1108 }
1109 }
1110
1111 return ScalarCalls * ScalarCost + ScalarizationCost;
1112 }
1113
1114 // This is going to be turned into a library call, make it expensive.
1115 return SingleCallCost;
1116 }
1117
1118 /// \brief Compute a cost of the given call instruction.
1119 ///
1120 /// Compute the cost of calling function F with return type RetTy and
1121 /// argument types Tys. F might be nullptr, in this case the cost of an
1122 /// arbitrary call with the specified signature will be returned.
1123 /// This is used, for instance, when we estimate call of a vector
1124 /// counterpart of the given function.
1125 /// \param F Called function, might be nullptr.
1126 /// \param RetTy Return value types.
1127 /// \param Tys Argument types.
1128 /// \returns The cost of Call instruction.
1129 unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) {
1130 return 10;
1131 }
1132
1133 unsigned getNumberOfParts(Type *Tp) {
1134 std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(DL, Tp);
1135 return LT.first;
1136 }
1137
1138 unsigned getAddressComputationCost(Type *Ty, ScalarEvolution *,
1139 const SCEV *) {
1140 return 0;
1141 }
1142
1143 /// Try to calculate arithmetic and shuffle op costs for reduction operations.
1144 /// We're assuming that reduction operation are performing the following way:
1145 /// 1. Non-pairwise reduction
1146 /// %val1 = shufflevector<n x t> %val, <n x t> %undef,
1147 /// <n x i32> <i32 n/2, i32 n/2 + 1, ..., i32 n, i32 undef, ..., i32 undef>
1148 /// \----------------v-------------/ \----------v------------/
1149 /// n/2 elements n/2 elements
1150 /// %red1 = op <n x t> %val, <n x t> val1
1151 /// After this operation we have a vector %red1 where only the first n/2
1152 /// elements are meaningful, the second n/2 elements are undefined and can be
1153 /// dropped. All other operations are actually working with the vector of
1154 /// length n/2, not n, though the real vector length is still n.
1155 /// %val2 = shufflevector<n x t> %red1, <n x t> %undef,
1156 /// <n x i32> <i32 n/4, i32 n/4 + 1, ..., i32 n/2, i32 undef, ..., i32 undef>
1157 /// \----------------v-------------/ \----------v------------/
1158 /// n/4 elements 3*n/4 elements
1159 /// %red2 = op <n x t> %red1, <n x t> val2 - working with the vector of
1160 /// length n/2, the resulting vector has length n/4 etc.
1161 /// 2. Pairwise reduction:
1162 /// Everything is the same except for an additional shuffle operation which
1163 /// is used to produce operands for pairwise kind of reductions.
1164 /// %val1 = shufflevector<n x t> %val, <n x t> %undef,
1165 /// <n x i32> <i32 0, i32 2, ..., i32 n-2, i32 undef, ..., i32 undef>
1166 /// \-------------v----------/ \----------v------------/
1167 /// n/2 elements n/2 elements
1168 /// %val2 = shufflevector<n x t> %val, <n x t> %undef,
1169 /// <n x i32> <i32 1, i32 3, ..., i32 n-1, i32 undef, ..., i32 undef>
1170 /// \-------------v----------/ \----------v------------/
1171 /// n/2 elements n/2 elements
1172 /// %red1 = op <n x t> %val1, <n x t> val2
1173 /// Again, the operation is performed on <n x t> vector, but the resulting
1174 /// vector %red1 is <n/2 x t> vector.
1175 ///
1176 /// The cost model should take into account that the actual length of the
1177 /// vector is reduced on each iteration.
1178 unsigned getArithmeticReductionCost(unsigned Opcode, Type *Ty,
1179 bool IsPairwise) {
1180 assert(Ty->isVectorTy() && "Expect a vector type")(static_cast <bool> (Ty->isVectorTy() && "Expect a vector type"
) ? void (0) : __assert_fail ("Ty->isVectorTy() && \"Expect a vector type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/CodeGen/BasicTTIImpl.h"
, 1180, __extension__ __PRETTY_FUNCTION__))
;
1181 Type *ScalarTy = Ty->getVectorElementType();
1182 unsigned NumVecElts = Ty->getVectorNumElements();
1183 unsigned NumReduxLevels = Log2_32(NumVecElts);
1184 unsigned ArithCost = 0;
1185 unsigned ShuffleCost = 0;
1186 auto *ConcreteTTI = static_cast<T *>(this);
1187 std::pair<unsigned, MVT> LT =
1188 ConcreteTTI->getTLI()->getTypeLegalizationCost(DL, Ty);
1189 unsigned LongVectorCount = 0;
1190 unsigned MVTLen =
1191 LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
1192 while (NumVecElts > MVTLen) {
1193 NumVecElts /= 2;
1194 // Assume the pairwise shuffles add a cost.
1195 ShuffleCost += (IsPairwise + 1) *
1196 ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1197 NumVecElts, Ty);
1198 ArithCost += ConcreteTTI->getArithmeticInstrCost(Opcode, Ty);
1199 Ty = VectorType::get(ScalarTy, NumVecElts);
1200 ++LongVectorCount;
1201 }
1202 // The minimal length of the vector is limited by the real length of vector
1203 // operations performed on the current platform. That's why several final
1204 // reduction operations are performed on the vectors with the same
1205 // architecture-dependent length.
1206 ShuffleCost += (NumReduxLevels - LongVectorCount) * (IsPairwise + 1) *
1207 ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1208 NumVecElts, Ty);
1209 ArithCost += (NumReduxLevels - LongVectorCount) *
1210 ConcreteTTI->getArithmeticInstrCost(Opcode, Ty);
1211 return ShuffleCost + ArithCost + getScalarizationOverhead(Ty, false, true);
1212 }
1213
1214 /// Try to calculate op costs for min/max reduction operations.
1215 /// \param CondTy Conditional type for the Select instruction.
1216 unsigned getMinMaxReductionCost(Type *Ty, Type *CondTy, bool IsPairwise,
1217 bool) {
1218 assert(Ty->isVectorTy() && "Expect a vector type")(static_cast <bool> (Ty->isVectorTy() && "Expect a vector type"
) ? void (0) : __assert_fail ("Ty->isVectorTy() && \"Expect a vector type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/CodeGen/BasicTTIImpl.h"
, 1218, __extension__ __PRETTY_FUNCTION__))
;
1219 Type *ScalarTy = Ty->getVectorElementType();
1220 Type *ScalarCondTy = CondTy->getVectorElementType();
1221 unsigned NumVecElts = Ty->getVectorNumElements();
1222 unsigned NumReduxLevels = Log2_32(NumVecElts);
1223 unsigned CmpOpcode;
1224 if (Ty->isFPOrFPVectorTy()) {
1225 CmpOpcode = Instruction::FCmp;
1226 } else {
1227 assert(Ty->isIntOrIntVectorTy() &&(static_cast <bool> (Ty->isIntOrIntVectorTy() &&
"expecting floating point or integer type for min/max reduction"
) ? void (0) : __assert_fail ("Ty->isIntOrIntVectorTy() && \"expecting floating point or integer type for min/max reduction\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/CodeGen/BasicTTIImpl.h"
, 1228, __extension__ __PRETTY_FUNCTION__))
1228 "expecting floating point or integer type for min/max reduction")(static_cast <bool> (Ty->isIntOrIntVectorTy() &&
"expecting floating point or integer type for min/max reduction"
) ? void (0) : __assert_fail ("Ty->isIntOrIntVectorTy() && \"expecting floating point or integer type for min/max reduction\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/CodeGen/BasicTTIImpl.h"
, 1228, __extension__ __PRETTY_FUNCTION__))
;
1229 CmpOpcode = Instruction::ICmp;
1230 }
1231 unsigned MinMaxCost = 0;
1232 unsigned ShuffleCost = 0;
1233 auto *ConcreteTTI = static_cast<T *>(this);
1234 std::pair<unsigned, MVT> LT =
1235 ConcreteTTI->getTLI()->getTypeLegalizationCost(DL, Ty);
1236 unsigned LongVectorCount = 0;
1237 unsigned MVTLen =
1238 LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
1239 while (NumVecElts > MVTLen) {
1240 NumVecElts /= 2;
1241 // Assume the pairwise shuffles add a cost.
1242 ShuffleCost += (IsPairwise + 1) *
1243 ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1244 NumVecElts, Ty);
1245 MinMaxCost +=
1246 ConcreteTTI->getCmpSelInstrCost(CmpOpcode, Ty, CondTy, nullptr) +
1247 ConcreteTTI->getCmpSelInstrCost(Instruction::Select, Ty, CondTy,
1248 nullptr);
1249 Ty = VectorType::get(ScalarTy, NumVecElts);
1250 CondTy = VectorType::get(ScalarCondTy, NumVecElts);
1251 ++LongVectorCount;
1252 }
1253 // The minimal length of the vector is limited by the real length of vector
1254 // operations performed on the current platform. That's why several final
1255 // reduction opertions are perfomed on the vectors with the same
1256 // architecture-dependent length.
1257 ShuffleCost += (NumReduxLevels - LongVectorCount) * (IsPairwise + 1) *
1258 ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1259 NumVecElts, Ty);
1260 MinMaxCost +=
1261 (NumReduxLevels - LongVectorCount) *
1262 (ConcreteTTI->getCmpSelInstrCost(CmpOpcode, Ty, CondTy, nullptr) +
1263 ConcreteTTI->getCmpSelInstrCost(Instruction::Select, Ty, CondTy,
1264 nullptr));
1265 // Need 3 extractelement instructions for scalarization + an additional
1266 // scalar select instruction.
1267 return ShuffleCost + MinMaxCost +
1268 3 * getScalarizationOverhead(Ty, /*Insert=*/false,
1269 /*Extract=*/true) +
1270 ConcreteTTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
1271 ScalarCondTy, nullptr);
1272 }
1273
1274 unsigned getVectorSplitCost() { return 1; }
1275
1276 /// @}
1277};
1278
1279/// \brief Concrete BasicTTIImpl that can be used if no further customization
1280/// is needed.
1281class BasicTTIImpl : public BasicTTIImplBase<BasicTTIImpl> {
1282 using BaseT = BasicTTIImplBase<BasicTTIImpl>;
1283
1284 friend class BasicTTIImplBase<BasicTTIImpl>;
1285
1286 const TargetSubtargetInfo *ST;
1287 const TargetLoweringBase *TLI;
1288
1289 const TargetSubtargetInfo *getST() const { return ST; }
1290 const TargetLoweringBase *getTLI() const { return TLI; }
1291
1292public:
1293 explicit BasicTTIImpl(const TargetMachine *ST, const Function &F);
1294};
1295
1296} // end namespace llvm
1297
1298#endif // LLVM_CODEGEN_BASICTTIIMPL_H