Bug Summary

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

Annotated Source Code

[?] Use j/k keys for keyboard navigation

/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/PowerPC/PPCTargetTransformInfo.cpp

1//===-- PPCTargetTransformInfo.cpp - PPC specific TTI ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "PPCTargetTransformInfo.h"
11#include "llvm/Analysis/TargetTransformInfo.h"
12#include "llvm/CodeGen/BasicTTIImpl.h"
13#include "llvm/CodeGen/CostTable.h"
14#include "llvm/CodeGen/TargetLowering.h"
15#include "llvm/Support/CommandLine.h"
16#include "llvm/Support/Debug.h"
17using namespace llvm;
18
19#define DEBUG_TYPE"ppctti" "ppctti"
20
21static cl::opt<bool> DisablePPCConstHoist("disable-ppc-constant-hoisting",
22cl::desc("disable constant hoisting on PPC"), cl::init(false), cl::Hidden);
23
24// This is currently only used for the data prefetch pass which is only enabled
25// for BG/Q by default.
26static cl::opt<unsigned>
27CacheLineSize("ppc-loop-prefetch-cache-line", cl::Hidden, cl::init(64),
28 cl::desc("The loop prefetch cache line size"));
29
30//===----------------------------------------------------------------------===//
31//
32// PPC cost model.
33//
34//===----------------------------------------------------------------------===//
35
36TargetTransformInfo::PopcntSupportKind
37PPCTTIImpl::getPopcntSupport(unsigned TyWidth) {
38 assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2")(static_cast <bool> (isPowerOf2_32(TyWidth) && "Ty width must be power of 2"
) ? void (0) : __assert_fail ("isPowerOf2_32(TyWidth) && \"Ty width must be power of 2\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/PowerPC/PPCTargetTransformInfo.cpp"
, 38, __extension__ __PRETTY_FUNCTION__))
;
39 if (ST->hasPOPCNTD() != PPCSubtarget::POPCNTD_Unavailable && TyWidth <= 64)
40 return ST->hasPOPCNTD() == PPCSubtarget::POPCNTD_Slow ?
41 TTI::PSK_SlowHardware : TTI::PSK_FastHardware;
42 return TTI::PSK_Software;
43}
44
45int PPCTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty) {
46 if (DisablePPCConstHoist)
47 return BaseT::getIntImmCost(Imm, Ty);
48
49 assert(Ty->isIntegerTy())(static_cast <bool> (Ty->isIntegerTy()) ? void (0) :
__assert_fail ("Ty->isIntegerTy()", "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/PowerPC/PPCTargetTransformInfo.cpp"
, 49, __extension__ __PRETTY_FUNCTION__))
;
50
51 unsigned BitSize = Ty->getPrimitiveSizeInBits();
52 if (BitSize == 0)
53 return ~0U;
54
55 if (Imm == 0)
56 return TTI::TCC_Free;
57
58 if (Imm.getBitWidth() <= 64) {
59 if (isInt<16>(Imm.getSExtValue()))
60 return TTI::TCC_Basic;
61
62 if (isInt<32>(Imm.getSExtValue())) {
63 // A constant that can be materialized using lis.
64 if ((Imm.getZExtValue() & 0xFFFF) == 0)
65 return TTI::TCC_Basic;
66
67 return 2 * TTI::TCC_Basic;
68 }
69 }
70
71 return 4 * TTI::TCC_Basic;
72}
73
74int PPCTTIImpl::getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
75 Type *Ty) {
76 if (DisablePPCConstHoist)
77 return BaseT::getIntImmCost(IID, Idx, Imm, Ty);
78
79 assert(Ty->isIntegerTy())(static_cast <bool> (Ty->isIntegerTy()) ? void (0) :
__assert_fail ("Ty->isIntegerTy()", "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/PowerPC/PPCTargetTransformInfo.cpp"
, 79, __extension__ __PRETTY_FUNCTION__))
;
80
81 unsigned BitSize = Ty->getPrimitiveSizeInBits();
82 if (BitSize == 0)
83 return ~0U;
84
85 switch (IID) {
86 default:
87 return TTI::TCC_Free;
88 case Intrinsic::sadd_with_overflow:
89 case Intrinsic::uadd_with_overflow:
90 case Intrinsic::ssub_with_overflow:
91 case Intrinsic::usub_with_overflow:
92 if ((Idx == 1) && Imm.getBitWidth() <= 64 && isInt<16>(Imm.getSExtValue()))
93 return TTI::TCC_Free;
94 break;
95 case Intrinsic::experimental_stackmap:
96 if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
97 return TTI::TCC_Free;
98 break;
99 case Intrinsic::experimental_patchpoint_void:
100 case Intrinsic::experimental_patchpoint_i64:
101 if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
102 return TTI::TCC_Free;
103 break;
104 }
105 return PPCTTIImpl::getIntImmCost(Imm, Ty);
106}
107
108int PPCTTIImpl::getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
109 Type *Ty) {
110 if (DisablePPCConstHoist)
111 return BaseT::getIntImmCost(Opcode, Idx, Imm, Ty);
112
113 assert(Ty->isIntegerTy())(static_cast <bool> (Ty->isIntegerTy()) ? void (0) :
__assert_fail ("Ty->isIntegerTy()", "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/PowerPC/PPCTargetTransformInfo.cpp"
, 113, __extension__ __PRETTY_FUNCTION__))
;
114
115 unsigned BitSize = Ty->getPrimitiveSizeInBits();
116 if (BitSize == 0)
117 return ~0U;
118
119 unsigned ImmIdx = ~0U;
120 bool ShiftedFree = false, RunFree = false, UnsignedFree = false,
121 ZeroFree = false;
122 switch (Opcode) {
123 default:
124 return TTI::TCC_Free;
125 case Instruction::GetElementPtr:
126 // Always hoist the base address of a GetElementPtr. This prevents the
127 // creation of new constants for every base constant that gets constant
128 // folded with the offset.
129 if (Idx == 0)
130 return 2 * TTI::TCC_Basic;
131 return TTI::TCC_Free;
132 case Instruction::And:
133 RunFree = true; // (for the rotate-and-mask instructions)
134 LLVM_FALLTHROUGH[[clang::fallthrough]];
135 case Instruction::Add:
136 case Instruction::Or:
137 case Instruction::Xor:
138 ShiftedFree = true;
139 LLVM_FALLTHROUGH[[clang::fallthrough]];
140 case Instruction::Sub:
141 case Instruction::Mul:
142 case Instruction::Shl:
143 case Instruction::LShr:
144 case Instruction::AShr:
145 ImmIdx = 1;
146 break;
147 case Instruction::ICmp:
148 UnsignedFree = true;
149 ImmIdx = 1;
150 // Zero comparisons can use record-form instructions.
151 LLVM_FALLTHROUGH[[clang::fallthrough]];
152 case Instruction::Select:
153 ZeroFree = true;
154 break;
155 case Instruction::PHI:
156 case Instruction::Call:
157 case Instruction::Ret:
158 case Instruction::Load:
159 case Instruction::Store:
160 break;
161 }
162
163 if (ZeroFree && Imm == 0)
164 return TTI::TCC_Free;
165
166 if (Idx == ImmIdx && Imm.getBitWidth() <= 64) {
167 if (isInt<16>(Imm.getSExtValue()))
168 return TTI::TCC_Free;
169
170 if (RunFree) {
171 if (Imm.getBitWidth() <= 32 &&
172 (isShiftedMask_32(Imm.getZExtValue()) ||
173 isShiftedMask_32(~Imm.getZExtValue())))
174 return TTI::TCC_Free;
175
176 if (ST->isPPC64() &&
177 (isShiftedMask_64(Imm.getZExtValue()) ||
178 isShiftedMask_64(~Imm.getZExtValue())))
179 return TTI::TCC_Free;
180 }
181
182 if (UnsignedFree && isUInt<16>(Imm.getZExtValue()))
183 return TTI::TCC_Free;
184
185 if (ShiftedFree && (Imm.getZExtValue() & 0xFFFF) == 0)
186 return TTI::TCC_Free;
187 }
188
189 return PPCTTIImpl::getIntImmCost(Imm, Ty);
190}
191
192unsigned PPCTTIImpl::getUserCost(const User *U,
193 ArrayRef<const Value *> Operands) {
194 if (U->getType()->isVectorTy()) {
1
Taking false branch
195 // Instructions that need to be split should cost more.
196 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, U->getType());
197 return LT.first * BaseT::getUserCost(U, Operands);
198 }
199
200 return BaseT::getUserCost(U, Operands);
2
Calling 'TargetTransformInfoImplCRTPBase::getUserCost'
201}
202
203void PPCTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
204 TTI::UnrollingPreferences &UP) {
205 if (ST->getDarwinDirective() == PPC::DIR_A2) {
206 // The A2 is in-order with a deep pipeline, and concatenation unrolling
207 // helps expose latency-hiding opportunities to the instruction scheduler.
208 UP.Partial = UP.Runtime = true;
209
210 // We unroll a lot on the A2 (hundreds of instructions), and the benefits
211 // often outweigh the cost of a division to compute the trip count.
212 UP.AllowExpensiveTripCount = true;
213 }
214
215 BaseT::getUnrollingPreferences(L, SE, UP);
216}
217
218bool PPCTTIImpl::enableAggressiveInterleaving(bool LoopHasReductions) {
219 // On the A2, always unroll aggressively. For QPX unaligned loads, we depend
220 // on combining the loads generated for consecutive accesses, and failure to
221 // do so is particularly expensive. This makes it much more likely (compared
222 // to only using concatenation unrolling).
223 if (ST->getDarwinDirective() == PPC::DIR_A2)
224 return true;
225
226 return LoopHasReductions;
227}
228
229const PPCTTIImpl::TTI::MemCmpExpansionOptions *
230PPCTTIImpl::enableMemCmpExpansion(bool IsZeroCmp) const {
231 static const auto Options = []() {
232 TTI::MemCmpExpansionOptions Options;
233 Options.LoadSizes.push_back(8);
234 Options.LoadSizes.push_back(4);
235 Options.LoadSizes.push_back(2);
236 Options.LoadSizes.push_back(1);
237 return Options;
238 }();
239 return &Options;
240}
241
242bool PPCTTIImpl::enableInterleavedAccessVectorization() {
243 return true;
244}
245
246unsigned PPCTTIImpl::getNumberOfRegisters(bool Vector) {
247 if (Vector && !ST->hasAltivec() && !ST->hasQPX())
248 return 0;
249 return ST->hasVSX() ? 64 : 32;
250}
251
252unsigned PPCTTIImpl::getRegisterBitWidth(bool Vector) const {
253 if (Vector) {
254 if (ST->hasQPX()) return 256;
255 if (ST->hasAltivec()) return 128;
256 return 0;
257 }
258
259 if (ST->isPPC64())
260 return 64;
261 return 32;
262
263}
264
265unsigned PPCTTIImpl::getCacheLineSize() {
266 // Check first if the user specified a custom line size.
267 if (CacheLineSize.getNumOccurrences() > 0)
268 return CacheLineSize;
269
270 // On P7, P8 or P9 we have a cache line size of 128.
271 unsigned Directive = ST->getDarwinDirective();
272 if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8 ||
273 Directive == PPC::DIR_PWR9)
274 return 128;
275
276 // On other processors return a default of 64 bytes.
277 return 64;
278}
279
280unsigned PPCTTIImpl::getPrefetchDistance() {
281 // This seems like a reasonable default for the BG/Q (this pass is enabled, by
282 // default, only on the BG/Q).
283 return 300;
284}
285
286unsigned PPCTTIImpl::getMaxInterleaveFactor(unsigned VF) {
287 unsigned Directive = ST->getDarwinDirective();
288 // The 440 has no SIMD support, but floating-point instructions
289 // have a 5-cycle latency, so unroll by 5x for latency hiding.
290 if (Directive == PPC::DIR_440)
291 return 5;
292
293 // The A2 has no SIMD support, but floating-point instructions
294 // have a 6-cycle latency, so unroll by 6x for latency hiding.
295 if (Directive == PPC::DIR_A2)
296 return 6;
297
298 // FIXME: For lack of any better information, do no harm...
299 if (Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500)
300 return 1;
301
302 // For P7 and P8, floating-point instructions have a 6-cycle latency and
303 // there are two execution units, so unroll by 12x for latency hiding.
304 // FIXME: the same for P9 as previous gen until POWER9 scheduling is ready
305 if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8 ||
306 Directive == PPC::DIR_PWR9)
307 return 12;
308
309 // For most things, modern systems have two execution units (and
310 // out-of-order execution).
311 return 2;
312}
313
314int PPCTTIImpl::getArithmeticInstrCost(
315 unsigned Opcode, Type *Ty, TTI::OperandValueKind Op1Info,
316 TTI::OperandValueKind Op2Info, TTI::OperandValueProperties Opd1PropInfo,
317 TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args) {
318 assert(TLI->InstructionOpcodeToISD(Opcode) && "Invalid opcode")(static_cast <bool> (TLI->InstructionOpcodeToISD(Opcode
) && "Invalid opcode") ? void (0) : __assert_fail ("TLI->InstructionOpcodeToISD(Opcode) && \"Invalid opcode\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/PowerPC/PPCTargetTransformInfo.cpp"
, 318, __extension__ __PRETTY_FUNCTION__))
;
319
320 // Fallback to the default implementation.
321 return BaseT::getArithmeticInstrCost(Opcode, Ty, Op1Info, Op2Info,
322 Opd1PropInfo, Opd2PropInfo);
323}
324
325int PPCTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
326 Type *SubTp) {
327 // Legalize the type.
328 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
329
330 // PPC, for both Altivec/VSX and QPX, support cheap arbitrary permutations
331 // (at least in the sense that there need only be one non-loop-invariant
332 // instruction). We need one such shuffle instruction for each actual
333 // register (this is not true for arbitrary shuffles, but is true for the
334 // structured types of shuffles covered by TTI::ShuffleKind).
335 return LT.first;
336}
337
338int PPCTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
339 const Instruction *I) {
340 assert(TLI->InstructionOpcodeToISD(Opcode) && "Invalid opcode")(static_cast <bool> (TLI->InstructionOpcodeToISD(Opcode
) && "Invalid opcode") ? void (0) : __assert_fail ("TLI->InstructionOpcodeToISD(Opcode) && \"Invalid opcode\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/PowerPC/PPCTargetTransformInfo.cpp"
, 340, __extension__ __PRETTY_FUNCTION__))
;
341
342 return BaseT::getCastInstrCost(Opcode, Dst, Src);
343}
344
345int PPCTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
346 const Instruction *I) {
347 return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, I);
348}
349
350int PPCTTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
351 assert(Val->isVectorTy() && "This must be a vector type")(static_cast <bool> (Val->isVectorTy() && "This must be a vector type"
) ? void (0) : __assert_fail ("Val->isVectorTy() && \"This must be a vector type\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/PowerPC/PPCTargetTransformInfo.cpp"
, 351, __extension__ __PRETTY_FUNCTION__))
;
352
353 int ISD = TLI->InstructionOpcodeToISD(Opcode);
354 assert(ISD && "Invalid opcode")(static_cast <bool> (ISD && "Invalid opcode") ?
void (0) : __assert_fail ("ISD && \"Invalid opcode\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/PowerPC/PPCTargetTransformInfo.cpp"
, 354, __extension__ __PRETTY_FUNCTION__))
;
355
356 if (ST->hasVSX() && Val->getScalarType()->isDoubleTy()) {
357 // Double-precision scalars are already located in index #0.
358 if (Index == 0)
359 return 0;
360
361 return BaseT::getVectorInstrCost(Opcode, Val, Index);
362 } else if (ST->hasQPX() && Val->getScalarType()->isFloatingPointTy()) {
363 // Floating point scalars are already located in index #0.
364 if (Index == 0)
365 return 0;
366
367 return BaseT::getVectorInstrCost(Opcode, Val, Index);
368 }
369
370 // Estimated cost of a load-hit-store delay. This was obtained
371 // experimentally as a minimum needed to prevent unprofitable
372 // vectorization for the paq8p benchmark. It may need to be
373 // raised further if other unprofitable cases remain.
374 unsigned LHSPenalty = 2;
375 if (ISD == ISD::INSERT_VECTOR_ELT)
376 LHSPenalty += 7;
377
378 // Vector element insert/extract with Altivec is very expensive,
379 // because they require store and reload with the attendant
380 // processor stall for load-hit-store. Until VSX is available,
381 // these need to be estimated as very costly.
382 if (ISD == ISD::EXTRACT_VECTOR_ELT ||
383 ISD == ISD::INSERT_VECTOR_ELT)
384 return LHSPenalty + BaseT::getVectorInstrCost(Opcode, Val, Index);
385
386 return BaseT::getVectorInstrCost(Opcode, Val, Index);
387}
388
389int PPCTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
390 unsigned AddressSpace, const Instruction *I) {
391 // Legalize the type.
392 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
393 assert((Opcode == Instruction::Load || Opcode == Instruction::Store) &&(static_cast <bool> ((Opcode == Instruction::Load || Opcode
== Instruction::Store) && "Invalid Opcode") ? void (
0) : __assert_fail ("(Opcode == Instruction::Load || Opcode == Instruction::Store) && \"Invalid Opcode\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/PowerPC/PPCTargetTransformInfo.cpp"
, 394, __extension__ __PRETTY_FUNCTION__))
394 "Invalid Opcode")(static_cast <bool> ((Opcode == Instruction::Load || Opcode
== Instruction::Store) && "Invalid Opcode") ? void (
0) : __assert_fail ("(Opcode == Instruction::Load || Opcode == Instruction::Store) && \"Invalid Opcode\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/PowerPC/PPCTargetTransformInfo.cpp"
, 394, __extension__ __PRETTY_FUNCTION__))
;
395
396 int Cost = BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace);
397
398 bool IsAltivecType = ST->hasAltivec() &&
399 (LT.second == MVT::v16i8 || LT.second == MVT::v8i16 ||
400 LT.second == MVT::v4i32 || LT.second == MVT::v4f32);
401 bool IsVSXType = ST->hasVSX() &&
402 (LT.second == MVT::v2f64 || LT.second == MVT::v2i64);
403 bool IsQPXType = ST->hasQPX() &&
404 (LT.second == MVT::v4f64 || LT.second == MVT::v4f32);
405
406 // VSX has 32b/64b load instructions. Legalization can handle loading of
407 // 32b/64b to VSR correctly and cheaply. But BaseT::getMemoryOpCost and
408 // PPCTargetLowering can't compute the cost appropriately. So here we
409 // explicitly check this case.
410 unsigned MemBytes = Src->getPrimitiveSizeInBits();
411 if (Opcode == Instruction::Load && ST->hasVSX() && IsAltivecType &&
412 (MemBytes == 64 || (ST->hasP8Vector() && MemBytes == 32)))
413 return 1;
414
415 // Aligned loads and stores are easy.
416 unsigned SrcBytes = LT.second.getStoreSize();
417 if (!SrcBytes || !Alignment || Alignment >= SrcBytes)
418 return Cost;
419
420 // If we can use the permutation-based load sequence, then this is also
421 // relatively cheap (not counting loop-invariant instructions): one load plus
422 // one permute (the last load in a series has extra cost, but we're
423 // neglecting that here). Note that on the P7, we could do unaligned loads
424 // for Altivec types using the VSX instructions, but that's more expensive
425 // than using the permutation-based load sequence. On the P8, that's no
426 // longer true.
427 if (Opcode == Instruction::Load &&
428 ((!ST->hasP8Vector() && IsAltivecType) || IsQPXType) &&
429 Alignment >= LT.second.getScalarType().getStoreSize())
430 return Cost + LT.first; // Add the cost of the permutations.
431
432 // For VSX, we can do unaligned loads and stores on Altivec/VSX types. On the
433 // P7, unaligned vector loads are more expensive than the permutation-based
434 // load sequence, so that might be used instead, but regardless, the net cost
435 // is about the same (not counting loop-invariant instructions).
436 if (IsVSXType || (ST->hasVSX() && IsAltivecType))
437 return Cost;
438
439 // Newer PPC supports unaligned memory access.
440 if (TLI->allowsMisalignedMemoryAccesses(LT.second, 0))
441 return Cost;
442
443 // PPC in general does not support unaligned loads and stores. They'll need
444 // to be decomposed based on the alignment factor.
445
446 // Add the cost of each scalar load or store.
447 Cost += LT.first*(SrcBytes/Alignment-1);
448
449 // For a vector type, there is also scalarization overhead (only for
450 // stores, loads are expanded using the vector-load + permutation sequence,
451 // which is much less expensive).
452 if (Src->isVectorTy() && Opcode == Instruction::Store)
453 for (int i = 0, e = Src->getVectorNumElements(); i < e; ++i)
454 Cost += getVectorInstrCost(Instruction::ExtractElement, Src, i);
455
456 return Cost;
457}
458
459int PPCTTIImpl::getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
460 unsigned Factor,
461 ArrayRef<unsigned> Indices,
462 unsigned Alignment,
463 unsigned AddressSpace) {
464 assert(isa<VectorType>(VecTy) &&(static_cast <bool> (isa<VectorType>(VecTy) &&
"Expect a vector type for interleaved memory op") ? void (0)
: __assert_fail ("isa<VectorType>(VecTy) && \"Expect a vector type for interleaved memory op\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/PowerPC/PPCTargetTransformInfo.cpp"
, 465, __extension__ __PRETTY_FUNCTION__))
465 "Expect a vector type for interleaved memory op")(static_cast <bool> (isa<VectorType>(VecTy) &&
"Expect a vector type for interleaved memory op") ? void (0)
: __assert_fail ("isa<VectorType>(VecTy) && \"Expect a vector type for interleaved memory op\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/lib/Target/PowerPC/PPCTargetTransformInfo.cpp"
, 465, __extension__ __PRETTY_FUNCTION__))
;
466
467 // Legalize the type.
468 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, VecTy);
469
470 // Firstly, the cost of load/store operation.
471 int Cost = getMemoryOpCost(Opcode, VecTy, Alignment, AddressSpace);
472
473 // PPC, for both Altivec/VSX and QPX, support cheap arbitrary permutations
474 // (at least in the sense that there need only be one non-loop-invariant
475 // instruction). For each result vector, we need one shuffle per incoming
476 // vector (except that the first shuffle can take two incoming vectors
477 // because it does not need to take itself).
478 Cost += Factor*(LT.first-1);
479
480 return Cost;
481}
482

/build/llvm-toolchain-snapshot-6.0~svn321639/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~svn321639/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~svn321639/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~svn321639/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~svn321639/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 bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) { return true; }
320
321 unsigned getFPOpCost(Type *Ty) { return TargetTransformInfo::TCC_Basic; }
322
323 int getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
324 Type *Ty) {
325 return 0;
326 }
327
328 unsigned getIntImmCost(const APInt &Imm, Type *Ty) { return TTI::TCC_Basic; }
329
330 unsigned getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
331 Type *Ty) {
332 return TTI::TCC_Free;
333 }
334
335 unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
336 Type *Ty) {
337 return TTI::TCC_Free;
338 }
339
340 unsigned getNumberOfRegisters(bool Vector) { return 8; }
341
342 unsigned getRegisterBitWidth(bool Vector) const { return 32; }
343
344 unsigned getMinVectorRegisterBitWidth() { return 128; }
345
346 bool
347 shouldConsiderAddressTypePromotion(const Instruction &I,
348 bool &AllowPromotionWithoutCommonHeader) {
349 AllowPromotionWithoutCommonHeader = false;
350 return false;
351 }
352
353 unsigned getCacheLineSize() { return 0; }
354
355 llvm::Optional<unsigned> getCacheSize(TargetTransformInfo::CacheLevel Level) {
356 switch (Level) {
357 case TargetTransformInfo::CacheLevel::L1D:
358 LLVM_FALLTHROUGH[[clang::fallthrough]];
359 case TargetTransformInfo::CacheLevel::L2D:
360 return llvm::Optional<unsigned>();
361 }
362
363 llvm_unreachable("Unknown TargetTransformInfo::CacheLevel")::llvm::llvm_unreachable_internal("Unknown TargetTransformInfo::CacheLevel"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/Analysis/TargetTransformInfoImpl.h"
, 363)
;
364 }
365
366 llvm::Optional<unsigned> getCacheAssociativity(
367 TargetTransformInfo::CacheLevel Level) {
368 switch (Level) {
369 case TargetTransformInfo::CacheLevel::L1D:
370 LLVM_FALLTHROUGH[[clang::fallthrough]];
371 case TargetTransformInfo::CacheLevel::L2D:
372 return llvm::Optional<unsigned>();
373 }
374
375 llvm_unreachable("Unknown TargetTransformInfo::CacheLevel")::llvm::llvm_unreachable_internal("Unknown TargetTransformInfo::CacheLevel"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/Analysis/TargetTransformInfoImpl.h"
, 375)
;
376 }
377
378 unsigned getPrefetchDistance() { return 0; }
379
380 unsigned getMinPrefetchStride() { return 1; }
381
382 unsigned getMaxPrefetchIterationsAhead() { return UINT_MAX(2147483647 *2U +1U); }
383
384 unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
385
386 unsigned getArithmeticInstrCost(unsigned Opcode, Type *Ty,
387 TTI::OperandValueKind Opd1Info,
388 TTI::OperandValueKind Opd2Info,
389 TTI::OperandValueProperties Opd1PropInfo,
390 TTI::OperandValueProperties Opd2PropInfo,
391 ArrayRef<const Value *> Args) {
392 return 1;
393 }
394
395 unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Ty, int Index,
396 Type *SubTp) {
397 return 1;
398 }
399
400 unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
401 const Instruction *I) { return 1; }
402
403 unsigned getExtractWithExtendCost(unsigned Opcode, Type *Dst,
404 VectorType *VecTy, unsigned Index) {
405 return 1;
406 }
407
408 unsigned getCFInstrCost(unsigned Opcode) { return 1; }
409
410 unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
411 const Instruction *I) {
412 return 1;
413 }
414
415 unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
416 return 1;
417 }
418
419 unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
420 unsigned AddressSpace, const Instruction *I) {
421 return 1;
422 }
423
424 unsigned getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
425 unsigned AddressSpace) {
426 return 1;
427 }
428
429 unsigned getGatherScatterOpCost(unsigned Opcode, Type *DataTy, Value *Ptr,
430 bool VariableMask,
431 unsigned Alignment) {
432 return 1;
433 }
434
435 unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
436 unsigned Factor,
437 ArrayRef<unsigned> Indices,
438 unsigned Alignment,
439 unsigned AddressSpace) {
440 return 1;
441 }
442
443 unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
444 ArrayRef<Type *> Tys, FastMathFlags FMF,
445 unsigned ScalarizationCostPassed) {
446 return 1;
447 }
448 unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
449 ArrayRef<Value *> Args, FastMathFlags FMF, unsigned VF) {
450 return 1;
451 }
452
453 unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) {
454 return 1;
455 }
456
457 unsigned getNumberOfParts(Type *Tp) { return 0; }
458
459 unsigned getAddressComputationCost(Type *Tp, ScalarEvolution *,
460 const SCEV *) {
461 return 0;
462 }
463
464 unsigned getArithmeticReductionCost(unsigned, Type *, bool) { return 1; }
465
466 unsigned getMinMaxReductionCost(Type *, Type *, bool, bool) { return 1; }
467
468 unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) { return 0; }
469
470 bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) {
471 return false;
472 }
473
474 unsigned getAtomicMemIntrinsicMaxElementSize() const {
475 // Note for overrides: You must ensure for all element unordered-atomic
476 // memory intrinsics that all power-of-2 element sizes up to, and
477 // including, the return value of this method have a corresponding
478 // runtime lib call. These runtime lib call definitions can be found
479 // in RuntimeLibcalls.h
480 return 0;
481 }
482
483 Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
484 Type *ExpectedType) {
485 return nullptr;
486 }
487
488 Type *getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length,
489 unsigned SrcAlign, unsigned DestAlign) const {
490 return Type::getInt8Ty(Context);
491 }
492
493 void getMemcpyLoopResidualLoweringType(SmallVectorImpl<Type *> &OpsOut,
494 LLVMContext &Context,
495 unsigned RemainingBytes,
496 unsigned SrcAlign,
497 unsigned DestAlign) const {
498 for (unsigned i = 0; i != RemainingBytes; ++i)
499 OpsOut.push_back(Type::getInt8Ty(Context));
500 }
501
502 bool areInlineCompatible(const Function *Caller,
503 const Function *Callee) const {
504 return (Caller->getFnAttribute("target-cpu") ==
505 Callee->getFnAttribute("target-cpu")) &&
506 (Caller->getFnAttribute("target-features") ==
507 Callee->getFnAttribute("target-features"));
508 }
509
510 unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const { return 128; }
511
512 bool isLegalToVectorizeLoad(LoadInst *LI) const { return true; }
513
514 bool isLegalToVectorizeStore(StoreInst *SI) const { return true; }
515
516 bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
517 unsigned Alignment,
518 unsigned AddrSpace) const {
519 return true;
520 }
521
522 bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
523 unsigned Alignment,
524 unsigned AddrSpace) const {
525 return true;
526 }
527
528 unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
529 unsigned ChainSizeInBytes,
530 VectorType *VecTy) const {
531 return VF;
532 }
533
534 unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
535 unsigned ChainSizeInBytes,
536 VectorType *VecTy) const {
537 return VF;
538 }
539
540 bool useReductionIntrinsic(unsigned Opcode, Type *Ty,
541 TTI::ReductionFlags Flags) const {
542 return false;
543 }
544
545 bool shouldExpandReduction(const IntrinsicInst *II) const {
546 return true;
547 }
548
549protected:
550 // Obtain the minimum required size to hold the value (without the sign)
551 // In case of a vector it returns the min required size for one element.
552 unsigned minRequiredElementSize(const Value* Val, bool &isSigned) {
553 if (isa<ConstantDataVector>(Val) || isa<ConstantVector>(Val)) {
554 const auto* VectorValue = cast<Constant>(Val);
555
556 // In case of a vector need to pick the max between the min
557 // required size for each element
558 auto *VT = cast<VectorType>(Val->getType());
559
560 // Assume unsigned elements
561 isSigned = false;
562
563 // The max required size is the total vector width divided by num
564 // of elements in the vector
565 unsigned MaxRequiredSize = VT->getBitWidth() / VT->getNumElements();
566
567 unsigned MinRequiredSize = 0;
568 for(unsigned i = 0, e = VT->getNumElements(); i < e; ++i) {
569 if (auto* IntElement =
570 dyn_cast<ConstantInt>(VectorValue->getAggregateElement(i))) {
571 bool signedElement = IntElement->getValue().isNegative();
572 // Get the element min required size.
573 unsigned ElementMinRequiredSize =
574 IntElement->getValue().getMinSignedBits() - 1;
575 // In case one element is signed then all the vector is signed.
576 isSigned |= signedElement;
577 // Save the max required bit size between all the elements.
578 MinRequiredSize = std::max(MinRequiredSize, ElementMinRequiredSize);
579 }
580 else {
581 // not an int constant element
582 return MaxRequiredSize;
583 }
584 }
585 return MinRequiredSize;
586 }
587
588 if (const auto* CI = dyn_cast<ConstantInt>(Val)) {
589 isSigned = CI->getValue().isNegative();
590 return CI->getValue().getMinSignedBits() - 1;
591 }
592
593 if (const auto* Cast = dyn_cast<SExtInst>(Val)) {
594 isSigned = true;
595 return Cast->getSrcTy()->getScalarSizeInBits() - 1;
596 }
597
598 if (const auto* Cast = dyn_cast<ZExtInst>(Val)) {
599 isSigned = false;
600 return Cast->getSrcTy()->getScalarSizeInBits();
601 }
602
603 isSigned = false;
604 return Val->getType()->getScalarSizeInBits();
605 }
606
607 bool isStridedAccess(const SCEV *Ptr) {
608 return Ptr && isa<SCEVAddRecExpr>(Ptr);
609 }
610
611 const SCEVConstant *getConstantStrideStep(ScalarEvolution *SE,
612 const SCEV *Ptr) {
613 if (!isStridedAccess(Ptr))
614 return nullptr;
615 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ptr);
616 return dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(*SE));
617 }
618
619 bool isConstantStridedAccessLessThan(ScalarEvolution *SE, const SCEV *Ptr,
620 int64_t MergeDistance) {
621 const SCEVConstant *Step = getConstantStrideStep(SE, Ptr);
622 if (!Step)
623 return false;
624 APInt StrideVal = Step->getAPInt();
625 if (StrideVal.getBitWidth() > 64)
626 return false;
627 // FIXME: Need to take absolute value for negative stride case.
628 return StrideVal.getSExtValue() < MergeDistance;
629 }
630};
631
632/// \brief CRTP base class for use as a mix-in that aids implementing
633/// a TargetTransformInfo-compatible class.
634template <typename T>
635class TargetTransformInfoImplCRTPBase : public TargetTransformInfoImplBase {
636private:
637 typedef TargetTransformInfoImplBase BaseT;
638
639protected:
640 explicit TargetTransformInfoImplCRTPBase(const DataLayout &DL) : BaseT(DL) {}
641
642public:
643 using BaseT::getCallCost;
644
645 unsigned getCallCost(const Function *F, int NumArgs) {
646 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~svn321639/include/llvm/Analysis/TargetTransformInfoImpl.h"
, 646, __extension__ __PRETTY_FUNCTION__))
;
647
648 if (NumArgs < 0)
649 // Set the argument number to the number of explicit arguments in the
650 // function.
651 NumArgs = F->arg_size();
652
653 if (Intrinsic::ID IID = F->getIntrinsicID()) {
654 FunctionType *FTy = F->getFunctionType();
655 SmallVector<Type *, 8> ParamTys(FTy->param_begin(), FTy->param_end());
656 return static_cast<T *>(this)
657 ->getIntrinsicCost(IID, FTy->getReturnType(), ParamTys);
658 }
659
660 if (!static_cast<T *>(this)->isLoweredToCall(F))
661 return TTI::TCC_Basic; // Give a basic cost if it will be lowered
662 // directly.
663
664 return static_cast<T *>(this)->getCallCost(F->getFunctionType(), NumArgs);
665 }
666
667 unsigned getCallCost(const Function *F, ArrayRef<const Value *> Arguments) {
668 // Simply delegate to generic handling of the call.
669 // FIXME: We should use instsimplify or something else to catch calls which
670 // will constant fold with these arguments.
671 return static_cast<T *>(this)->getCallCost(F, Arguments.size());
672 }
673
674 using BaseT::getGEPCost;
675
676 int getGEPCost(Type *PointeeType, const Value *Ptr,
677 ArrayRef<const Value *> Operands) {
678 const GlobalValue *BaseGV = nullptr;
679 if (Ptr != nullptr) {
680 // TODO: will remove this when pointers have an opaque type.
681 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~svn321639/include/llvm/Analysis/TargetTransformInfoImpl.h"
, 683, __extension__ __PRETTY_FUNCTION__))
682 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~svn321639/include/llvm/Analysis/TargetTransformInfoImpl.h"
, 683, __extension__ __PRETTY_FUNCTION__))
683 "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~svn321639/include/llvm/Analysis/TargetTransformInfoImpl.h"
, 683, __extension__ __PRETTY_FUNCTION__))
;
684 BaseGV = dyn_cast<GlobalValue>(Ptr->stripPointerCasts());
685 }
686 bool HasBaseReg = (BaseGV == nullptr);
687
688 auto PtrSizeBits = DL.getPointerTypeSizeInBits(Ptr->getType());
689 APInt BaseOffset(PtrSizeBits, 0);
690 int64_t Scale = 0;
691
692 auto GTI = gep_type_begin(PointeeType, Operands);
693 Type *TargetType = nullptr;
694
695 // Handle the case where the GEP instruction has a single operand,
696 // the basis, therefore TargetType is a nullptr.
697 if (Operands.empty())
698 return !BaseGV ? TTI::TCC_Free : TTI::TCC_Basic;
699
700 for (auto I = Operands.begin(); I != Operands.end(); ++I, ++GTI) {
701 TargetType = GTI.getIndexedType();
702 // We assume that the cost of Scalar GEP with constant index and the
703 // cost of Vector GEP with splat constant index are the same.
704 const ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I);
705 if (!ConstIdx)
706 if (auto Splat = getSplatValue(*I))
707 ConstIdx = dyn_cast<ConstantInt>(Splat);
708 if (StructType *STy = GTI.getStructTypeOrNull()) {
709 // For structures the index is always splat or scalar constant
710 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~svn321639/include/llvm/Analysis/TargetTransformInfoImpl.h"
, 710, __extension__ __PRETTY_FUNCTION__))
;
711 uint64_t Field = ConstIdx->getZExtValue();
712 BaseOffset += DL.getStructLayout(STy)->getElementOffset(Field);
713 } else {
714 int64_t ElementSize = DL.getTypeAllocSize(GTI.getIndexedType());
715 if (ConstIdx) {
716 BaseOffset +=
717 ConstIdx->getValue().sextOrTrunc(PtrSizeBits) * ElementSize;
718 } else {
719 // Needs scale register.
720 if (Scale != 0)
721 // No addressing mode takes two scale registers.
722 return TTI::TCC_Basic;
723 Scale = ElementSize;
724 }
725 }
726 }
727
728 // Assumes the address space is 0 when Ptr is nullptr.
729 unsigned AS =
730 (Ptr == nullptr ? 0 : Ptr->getType()->getPointerAddressSpace());
731
732 if (static_cast<T *>(this)->isLegalAddressingMode(
733 TargetType, const_cast<GlobalValue *>(BaseGV),
734 BaseOffset.sextOrTrunc(64).getSExtValue(), HasBaseReg, Scale, AS))
735 return TTI::TCC_Free;
736 return TTI::TCC_Basic;
737 }
738
739 using BaseT::getIntrinsicCost;
740
741 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
742 ArrayRef<const Value *> Arguments) {
743 // Delegate to the generic intrinsic handling code. This mostly provides an
744 // opportunity for targets to (for example) special case the cost of
745 // certain intrinsics based on constants used as arguments.
746 SmallVector<Type *, 8> ParamTys;
747 ParamTys.reserve(Arguments.size());
748 for (unsigned Idx = 0, Size = Arguments.size(); Idx != Size; ++Idx)
749 ParamTys.push_back(Arguments[Idx]->getType());
750 return static_cast<T *>(this)->getIntrinsicCost(IID, RetTy, ParamTys);
751 }
752
753 unsigned getUserCost(const User *U, ArrayRef<const Value *> Operands) {
754 if (isa<PHINode>(U))
3
Taking false branch
755 return TTI::TCC_Free; // Model all PHI nodes as free.
756
757 // Static alloca doesn't generate target instructions.
758 if (auto *A = dyn_cast<AllocaInst>(U))
4
Taking false branch
759 if (A->isStaticAlloca())
760 return TTI::TCC_Free;
761
762 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
5
Taking false branch
763 return static_cast<T *>(this)->getGEPCost(GEP->getSourceElementType(),
764 GEP->getPointerOperand(),
765 Operands.drop_front());
766 }
767
768 if (auto CS = ImmutableCallSite(U)) {
6
Taking false branch
769 const Function *F = CS.getCalledFunction();
770 if (!F) {
771 // Just use the called value type.
772 Type *FTy = CS.getCalledValue()->getType()->getPointerElementType();
773 return static_cast<T *>(this)
774 ->getCallCost(cast<FunctionType>(FTy), CS.arg_size());
775 }
776
777 SmallVector<const Value *, 8> Arguments(CS.arg_begin(), CS.arg_end());
778 return static_cast<T *>(this)->getCallCost(F, Arguments);
779 }
780
781 if (const CastInst *CI = dyn_cast<CastInst>(U)) {
7
Taking false branch
782 // Result of a cmp instruction is often extended (to be used by other
783 // cmp instructions, logical or return instructions). These are usually
784 // nop on most sane targets.
785 if (isa<CmpInst>(CI->getOperand(0)))
786 return TTI::TCC_Free;
787 if (isa<SExtInst>(CI) || isa<ZExtInst>(CI) || isa<FPExtInst>(CI))
788 return static_cast<T *>(this)->getExtCost(CI, Operands.back());
789 }
790
791 return static_cast<T *>(this)->getOperationCost(
11
Calling 'BasicTTIImplBase::getOperationCost'
792 Operator::getOpcode(U), U->getType(),
793 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'
794 }
795
796 int getInstructionLatency(const Instruction *I) {
797 SmallVector<const Value *, 4> Operands(I->value_op_begin(),
798 I->value_op_end());
799 if (getUserCost(I, Operands) == TTI::TCC_Free)
800 return 0;
801
802 if (isa<LoadInst>(I))
803 return 4;
804
805 Type *DstTy = I->getType();
806
807 // Usually an intrinsic is a simple instruction.
808 // A real function call is much slower.
809 if (auto *CI = dyn_cast<CallInst>(I)) {
810 const Function *F = CI->getCalledFunction();
811 if (!F || static_cast<T *>(this)->isLoweredToCall(F))
812 return 40;
813 // Some intrinsics return a value and a flag, we use the value type
814 // to decide its latency.
815 if (StructType* StructTy = dyn_cast<StructType>(DstTy))
816 DstTy = StructTy->getElementType(0);
817 // Fall through to simple instructions.
818 }
819
820 if (VectorType *VectorTy = dyn_cast<VectorType>(DstTy))
821 DstTy = VectorTy->getElementType();
822 if (DstTy->isFloatingPointTy())
823 return 3;
824
825 return 1;
826 }
827};
828}
829
830#endif

/build/llvm-toolchain-snapshot-6.0~svn321639/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~svn321639/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 bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) {
301 return true;
302 }
303
304 unsigned getFPOpCost(Type *Ty) {
305 // Check whether FADD is available, as a proxy for floating-point in
306 // general.
307 const TargetLoweringBase *TLI = getTLI();
308 EVT VT = TLI->getValueType(DL, Ty);
309 if (TLI->isOperationLegalOrCustomOrPromote(ISD::FADD, VT))
310 return TargetTransformInfo::TCC_Basic;
311 return TargetTransformInfo::TCC_Expensive;
312 }
313
314 unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) {
315 const TargetLoweringBase *TLI = getTLI();
316 switch (Opcode) {
12
Control jumps to the 'default' case at line 317
317 default: break;
13
Execution continues on line 328
318 case Instruction::Trunc:
319 if (TLI->isTruncateFree(OpTy, Ty))
320 return TargetTransformInfo::TCC_Free;
321 return TargetTransformInfo::TCC_Basic;
322 case Instruction::ZExt:
323 if (TLI->isZExtFree(OpTy, Ty))
324 return TargetTransformInfo::TCC_Free;
325 return TargetTransformInfo::TCC_Basic;
326 }
327
328 return BaseT::getOperationCost(Opcode, Ty, OpTy);
14
Passing null pointer value via 3rd parameter 'OpTy'
15
Calling 'TargetTransformInfoImplBase::getOperationCost'
329 }
330
331 unsigned getInliningThresholdMultiplier() { return 1; }
332
333 void getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
334 TTI::UnrollingPreferences &UP) {
335 // This unrolling functionality is target independent, but to provide some
336 // motivation for its intended use, for x86:
337
338 // According to the Intel 64 and IA-32 Architectures Optimization Reference
339 // Manual, Intel Core models and later have a loop stream detector (and
340 // associated uop queue) that can benefit from partial unrolling.
341 // The relevant requirements are:
342 // - The loop must have no more than 4 (8 for Nehalem and later) branches
343 // taken, and none of them may be calls.
344 // - The loop can have no more than 18 (28 for Nehalem and later) uops.
345
346 // According to the Software Optimization Guide for AMD Family 15h
347 // Processors, models 30h-4fh (Steamroller and later) have a loop predictor
348 // and loop buffer which can benefit from partial unrolling.
349 // The relevant requirements are:
350 // - The loop must have fewer than 16 branches
351 // - The loop must have less than 40 uops in all executed loop branches
352
353 // The number of taken branches in a loop is hard to estimate here, and
354 // benchmarking has revealed that it is better not to be conservative when
355 // estimating the branch count. As a result, we'll ignore the branch limits
356 // until someone finds a case where it matters in practice.
357
358 unsigned MaxOps;
359 const TargetSubtargetInfo *ST = getST();
360 if (PartialUnrollingThreshold.getNumOccurrences() > 0)
361 MaxOps = PartialUnrollingThreshold;
362 else if (ST->getSchedModel().LoopMicroOpBufferSize > 0)
363 MaxOps = ST->getSchedModel().LoopMicroOpBufferSize;
364 else
365 return;
366
367 // Scan the loop: don't unroll loops with calls.
368 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
369 ++I) {
370 BasicBlock *BB = *I;
371
372 for (BasicBlock::iterator J = BB->begin(), JE = BB->end(); J != JE; ++J)
373 if (isa<CallInst>(J) || isa<InvokeInst>(J)) {
374 ImmutableCallSite CS(&*J);
375 if (const Function *F = CS.getCalledFunction()) {
376 if (!static_cast<T *>(this)->isLoweredToCall(F))
377 continue;
378 }
379
380 return;
381 }
382 }
383
384 // Enable runtime and partial unrolling up to the specified size.
385 // Enable using trip count upper bound to unroll loops.
386 UP.Partial = UP.Runtime = UP.UpperBound = true;
387 UP.PartialThreshold = MaxOps;
388
389 // Avoid unrolling when optimizing for size.
390 UP.OptSizeThreshold = 0;
391 UP.PartialOptSizeThreshold = 0;
392
393 // Set number of instructions optimized when "back edge"
394 // becomes "fall through" to default value of 2.
395 UP.BEInsns = 2;
396 }
397
398 int getInstructionLatency(const Instruction *I) {
399 if (isa<LoadInst>(I))
400 return getST()->getSchedModel().DefaultLoadLatency;
401
402 return BaseT::getInstructionLatency(I);
403 }
404
405 /// @}
406
407 /// \name Vector TTI Implementations
408 /// @{
409
410 unsigned getNumberOfRegisters(bool Vector) { return Vector ? 0 : 1; }
411
412 unsigned getRegisterBitWidth(bool Vector) const { return 32; }
413
414 /// Estimate the overhead of scalarizing an instruction. Insert and Extract
415 /// are set if the result needs to be inserted and/or extracted from vectors.
416 unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) {
417 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~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 417, __extension__ __PRETTY_FUNCTION__))
;
418 unsigned Cost = 0;
419
420 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
421 if (Insert)
422 Cost += static_cast<T *>(this)
423 ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
424 if (Extract)
425 Cost += static_cast<T *>(this)
426 ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
427 }
428
429 return Cost;
430 }
431
432 /// Estimate the overhead of scalarizing an instructions unique
433 /// non-constant operands. The types of the arguments are ordinarily
434 /// scalar, in which case the costs are multiplied with VF.
435 unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
436 unsigned VF) {
437 unsigned Cost = 0;
438 SmallPtrSet<const Value*, 4> UniqueOperands;
439 for (const Value *A : Args) {
440 if (!isa<Constant>(A) && UniqueOperands.insert(A).second) {
441 Type *VecTy = nullptr;
442 if (A->getType()->isVectorTy()) {
443 VecTy = A->getType();
444 // If A is a vector operand, VF should be 1 or correspond to A.
445 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~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 446, __extension__ __PRETTY_FUNCTION__))
446 "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~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 446, __extension__ __PRETTY_FUNCTION__))
;
447 }
448 else
449 VecTy = VectorType::get(A->getType(), VF);
450
451 Cost += getScalarizationOverhead(VecTy, false, true);
452 }
453 }
454
455 return Cost;
456 }
457
458 unsigned getScalarizationOverhead(Type *VecTy, ArrayRef<const Value *> Args) {
459 assert(VecTy->isVectorTy())(static_cast <bool> (VecTy->isVectorTy()) ? void (0)
: __assert_fail ("VecTy->isVectorTy()", "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 459, __extension__ __PRETTY_FUNCTION__))
;
460
461 unsigned Cost = 0;
462
463 Cost += getScalarizationOverhead(VecTy, true, false);
464 if (!Args.empty())
465 Cost += getOperandsScalarizationOverhead(Args,
466 VecTy->getVectorNumElements());
467 else
468 // When no information on arguments is provided, we add the cost
469 // associated with one argument as a heuristic.
470 Cost += getScalarizationOverhead(VecTy, false, true);
471
472 return Cost;
473 }
474
475 unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
476
477 unsigned getArithmeticInstrCost(
478 unsigned Opcode, Type *Ty,
479 TTI::OperandValueKind Opd1Info = TTI::OK_AnyValue,
480 TTI::OperandValueKind Opd2Info = TTI::OK_AnyValue,
481 TTI::OperandValueProperties Opd1PropInfo = TTI::OP_None,
482 TTI::OperandValueProperties Opd2PropInfo = TTI::OP_None,
483 ArrayRef<const Value *> Args = ArrayRef<const Value *>()) {
484 // Check if any of the operands are vector operands.
485 const TargetLoweringBase *TLI = getTLI();
486 int ISD = TLI->InstructionOpcodeToISD(Opcode);
487 assert(ISD && "Invalid opcode")(static_cast <bool> (ISD && "Invalid opcode") ?
void (0) : __assert_fail ("ISD && \"Invalid opcode\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 487, __extension__ __PRETTY_FUNCTION__))
;
488
489 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
490
491 bool IsFloat = Ty->isFPOrFPVectorTy();
492 // Assume that floating point arithmetic operations cost twice as much as
493 // integer operations.
494 unsigned OpCost = (IsFloat ? 2 : 1);
495
496 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
497 // The operation is legal. Assume it costs 1.
498 // TODO: Once we have extract/insert subvector cost we need to use them.
499 return LT.first * OpCost;
500 }
501
502 if (!TLI->isOperationExpand(ISD, LT.second)) {
503 // If the operation is custom lowered, then assume that the code is twice
504 // as expensive.
505 return LT.first * 2 * OpCost;
506 }
507
508 // Else, assume that we need to scalarize this op.
509 // TODO: If one of the types get legalized by splitting, handle this
510 // similarly to what getCastInstrCost() does.
511 if (Ty->isVectorTy()) {
512 unsigned Num = Ty->getVectorNumElements();
513 unsigned Cost = static_cast<T *>(this)
514 ->getArithmeticInstrCost(Opcode, Ty->getScalarType());
515 // Return the cost of multiple scalar invocation plus the cost of
516 // inserting and extracting the values.
517 return getScalarizationOverhead(Ty, Args) + Num * Cost;
518 }
519
520 // We don't know anything about this scalar instruction.
521 return OpCost;
522 }
523
524 unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
525 Type *SubTp) {
526 if (Kind == TTI::SK_Alternate || Kind == TTI::SK_PermuteTwoSrc ||
527 Kind == TTI::SK_PermuteSingleSrc) {
528 return getPermuteShuffleOverhead(Tp);
529 }
530 return 1;
531 }
532
533 unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
534 const Instruction *I = nullptr) {
535 const TargetLoweringBase *TLI = getTLI();
536 int ISD = TLI->InstructionOpcodeToISD(Opcode);
537 assert(ISD && "Invalid opcode")(static_cast <bool> (ISD && "Invalid opcode") ?
void (0) : __assert_fail ("ISD && \"Invalid opcode\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 537, __extension__ __PRETTY_FUNCTION__))
;
538 std::pair<unsigned, MVT> SrcLT = TLI->getTypeLegalizationCost(DL, Src);
539 std::pair<unsigned, MVT> DstLT = TLI->getTypeLegalizationCost(DL, Dst);
540
541 // Check for NOOP conversions.
542 if (SrcLT.first == DstLT.first &&
543 SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
544
545 // Bitcast between types that are legalized to the same type are free.
546 if (Opcode == Instruction::BitCast || Opcode == Instruction::Trunc)
547 return 0;
548 }
549
550 if (Opcode == Instruction::Trunc &&
551 TLI->isTruncateFree(SrcLT.second, DstLT.second))
552 return 0;
553
554 if (Opcode == Instruction::ZExt &&
555 TLI->isZExtFree(SrcLT.second, DstLT.second))
556 return 0;
557
558 if (Opcode == Instruction::AddrSpaceCast &&
559 TLI->isNoopAddrSpaceCast(Src->getPointerAddressSpace(),
560 Dst->getPointerAddressSpace()))
561 return 0;
562
563 // If this is a zext/sext of a load, return 0 if the corresponding
564 // extending load exists on target.
565 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
566 I && isa<LoadInst>(I->getOperand(0))) {
567 EVT ExtVT = EVT::getEVT(Dst);
568 EVT LoadVT = EVT::getEVT(Src);
569 unsigned LType =
570 ((Opcode == Instruction::ZExt) ? ISD::ZEXTLOAD : ISD::SEXTLOAD);
571 if (TLI->isLoadExtLegal(LType, ExtVT, LoadVT))
572 return 0;
573 }
574
575 // If the cast is marked as legal (or promote) then assume low cost.
576 if (SrcLT.first == DstLT.first &&
577 TLI->isOperationLegalOrPromote(ISD, DstLT.second))
578 return 1;
579
580 // Handle scalar conversions.
581 if (!Src->isVectorTy() && !Dst->isVectorTy()) {
582 // Scalar bitcasts are usually free.
583 if (Opcode == Instruction::BitCast)
584 return 0;
585
586 // Just check the op cost. If the operation is legal then assume it costs
587 // 1.
588 if (!TLI->isOperationExpand(ISD, DstLT.second))
589 return 1;
590
591 // Assume that illegal scalar instruction are expensive.
592 return 4;
593 }
594
595 // Check vector-to-vector casts.
596 if (Dst->isVectorTy() && Src->isVectorTy()) {
597 // If the cast is between same-sized registers, then the check is simple.
598 if (SrcLT.first == DstLT.first &&
599 SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
600
601 // Assume that Zext is done using AND.
602 if (Opcode == Instruction::ZExt)
603 return 1;
604
605 // Assume that sext is done using SHL and SRA.
606 if (Opcode == Instruction::SExt)
607 return 2;
608
609 // Just check the op cost. If the operation is legal then assume it
610 // costs
611 // 1 and multiply by the type-legalization overhead.
612 if (!TLI->isOperationExpand(ISD, DstLT.second))
613 return SrcLT.first * 1;
614 }
615
616 // If we are legalizing by splitting, query the concrete TTI for the cost
617 // of casting the original vector twice. We also need to factor int the
618 // cost of the split itself. Count that as 1, to be consistent with
619 // TLI->getTypeLegalizationCost().
620 if ((TLI->getTypeAction(Src->getContext(), TLI->getValueType(DL, Src)) ==
621 TargetLowering::TypeSplitVector) ||
622 (TLI->getTypeAction(Dst->getContext(), TLI->getValueType(DL, Dst)) ==
623 TargetLowering::TypeSplitVector)) {
624 Type *SplitDst = VectorType::get(Dst->getVectorElementType(),
625 Dst->getVectorNumElements() / 2);
626 Type *SplitSrc = VectorType::get(Src->getVectorElementType(),
627 Src->getVectorNumElements() / 2);
628 T *TTI = static_cast<T *>(this);
629 return TTI->getVectorSplitCost() +
630 (2 * TTI->getCastInstrCost(Opcode, SplitDst, SplitSrc, I));
631 }
632
633 // In other cases where the source or destination are illegal, assume
634 // the operation will get scalarized.
635 unsigned Num = Dst->getVectorNumElements();
636 unsigned Cost = static_cast<T *>(this)->getCastInstrCost(
637 Opcode, Dst->getScalarType(), Src->getScalarType(), I);
638
639 // Return the cost of multiple scalar invocation plus the cost of
640 // inserting and extracting the values.
641 return getScalarizationOverhead(Dst, true, true) + Num * Cost;
642 }
643
644 // We already handled vector-to-vector and scalar-to-scalar conversions.
645 // This
646 // is where we handle bitcast between vectors and scalars. We need to assume
647 // that the conversion is scalarized in one way or another.
648 if (Opcode == Instruction::BitCast)
649 // Illegal bitcasts are done by storing and loading from a stack slot.
650 return (Src->isVectorTy() ? getScalarizationOverhead(Src, false, true)
651 : 0) +
652 (Dst->isVectorTy() ? getScalarizationOverhead(Dst, true, false)
653 : 0);
654
655 llvm_unreachable("Unhandled cast")::llvm::llvm_unreachable_internal("Unhandled cast", "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 655)
;
656 }
657
658 unsigned getExtractWithExtendCost(unsigned Opcode, Type *Dst,
659 VectorType *VecTy, unsigned Index) {
660 return static_cast<T *>(this)->getVectorInstrCost(
661 Instruction::ExtractElement, VecTy, Index) +
662 static_cast<T *>(this)->getCastInstrCost(Opcode, Dst,
663 VecTy->getElementType());
664 }
665
666 unsigned getCFInstrCost(unsigned Opcode) {
667 // Branches are assumed to be predicted.
668 return 0;
669 }
670
671 unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
672 const Instruction *I) {
673 const TargetLoweringBase *TLI = getTLI();
674 int ISD = TLI->InstructionOpcodeToISD(Opcode);
675 assert(ISD && "Invalid opcode")(static_cast <bool> (ISD && "Invalid opcode") ?
void (0) : __assert_fail ("ISD && \"Invalid opcode\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 675, __extension__ __PRETTY_FUNCTION__))
;
676
677 // Selects on vectors are actually vector selects.
678 if (ISD == ISD::SELECT) {
679 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~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 679, __extension__ __PRETTY_FUNCTION__))
;
680 if (CondTy->isVectorTy())
681 ISD = ISD::VSELECT;
682 }
683 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
684
685 if (!(ValTy->isVectorTy() && !LT.second.isVector()) &&
686 !TLI->isOperationExpand(ISD, LT.second)) {
687 // The operation is legal. Assume it costs 1. Multiply
688 // by the type-legalization overhead.
689 return LT.first * 1;
690 }
691
692 // Otherwise, assume that the cast is scalarized.
693 // TODO: If one of the types get legalized by splitting, handle this
694 // similarly to what getCastInstrCost() does.
695 if (ValTy->isVectorTy()) {
696 unsigned Num = ValTy->getVectorNumElements();
697 if (CondTy)
698 CondTy = CondTy->getScalarType();
699 unsigned Cost = static_cast<T *>(this)->getCmpSelInstrCost(
700 Opcode, ValTy->getScalarType(), CondTy, I);
701
702 // Return the cost of multiple scalar invocation plus the cost of
703 // inserting and extracting the values.
704 return getScalarizationOverhead(ValTy, true, false) + Num * Cost;
705 }
706
707 // Unknown scalar opcode.
708 return 1;
709 }
710
711 unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
712 std::pair<unsigned, MVT> LT =
713 getTLI()->getTypeLegalizationCost(DL, Val->getScalarType());
714
715 return LT.first;
716 }
717
718 unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
719 unsigned AddressSpace, const Instruction *I = nullptr) {
720 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~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 720, __extension__ __PRETTY_FUNCTION__))
;
721 std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(DL, Src);
722
723 // Assuming that all loads of legal types cost 1.
724 unsigned Cost = LT.first;
725
726 if (Src->isVectorTy() &&
727 Src->getPrimitiveSizeInBits() < LT.second.getSizeInBits()) {
728 // This is a vector load that legalizes to a larger type than the vector
729 // itself. Unless the corresponding extending load or truncating store is
730 // legal, then this will scalarize.
731 TargetLowering::LegalizeAction LA = TargetLowering::Expand;
732 EVT MemVT = getTLI()->getValueType(DL, Src);
733 if (Opcode == Instruction::Store)
734 LA = getTLI()->getTruncStoreAction(LT.second, MemVT);
735 else
736 LA = getTLI()->getLoadExtAction(ISD::EXTLOAD, LT.second, MemVT);
737
738 if (LA != TargetLowering::Legal && LA != TargetLowering::Custom) {
739 // This is a vector load/store for some illegal type that is scalarized.
740 // We must account for the cost of building or decomposing the vector.
741 Cost += getScalarizationOverhead(Src, Opcode != Instruction::Store,
742 Opcode == Instruction::Store);
743 }
744 }
745
746 return Cost;
747 }
748
749 unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
750 unsigned Factor,
751 ArrayRef<unsigned> Indices,
752 unsigned Alignment,
753 unsigned AddressSpace) {
754 VectorType *VT = dyn_cast<VectorType>(VecTy);
755 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~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 755, __extension__ __PRETTY_FUNCTION__))
;
756
757 unsigned NumElts = VT->getNumElements();
758 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~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 758, __extension__ __PRETTY_FUNCTION__))
;
759
760 unsigned NumSubElts = NumElts / Factor;
761 VectorType *SubVT = VectorType::get(VT->getElementType(), NumSubElts);
762
763 // Firstly, the cost of load/store operation.
764 unsigned Cost = static_cast<T *>(this)->getMemoryOpCost(
765 Opcode, VecTy, Alignment, AddressSpace);
766
767 // Legalize the vector type, and get the legalized and unlegalized type
768 // sizes.
769 MVT VecTyLT = getTLI()->getTypeLegalizationCost(DL, VecTy).second;
770 unsigned VecTySize =
771 static_cast<T *>(this)->getDataLayout().getTypeStoreSize(VecTy);
772 unsigned VecTyLTSize = VecTyLT.getStoreSize();
773
774 // Return the ceiling of dividing A by B.
775 auto ceil = [](unsigned A, unsigned B) { return (A + B - 1) / B; };
776
777 // Scale the cost of the memory operation by the fraction of legalized
778 // instructions that will actually be used. We shouldn't account for the
779 // cost of dead instructions since they will be removed.
780 //
781 // E.g., An interleaved load of factor 8:
782 // %vec = load <16 x i64>, <16 x i64>* %ptr
783 // %v0 = shufflevector %vec, undef, <0, 8>
784 //
785 // If <16 x i64> is legalized to 8 v2i64 loads, only 2 of the loads will be
786 // used (those corresponding to elements [0:1] and [8:9] of the unlegalized
787 // type). The other loads are unused.
788 //
789 // We only scale the cost of loads since interleaved store groups aren't
790 // allowed to have gaps.
791 if (Opcode == Instruction::Load && VecTySize > VecTyLTSize) {
792 // The number of loads of a legal type it will take to represent a load
793 // of the unlegalized vector type.
794 unsigned NumLegalInsts = ceil(VecTySize, VecTyLTSize);
795
796 // The number of elements of the unlegalized type that correspond to a
797 // single legal instruction.
798 unsigned NumEltsPerLegalInst = ceil(NumElts, NumLegalInsts);
799
800 // Determine which legal instructions will be used.
801 BitVector UsedInsts(NumLegalInsts, false);
802 for (unsigned Index : Indices)
803 for (unsigned Elt = 0; Elt < NumSubElts; ++Elt)
804 UsedInsts.set((Index + Elt * Factor) / NumEltsPerLegalInst);
805
806 // Scale the cost of the load by the fraction of legal instructions that
807 // will be used.
808 Cost *= UsedInsts.count() / NumLegalInsts;
809 }
810
811 // Then plus the cost of interleave operation.
812 if (Opcode == Instruction::Load) {
813 // The interleave cost is similar to extract sub vectors' elements
814 // from the wide vector, and insert them into sub vectors.
815 //
816 // E.g. An interleaved load of factor 2 (with one member of index 0):
817 // %vec = load <8 x i32>, <8 x i32>* %ptr
818 // %v0 = shuffle %vec, undef, <0, 2, 4, 6> ; Index 0
819 // The cost is estimated as extract elements at 0, 2, 4, 6 from the
820 // <8 x i32> vector and insert them into a <4 x i32> vector.
821
822 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~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 823, __extension__ __PRETTY_FUNCTION__))
823 "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~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 823, __extension__ __PRETTY_FUNCTION__))
;
824
825 for (unsigned Index : Indices) {
826 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~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 826, __extension__ __PRETTY_FUNCTION__))
;
827
828 // Extract elements from loaded vector for each sub vector.
829 for (unsigned i = 0; i < NumSubElts; i++)
830 Cost += static_cast<T *>(this)->getVectorInstrCost(
831 Instruction::ExtractElement, VT, Index + i * Factor);
832 }
833
834 unsigned InsSubCost = 0;
835 for (unsigned i = 0; i < NumSubElts; i++)
836 InsSubCost += static_cast<T *>(this)->getVectorInstrCost(
837 Instruction::InsertElement, SubVT, i);
838
839 Cost += Indices.size() * InsSubCost;
840 } else {
841 // The interleave cost is extract all elements from sub vectors, and
842 // insert them into the wide vector.
843 //
844 // E.g. An interleaved store of factor 2:
845 // %v0_v1 = shuffle %v0, %v1, <0, 4, 1, 5, 2, 6, 3, 7>
846 // store <8 x i32> %interleaved.vec, <8 x i32>* %ptr
847 // The cost is estimated as extract all elements from both <4 x i32>
848 // vectors and insert into the <8 x i32> vector.
849
850 unsigned ExtSubCost = 0;
851 for (unsigned i = 0; i < NumSubElts; i++)
852 ExtSubCost += static_cast<T *>(this)->getVectorInstrCost(
853 Instruction::ExtractElement, SubVT, i);
854 Cost += ExtSubCost * Factor;
855
856 for (unsigned i = 0; i < NumElts; i++)
857 Cost += static_cast<T *>(this)
858 ->getVectorInstrCost(Instruction::InsertElement, VT, i);
859 }
860
861 return Cost;
862 }
863
864 /// Get intrinsic cost based on arguments.
865 unsigned getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
866 ArrayRef<Value *> Args, FastMathFlags FMF,
867 unsigned VF = 1) {
868 unsigned RetVF = (RetTy->isVectorTy() ? RetTy->getVectorNumElements() : 1);
869 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~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 869, __extension__ __PRETTY_FUNCTION__))
;
870
871 switch (IID) {
872 default: {
873 // Assume that we need to scalarize this intrinsic.
874 SmallVector<Type *, 4> Types;
875 for (Value *Op : Args) {
876 Type *OpTy = Op->getType();
877 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~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 877, __extension__ __PRETTY_FUNCTION__))
;
878 Types.push_back(VF == 1 ? OpTy : VectorType::get(OpTy, VF));
879 }
880
881 if (VF > 1 && !RetTy->isVoidTy())
882 RetTy = VectorType::get(RetTy, VF);
883
884 // Compute the scalarization overhead based on Args for a vector
885 // intrinsic. A vectorizer will pass a scalar RetTy and VF > 1, while
886 // CostModel will pass a vector RetTy and VF is 1.
887 unsigned ScalarizationCost = std::numeric_limits<unsigned>::max();
888 if (RetVF > 1 || VF > 1) {
889 ScalarizationCost = 0;
890 if (!RetTy->isVoidTy())
891 ScalarizationCost += getScalarizationOverhead(RetTy, true, false);
892 ScalarizationCost += getOperandsScalarizationOverhead(Args, VF);
893 }
894
895 return static_cast<T *>(this)->
896 getIntrinsicInstrCost(IID, RetTy, Types, FMF, ScalarizationCost);
897 }
898 case Intrinsic::masked_scatter: {
899 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~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 899, __extension__ __PRETTY_FUNCTION__))
;
900 Value *Mask = Args[3];
901 bool VarMask = !isa<Constant>(Mask);
902 unsigned Alignment = cast<ConstantInt>(Args[2])->getZExtValue();
903 return
904 static_cast<T *>(this)->getGatherScatterOpCost(Instruction::Store,
905 Args[0]->getType(),
906 Args[1], VarMask,
907 Alignment);
908 }
909 case Intrinsic::masked_gather: {
910 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~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 910, __extension__ __PRETTY_FUNCTION__))
;
911 Value *Mask = Args[2];
912 bool VarMask = !isa<Constant>(Mask);
913 unsigned Alignment = cast<ConstantInt>(Args[1])->getZExtValue();
914 return
915 static_cast<T *>(this)->getGatherScatterOpCost(Instruction::Load,
916 RetTy, Args[0], VarMask,
917 Alignment);
918 }
919 }
920 }
921
922 /// Get intrinsic cost based on argument types.
923 /// If ScalarizationCostPassed is std::numeric_limits<unsigned>::max(), the
924 /// cost of scalarizing the arguments and the return value will be computed
925 /// based on types.
926 unsigned getIntrinsicInstrCost(
927 Intrinsic::ID IID, Type *RetTy, ArrayRef<Type *> Tys, FastMathFlags FMF,
928 unsigned ScalarizationCostPassed = std::numeric_limits<unsigned>::max()) {
929 SmallVector<unsigned, 2> ISDs;
930 unsigned SingleCallCost = 10; // Library call cost. Make it expensive.
931 switch (IID) {
932 default: {
933 // Assume that we need to scalarize this intrinsic.
934 unsigned ScalarizationCost = ScalarizationCostPassed;
935 unsigned ScalarCalls = 1;
936 Type *ScalarRetTy = RetTy;
937 if (RetTy->isVectorTy()) {
938 if (ScalarizationCostPassed == std::numeric_limits<unsigned>::max())
939 ScalarizationCost = getScalarizationOverhead(RetTy, true, false);
940 ScalarCalls = std::max(ScalarCalls, RetTy->getVectorNumElements());
941 ScalarRetTy = RetTy->getScalarType();
942 }
943 SmallVector<Type *, 4> ScalarTys;
944 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
945 Type *Ty = Tys[i];
946 if (Ty->isVectorTy()) {
947 if (ScalarizationCostPassed == std::numeric_limits<unsigned>::max())
948 ScalarizationCost += getScalarizationOverhead(Ty, false, true);
949 ScalarCalls = std::max(ScalarCalls, Ty->getVectorNumElements());
950 Ty = Ty->getScalarType();
951 }
952 ScalarTys.push_back(Ty);
953 }
954 if (ScalarCalls == 1)
955 return 1; // Return cost of a scalar intrinsic. Assume it to be cheap.
956
957 unsigned ScalarCost = static_cast<T *>(this)->getIntrinsicInstrCost(
958 IID, ScalarRetTy, ScalarTys, FMF);
959
960 return ScalarCalls * ScalarCost + ScalarizationCost;
961 }
962 // Look for intrinsics that can be lowered directly or turned into a scalar
963 // intrinsic call.
964 case Intrinsic::sqrt:
965 ISDs.push_back(ISD::FSQRT);
966 break;
967 case Intrinsic::sin:
968 ISDs.push_back(ISD::FSIN);
969 break;
970 case Intrinsic::cos:
971 ISDs.push_back(ISD::FCOS);
972 break;
973 case Intrinsic::exp:
974 ISDs.push_back(ISD::FEXP);
975 break;
976 case Intrinsic::exp2:
977 ISDs.push_back(ISD::FEXP2);
978 break;
979 case Intrinsic::log:
980 ISDs.push_back(ISD::FLOG);
981 break;
982 case Intrinsic::log10:
983 ISDs.push_back(ISD::FLOG10);
984 break;
985 case Intrinsic::log2:
986 ISDs.push_back(ISD::FLOG2);
987 break;
988 case Intrinsic::fabs:
989 ISDs.push_back(ISD::FABS);
990 break;
991 case Intrinsic::minnum:
992 ISDs.push_back(ISD::FMINNUM);
993 if (FMF.noNaNs())
994 ISDs.push_back(ISD::FMINNAN);
995 break;
996 case Intrinsic::maxnum:
997 ISDs.push_back(ISD::FMAXNUM);
998 if (FMF.noNaNs())
999 ISDs.push_back(ISD::FMAXNAN);
1000 break;
1001 case Intrinsic::copysign:
1002 ISDs.push_back(ISD::FCOPYSIGN);
1003 break;
1004 case Intrinsic::floor:
1005 ISDs.push_back(ISD::FFLOOR);
1006 break;
1007 case Intrinsic::ceil:
1008 ISDs.push_back(ISD::FCEIL);
1009 break;
1010 case Intrinsic::trunc:
1011 ISDs.push_back(ISD::FTRUNC);
1012 break;
1013 case Intrinsic::nearbyint:
1014 ISDs.push_back(ISD::FNEARBYINT);
1015 break;
1016 case Intrinsic::rint:
1017 ISDs.push_back(ISD::FRINT);
1018 break;
1019 case Intrinsic::round:
1020 ISDs.push_back(ISD::FROUND);
1021 break;
1022 case Intrinsic::pow:
1023 ISDs.push_back(ISD::FPOW);
1024 break;
1025 case Intrinsic::fma:
1026 ISDs.push_back(ISD::FMA);
1027 break;
1028 case Intrinsic::fmuladd:
1029 ISDs.push_back(ISD::FMA);
1030 break;
1031 // FIXME: We should return 0 whenever getIntrinsicCost == TCC_Free.
1032 case Intrinsic::lifetime_start:
1033 case Intrinsic::lifetime_end:
1034 case Intrinsic::sideeffect:
1035 return 0;
1036 case Intrinsic::masked_store:
1037 return static_cast<T *>(this)
1038 ->getMaskedMemoryOpCost(Instruction::Store, Tys[0], 0, 0);
1039 case Intrinsic::masked_load:
1040 return static_cast<T *>(this)
1041 ->getMaskedMemoryOpCost(Instruction::Load, RetTy, 0, 0);
1042 case Intrinsic::ctpop:
1043 ISDs.push_back(ISD::CTPOP);
1044 // In case of legalization use TCC_Expensive. This is cheaper than a
1045 // library call but still not a cheap instruction.
1046 SingleCallCost = TargetTransformInfo::TCC_Expensive;
1047 break;
1048 // FIXME: ctlz, cttz, ...
1049 }
1050
1051 const TargetLoweringBase *TLI = getTLI();
1052 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, RetTy);
1053
1054 SmallVector<unsigned, 2> LegalCost;
1055 SmallVector<unsigned, 2> CustomCost;
1056 for (unsigned ISD : ISDs) {
1057 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
1058 if (IID == Intrinsic::fabs && TLI->isFAbsFree(LT.second)) {
1059 return 0;
1060 }
1061
1062 // The operation is legal. Assume it costs 1.
1063 // If the type is split to multiple registers, assume that there is some
1064 // overhead to this.
1065 // TODO: Once we have extract/insert subvector cost we need to use them.
1066 if (LT.first > 1)
1067 LegalCost.push_back(LT.first * 2);
1068 else
1069 LegalCost.push_back(LT.first * 1);
1070 } else if (!TLI->isOperationExpand(ISD, LT.second)) {
1071 // If the operation is custom lowered then assume
1072 // that the code is twice as expensive.
1073 CustomCost.push_back(LT.first * 2);
1074 }
1075 }
1076
1077 auto MinLegalCostI = std::min_element(LegalCost.begin(), LegalCost.end());
1078 if (MinLegalCostI != LegalCost.end())
1079 return *MinLegalCostI;
1080
1081 auto MinCustomCostI = std::min_element(CustomCost.begin(), CustomCost.end());
1082 if (MinCustomCostI != CustomCost.end())
1083 return *MinCustomCostI;
1084
1085 // If we can't lower fmuladd into an FMA estimate the cost as a floating
1086 // point mul followed by an add.
1087 if (IID == Intrinsic::fmuladd)
1088 return static_cast<T *>(this)
1089 ->getArithmeticInstrCost(BinaryOperator::FMul, RetTy) +
1090 static_cast<T *>(this)
1091 ->getArithmeticInstrCost(BinaryOperator::FAdd, RetTy);
1092
1093 // Else, assume that we need to scalarize this intrinsic. For math builtins
1094 // this will emit a costly libcall, adding call overhead and spills. Make it
1095 // very expensive.
1096 if (RetTy->isVectorTy()) {
1097 unsigned ScalarizationCost =
1098 ((ScalarizationCostPassed != std::numeric_limits<unsigned>::max())
1099 ? ScalarizationCostPassed
1100 : getScalarizationOverhead(RetTy, true, false));
1101 unsigned ScalarCalls = RetTy->getVectorNumElements();
1102 SmallVector<Type *, 4> ScalarTys;
1103 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
1104 Type *Ty = Tys[i];
1105 if (Ty->isVectorTy())
1106 Ty = Ty->getScalarType();
1107 ScalarTys.push_back(Ty);
1108 }
1109 unsigned ScalarCost = static_cast<T *>(this)->getIntrinsicInstrCost(
1110 IID, RetTy->getScalarType(), ScalarTys, FMF);
1111 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
1112 if (Tys[i]->isVectorTy()) {
1113 if (ScalarizationCostPassed == std::numeric_limits<unsigned>::max())
1114 ScalarizationCost += getScalarizationOverhead(Tys[i], false, true);
1115 ScalarCalls = std::max(ScalarCalls, Tys[i]->getVectorNumElements());
1116 }
1117 }
1118
1119 return ScalarCalls * ScalarCost + ScalarizationCost;
1120 }
1121
1122 // This is going to be turned into a library call, make it expensive.
1123 return SingleCallCost;
1124 }
1125
1126 /// \brief Compute a cost of the given call instruction.
1127 ///
1128 /// Compute the cost of calling function F with return type RetTy and
1129 /// argument types Tys. F might be nullptr, in this case the cost of an
1130 /// arbitrary call with the specified signature will be returned.
1131 /// This is used, for instance, when we estimate call of a vector
1132 /// counterpart of the given function.
1133 /// \param F Called function, might be nullptr.
1134 /// \param RetTy Return value types.
1135 /// \param Tys Argument types.
1136 /// \returns The cost of Call instruction.
1137 unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) {
1138 return 10;
1139 }
1140
1141 unsigned getNumberOfParts(Type *Tp) {
1142 std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(DL, Tp);
1143 return LT.first;
1144 }
1145
1146 unsigned getAddressComputationCost(Type *Ty, ScalarEvolution *,
1147 const SCEV *) {
1148 return 0;
1149 }
1150
1151 /// Try to calculate arithmetic and shuffle op costs for reduction operations.
1152 /// We're assuming that reduction operation are performing the following way:
1153 /// 1. Non-pairwise reduction
1154 /// %val1 = shufflevector<n x t> %val, <n x t> %undef,
1155 /// <n x i32> <i32 n/2, i32 n/2 + 1, ..., i32 n, i32 undef, ..., i32 undef>
1156 /// \----------------v-------------/ \----------v------------/
1157 /// n/2 elements n/2 elements
1158 /// %red1 = op <n x t> %val, <n x t> val1
1159 /// After this operation we have a vector %red1 where only the first n/2
1160 /// elements are meaningful, the second n/2 elements are undefined and can be
1161 /// dropped. All other operations are actually working with the vector of
1162 /// length n/2, not n, though the real vector length is still n.
1163 /// %val2 = shufflevector<n x t> %red1, <n x t> %undef,
1164 /// <n x i32> <i32 n/4, i32 n/4 + 1, ..., i32 n/2, i32 undef, ..., i32 undef>
1165 /// \----------------v-------------/ \----------v------------/
1166 /// n/4 elements 3*n/4 elements
1167 /// %red2 = op <n x t> %red1, <n x t> val2 - working with the vector of
1168 /// length n/2, the resulting vector has length n/4 etc.
1169 /// 2. Pairwise reduction:
1170 /// Everything is the same except for an additional shuffle operation which
1171 /// is used to produce operands for pairwise kind of reductions.
1172 /// %val1 = shufflevector<n x t> %val, <n x t> %undef,
1173 /// <n x i32> <i32 0, i32 2, ..., i32 n-2, i32 undef, ..., i32 undef>
1174 /// \-------------v----------/ \----------v------------/
1175 /// n/2 elements n/2 elements
1176 /// %val2 = shufflevector<n x t> %val, <n x t> %undef,
1177 /// <n x i32> <i32 1, i32 3, ..., i32 n-1, i32 undef, ..., i32 undef>
1178 /// \-------------v----------/ \----------v------------/
1179 /// n/2 elements n/2 elements
1180 /// %red1 = op <n x t> %val1, <n x t> val2
1181 /// Again, the operation is performed on <n x t> vector, but the resulting
1182 /// vector %red1 is <n/2 x t> vector.
1183 ///
1184 /// The cost model should take into account that the actual length of the
1185 /// vector is reduced on each iteration.
1186 unsigned getArithmeticReductionCost(unsigned Opcode, Type *Ty,
1187 bool IsPairwise) {
1188 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~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 1188, __extension__ __PRETTY_FUNCTION__))
;
1189 Type *ScalarTy = Ty->getVectorElementType();
1190 unsigned NumVecElts = Ty->getVectorNumElements();
1191 unsigned NumReduxLevels = Log2_32(NumVecElts);
1192 unsigned ArithCost = 0;
1193 unsigned ShuffleCost = 0;
1194 auto *ConcreteTTI = static_cast<T *>(this);
1195 std::pair<unsigned, MVT> LT =
1196 ConcreteTTI->getTLI()->getTypeLegalizationCost(DL, Ty);
1197 unsigned LongVectorCount = 0;
1198 unsigned MVTLen =
1199 LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
1200 while (NumVecElts > MVTLen) {
1201 NumVecElts /= 2;
1202 // Assume the pairwise shuffles add a cost.
1203 ShuffleCost += (IsPairwise + 1) *
1204 ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1205 NumVecElts, Ty);
1206 ArithCost += ConcreteTTI->getArithmeticInstrCost(Opcode, Ty);
1207 Ty = VectorType::get(ScalarTy, NumVecElts);
1208 ++LongVectorCount;
1209 }
1210 // The minimal length of the vector is limited by the real length of vector
1211 // operations performed on the current platform. That's why several final
1212 // reduction operations are performed on the vectors with the same
1213 // architecture-dependent length.
1214 ShuffleCost += (NumReduxLevels - LongVectorCount) * (IsPairwise + 1) *
1215 ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1216 NumVecElts, Ty);
1217 ArithCost += (NumReduxLevels - LongVectorCount) *
1218 ConcreteTTI->getArithmeticInstrCost(Opcode, Ty);
1219 return ShuffleCost + ArithCost + getScalarizationOverhead(Ty, false, true);
1220 }
1221
1222 /// Try to calculate op costs for min/max reduction operations.
1223 /// \param CondTy Conditional type for the Select instruction.
1224 unsigned getMinMaxReductionCost(Type *Ty, Type *CondTy, bool IsPairwise,
1225 bool) {
1226 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~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 1226, __extension__ __PRETTY_FUNCTION__))
;
1227 Type *ScalarTy = Ty->getVectorElementType();
1228 Type *ScalarCondTy = CondTy->getVectorElementType();
1229 unsigned NumVecElts = Ty->getVectorNumElements();
1230 unsigned NumReduxLevels = Log2_32(NumVecElts);
1231 unsigned CmpOpcode;
1232 if (Ty->isFPOrFPVectorTy()) {
1233 CmpOpcode = Instruction::FCmp;
1234 } else {
1235 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~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 1236, __extension__ __PRETTY_FUNCTION__))
1236 "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~svn321639/include/llvm/CodeGen/BasicTTIImpl.h"
, 1236, __extension__ __PRETTY_FUNCTION__))
;
1237 CmpOpcode = Instruction::ICmp;
1238 }
1239 unsigned MinMaxCost = 0;
1240 unsigned ShuffleCost = 0;
1241 auto *ConcreteTTI = static_cast<T *>(this);
1242 std::pair<unsigned, MVT> LT =
1243 ConcreteTTI->getTLI()->getTypeLegalizationCost(DL, Ty);
1244 unsigned LongVectorCount = 0;
1245 unsigned MVTLen =
1246 LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
1247 while (NumVecElts > MVTLen) {
1248 NumVecElts /= 2;
1249 // Assume the pairwise shuffles add a cost.
1250 ShuffleCost += (IsPairwise + 1) *
1251 ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1252 NumVecElts, Ty);
1253 MinMaxCost +=
1254 ConcreteTTI->getCmpSelInstrCost(CmpOpcode, Ty, CondTy, nullptr) +
1255 ConcreteTTI->getCmpSelInstrCost(Instruction::Select, Ty, CondTy,
1256 nullptr);
1257 Ty = VectorType::get(ScalarTy, NumVecElts);
1258 CondTy = VectorType::get(ScalarCondTy, NumVecElts);
1259 ++LongVectorCount;
1260 }
1261 // The minimal length of the vector is limited by the real length of vector
1262 // operations performed on the current platform. That's why several final
1263 // reduction opertions are perfomed on the vectors with the same
1264 // architecture-dependent length.
1265 ShuffleCost += (NumReduxLevels - LongVectorCount) * (IsPairwise + 1) *
1266 ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1267 NumVecElts, Ty);
1268 MinMaxCost +=
1269 (NumReduxLevels - LongVectorCount) *
1270 (ConcreteTTI->getCmpSelInstrCost(CmpOpcode, Ty, CondTy, nullptr) +
1271 ConcreteTTI->getCmpSelInstrCost(Instruction::Select, Ty, CondTy,
1272 nullptr));
1273 // Need 3 extractelement instructions for scalarization + an additional
1274 // scalar select instruction.
1275 return ShuffleCost + MinMaxCost +
1276 3 * getScalarizationOverhead(Ty, /*Insert=*/false,
1277 /*Extract=*/true) +
1278 ConcreteTTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
1279 ScalarCondTy, nullptr);
1280 }
1281
1282 unsigned getVectorSplitCost() { return 1; }
1283
1284 /// @}
1285};
1286
1287/// \brief Concrete BasicTTIImpl that can be used if no further customization
1288/// is needed.
1289class BasicTTIImpl : public BasicTTIImplBase<BasicTTIImpl> {
1290 using BaseT = BasicTTIImplBase<BasicTTIImpl>;
1291
1292 friend class BasicTTIImplBase<BasicTTIImpl>;
1293
1294 const TargetSubtargetInfo *ST;
1295 const TargetLoweringBase *TLI;
1296
1297 const TargetSubtargetInfo *getST() const { return ST; }
1298 const TargetLoweringBase *getTLI() const { return TLI; }
1299
1300public:
1301 explicit BasicTTIImpl(const TargetMachine *ST, const Function &F);
1302};
1303
1304} // end namespace llvm
1305
1306#endif // LLVM_CODEGEN_BASICTTIIMPL_H