Bug Summary

File:llvm/include/llvm/CodeGen/BasicTTIImpl.h
Warning:line 428, column 36
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name X86TargetTransformInfo.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/lib/Target/X86 -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86 -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/lib/Target/X86 -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-12-07-102640-14763-1 -x c++ /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp

1//===-- X86TargetTransformInfo.cpp - X86 specific TTI pass ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8/// \file
9/// This file implements a TargetTransformInfo analysis pass specific to the
10/// X86 target machine. It uses the target's detailed information to provide
11/// more precise answers to certain TTI queries, while letting the target
12/// independent and default TTI implementations handle the rest.
13///
14//===----------------------------------------------------------------------===//
15/// About Cost Model numbers used below it's necessary to say the following:
16/// the numbers correspond to some "generic" X86 CPU instead of usage of
17/// concrete CPU model. Usually the numbers correspond to CPU where the feature
18/// apeared at the first time. For example, if we do Subtarget.hasSSE42() in
19/// the lookups below the cost is based on Nehalem as that was the first CPU
20/// to support that feature level and thus has most likely the worst case cost.
21/// Some examples of other technologies/CPUs:
22/// SSE 3 - Pentium4 / Athlon64
23/// SSE 4.1 - Penryn
24/// SSE 4.2 - Nehalem
25/// AVX - Sandy Bridge
26/// AVX2 - Haswell
27/// AVX-512 - Xeon Phi / Skylake
28/// And some examples of instruction target dependent costs (latency)
29/// divss sqrtss rsqrtss
30/// AMD K7 11-16 19 3
31/// Piledriver 9-24 13-15 5
32/// Jaguar 14 16 2
33/// Pentium II,III 18 30 2
34/// Nehalem 7-14 7-18 3
35/// Haswell 10-13 11 5
36/// TODO: Develop and implement the target dependent cost model and
37/// specialize cost numbers for different Cost Model Targets such as throughput,
38/// code size, latency and uop count.
39//===----------------------------------------------------------------------===//
40
41#include "X86TargetTransformInfo.h"
42#include "llvm/Analysis/TargetTransformInfo.h"
43#include "llvm/CodeGen/BasicTTIImpl.h"
44#include "llvm/CodeGen/CostTable.h"
45#include "llvm/CodeGen/TargetLowering.h"
46#include "llvm/IR/IntrinsicInst.h"
47#include "llvm/Support/Debug.h"
48
49using namespace llvm;
50
51#define DEBUG_TYPE"x86tti" "x86tti"
52
53//===----------------------------------------------------------------------===//
54//
55// X86 cost model.
56//
57//===----------------------------------------------------------------------===//
58
59TargetTransformInfo::PopcntSupportKind
60X86TTIImpl::getPopcntSupport(unsigned TyWidth) {
61 assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2")((isPowerOf2_32(TyWidth) && "Ty width must be power of 2"
) ? static_cast<void> (0) : __assert_fail ("isPowerOf2_32(TyWidth) && \"Ty width must be power of 2\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 61, __PRETTY_FUNCTION__))
;
62 // TODO: Currently the __builtin_popcount() implementation using SSE3
63 // instructions is inefficient. Once the problem is fixed, we should
64 // call ST->hasSSE3() instead of ST->hasPOPCNT().
65 return ST->hasPOPCNT() ? TTI::PSK_FastHardware : TTI::PSK_Software;
66}
67
68llvm::Optional<unsigned> X86TTIImpl::getCacheSize(
69 TargetTransformInfo::CacheLevel Level) const {
70 switch (Level) {
71 case TargetTransformInfo::CacheLevel::L1D:
72 // - Penryn
73 // - Nehalem
74 // - Westmere
75 // - Sandy Bridge
76 // - Ivy Bridge
77 // - Haswell
78 // - Broadwell
79 // - Skylake
80 // - Kabylake
81 return 32 * 1024; // 32 KByte
82 case TargetTransformInfo::CacheLevel::L2D:
83 // - Penryn
84 // - Nehalem
85 // - Westmere
86 // - Sandy Bridge
87 // - Ivy Bridge
88 // - Haswell
89 // - Broadwell
90 // - Skylake
91 // - Kabylake
92 return 256 * 1024; // 256 KByte
93 }
94
95 llvm_unreachable("Unknown TargetTransformInfo::CacheLevel")::llvm::llvm_unreachable_internal("Unknown TargetTransformInfo::CacheLevel"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 95)
;
96}
97
98llvm::Optional<unsigned> X86TTIImpl::getCacheAssociativity(
99 TargetTransformInfo::CacheLevel Level) const {
100 // - Penryn
101 // - Nehalem
102 // - Westmere
103 // - Sandy Bridge
104 // - Ivy Bridge
105 // - Haswell
106 // - Broadwell
107 // - Skylake
108 // - Kabylake
109 switch (Level) {
110 case TargetTransformInfo::CacheLevel::L1D:
111 LLVM_FALLTHROUGH[[gnu::fallthrough]];
112 case TargetTransformInfo::CacheLevel::L2D:
113 return 8;
114 }
115
116 llvm_unreachable("Unknown TargetTransformInfo::CacheLevel")::llvm::llvm_unreachable_internal("Unknown TargetTransformInfo::CacheLevel"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 116)
;
117}
118
119unsigned X86TTIImpl::getNumberOfRegisters(unsigned ClassID) const {
120 bool Vector = (ClassID == 1);
121 if (Vector && !ST->hasSSE1())
122 return 0;
123
124 if (ST->is64Bit()) {
125 if (Vector && ST->hasAVX512())
126 return 32;
127 return 16;
128 }
129 return 8;
130}
131
132unsigned X86TTIImpl::getRegisterBitWidth(bool Vector) const {
133 unsigned PreferVectorWidth = ST->getPreferVectorWidth();
134 if (Vector) {
135 if (ST->hasAVX512() && PreferVectorWidth >= 512)
136 return 512;
137 if (ST->hasAVX() && PreferVectorWidth >= 256)
138 return 256;
139 if (ST->hasSSE1() && PreferVectorWidth >= 128)
140 return 128;
141 return 0;
142 }
143
144 if (ST->is64Bit())
145 return 64;
146
147 return 32;
148}
149
150unsigned X86TTIImpl::getLoadStoreVecRegBitWidth(unsigned) const {
151 return getRegisterBitWidth(true);
152}
153
154unsigned X86TTIImpl::getMaxInterleaveFactor(unsigned VF) {
155 // If the loop will not be vectorized, don't interleave the loop.
156 // Let regular unroll to unroll the loop, which saves the overflow
157 // check and memory check cost.
158 if (VF == 1)
159 return 1;
160
161 if (ST->isAtom())
162 return 1;
163
164 // Sandybridge and Haswell have multiple execution ports and pipelined
165 // vector units.
166 if (ST->hasAVX())
167 return 4;
168
169 return 2;
170}
171
172int X86TTIImpl::getArithmeticInstrCost(
173 unsigned Opcode, Type *Ty,
174 TTI::OperandValueKind Op1Info, TTI::OperandValueKind Op2Info,
175 TTI::OperandValueProperties Opd1PropInfo,
176 TTI::OperandValueProperties Opd2PropInfo,
177 ArrayRef<const Value *> Args) {
178 // Legalize the type.
179 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
180
181 int ISD = TLI->InstructionOpcodeToISD(Opcode);
182 assert(ISD && "Invalid opcode")((ISD && "Invalid opcode") ? static_cast<void> (
0) : __assert_fail ("ISD && \"Invalid opcode\"", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 182, __PRETTY_FUNCTION__))
;
183
184 static const CostTblEntry GLMCostTable[] = {
185 { ISD::FDIV, MVT::f32, 18 }, // divss
186 { ISD::FDIV, MVT::v4f32, 35 }, // divps
187 { ISD::FDIV, MVT::f64, 33 }, // divsd
188 { ISD::FDIV, MVT::v2f64, 65 }, // divpd
189 };
190
191 if (ST->isGLM())
192 if (const auto *Entry = CostTableLookup(GLMCostTable, ISD,
193 LT.second))
194 return LT.first * Entry->Cost;
195
196 static const CostTblEntry SLMCostTable[] = {
197 { ISD::MUL, MVT::v4i32, 11 }, // pmulld
198 { ISD::MUL, MVT::v8i16, 2 }, // pmullw
199 { ISD::MUL, MVT::v16i8, 14 }, // extend/pmullw/trunc sequence.
200 { ISD::FMUL, MVT::f64, 2 }, // mulsd
201 { ISD::FMUL, MVT::v2f64, 4 }, // mulpd
202 { ISD::FMUL, MVT::v4f32, 2 }, // mulps
203 { ISD::FDIV, MVT::f32, 17 }, // divss
204 { ISD::FDIV, MVT::v4f32, 39 }, // divps
205 { ISD::FDIV, MVT::f64, 32 }, // divsd
206 { ISD::FDIV, MVT::v2f64, 69 }, // divpd
207 { ISD::FADD, MVT::v2f64, 2 }, // addpd
208 { ISD::FSUB, MVT::v2f64, 2 }, // subpd
209 // v2i64/v4i64 mul is custom lowered as a series of long:
210 // multiplies(3), shifts(3) and adds(2)
211 // slm muldq version throughput is 2 and addq throughput 4
212 // thus: 3X2 (muldq throughput) + 3X1 (shift throughput) +
213 // 3X4 (addq throughput) = 17
214 { ISD::MUL, MVT::v2i64, 17 },
215 // slm addq\subq throughput is 4
216 { ISD::ADD, MVT::v2i64, 4 },
217 { ISD::SUB, MVT::v2i64, 4 },
218 };
219
220 if (ST->isSLM()) {
221 if (Args.size() == 2 && ISD == ISD::MUL && LT.second == MVT::v4i32) {
222 // Check if the operands can be shrinked into a smaller datatype.
223 bool Op1Signed = false;
224 unsigned Op1MinSize = BaseT::minRequiredElementSize(Args[0], Op1Signed);
225 bool Op2Signed = false;
226 unsigned Op2MinSize = BaseT::minRequiredElementSize(Args[1], Op2Signed);
227
228 bool signedMode = Op1Signed | Op2Signed;
229 unsigned OpMinSize = std::max(Op1MinSize, Op2MinSize);
230
231 if (OpMinSize <= 7)
232 return LT.first * 3; // pmullw/sext
233 if (!signedMode && OpMinSize <= 8)
234 return LT.first * 3; // pmullw/zext
235 if (OpMinSize <= 15)
236 return LT.first * 5; // pmullw/pmulhw/pshuf
237 if (!signedMode && OpMinSize <= 16)
238 return LT.first * 5; // pmullw/pmulhw/pshuf
239 }
240
241 if (const auto *Entry = CostTableLookup(SLMCostTable, ISD,
242 LT.second)) {
243 return LT.first * Entry->Cost;
244 }
245 }
246
247 if ((ISD == ISD::SDIV || ISD == ISD::SREM || ISD == ISD::UDIV ||
248 ISD == ISD::UREM) &&
249 (Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
250 Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) &&
251 Opd2PropInfo == TargetTransformInfo::OP_PowerOf2) {
252 if (ISD == ISD::SDIV || ISD == ISD::SREM) {
253 // On X86, vector signed division by constants power-of-two are
254 // normally expanded to the sequence SRA + SRL + ADD + SRA.
255 // The OperandValue properties may not be the same as that of the previous
256 // operation; conservatively assume OP_None.
257 int Cost =
258 2 * getArithmeticInstrCost(Instruction::AShr, Ty, Op1Info, Op2Info,
259 TargetTransformInfo::OP_None,
260 TargetTransformInfo::OP_None);
261 Cost += getArithmeticInstrCost(Instruction::LShr, Ty, Op1Info, Op2Info,
262 TargetTransformInfo::OP_None,
263 TargetTransformInfo::OP_None);
264 Cost += getArithmeticInstrCost(Instruction::Add, Ty, Op1Info, Op2Info,
265 TargetTransformInfo::OP_None,
266 TargetTransformInfo::OP_None);
267
268 if (ISD == ISD::SREM) {
269 // For SREM: (X % C) is the equivalent of (X - (X/C)*C)
270 Cost += getArithmeticInstrCost(Instruction::Mul, Ty, Op1Info, Op2Info);
271 Cost += getArithmeticInstrCost(Instruction::Sub, Ty, Op1Info, Op2Info);
272 }
273
274 return Cost;
275 }
276
277 // Vector unsigned division/remainder will be simplified to shifts/masks.
278 if (ISD == ISD::UDIV)
279 return getArithmeticInstrCost(Instruction::LShr, Ty, Op1Info, Op2Info,
280 TargetTransformInfo::OP_None,
281 TargetTransformInfo::OP_None);
282
283 else // UREM
284 return getArithmeticInstrCost(Instruction::And, Ty, Op1Info, Op2Info,
285 TargetTransformInfo::OP_None,
286 TargetTransformInfo::OP_None);
287 }
288
289 static const CostTblEntry AVX512BWUniformConstCostTable[] = {
290 { ISD::SHL, MVT::v64i8, 2 }, // psllw + pand.
291 { ISD::SRL, MVT::v64i8, 2 }, // psrlw + pand.
292 { ISD::SRA, MVT::v64i8, 4 }, // psrlw, pand, pxor, psubb.
293 };
294
295 if (Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
296 ST->hasBWI()) {
297 if (const auto *Entry = CostTableLookup(AVX512BWUniformConstCostTable, ISD,
298 LT.second))
299 return LT.first * Entry->Cost;
300 }
301
302 static const CostTblEntry AVX512UniformConstCostTable[] = {
303 { ISD::SRA, MVT::v2i64, 1 },
304 { ISD::SRA, MVT::v4i64, 1 },
305 { ISD::SRA, MVT::v8i64, 1 },
306 };
307
308 if (Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
309 ST->hasAVX512()) {
310 if (const auto *Entry = CostTableLookup(AVX512UniformConstCostTable, ISD,
311 LT.second))
312 return LT.first * Entry->Cost;
313 }
314
315 static const CostTblEntry AVX2UniformConstCostTable[] = {
316 { ISD::SHL, MVT::v32i8, 2 }, // psllw + pand.
317 { ISD::SRL, MVT::v32i8, 2 }, // psrlw + pand.
318 { ISD::SRA, MVT::v32i8, 4 }, // psrlw, pand, pxor, psubb.
319
320 { ISD::SRA, MVT::v4i64, 4 }, // 2 x psrad + shuffle.
321 };
322
323 if (Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
324 ST->hasAVX2()) {
325 if (const auto *Entry = CostTableLookup(AVX2UniformConstCostTable, ISD,
326 LT.second))
327 return LT.first * Entry->Cost;
328 }
329
330 static const CostTblEntry SSE2UniformConstCostTable[] = {
331 { ISD::SHL, MVT::v16i8, 2 }, // psllw + pand.
332 { ISD::SRL, MVT::v16i8, 2 }, // psrlw + pand.
333 { ISD::SRA, MVT::v16i8, 4 }, // psrlw, pand, pxor, psubb.
334
335 { ISD::SHL, MVT::v32i8, 4+2 }, // 2*(psllw + pand) + split.
336 { ISD::SRL, MVT::v32i8, 4+2 }, // 2*(psrlw + pand) + split.
337 { ISD::SRA, MVT::v32i8, 8+2 }, // 2*(psrlw, pand, pxor, psubb) + split.
338 };
339
340 // XOP has faster vXi8 shifts.
341 if (Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
342 ST->hasSSE2() && !ST->hasXOP()) {
343 if (const auto *Entry =
344 CostTableLookup(SSE2UniformConstCostTable, ISD, LT.second))
345 return LT.first * Entry->Cost;
346 }
347
348 static const CostTblEntry AVX512BWConstCostTable[] = {
349 { ISD::SDIV, MVT::v64i8, 14 }, // 2*ext+2*pmulhw sequence
350 { ISD::SREM, MVT::v64i8, 16 }, // 2*ext+2*pmulhw+mul+sub sequence
351 { ISD::UDIV, MVT::v64i8, 14 }, // 2*ext+2*pmulhw sequence
352 { ISD::UREM, MVT::v64i8, 16 }, // 2*ext+2*pmulhw+mul+sub sequence
353 { ISD::SDIV, MVT::v32i16, 6 }, // vpmulhw sequence
354 { ISD::SREM, MVT::v32i16, 8 }, // vpmulhw+mul+sub sequence
355 { ISD::UDIV, MVT::v32i16, 6 }, // vpmulhuw sequence
356 { ISD::UREM, MVT::v32i16, 8 }, // vpmulhuw+mul+sub sequence
357 };
358
359 if ((Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
360 Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) &&
361 ST->hasBWI()) {
362 if (const auto *Entry =
363 CostTableLookup(AVX512BWConstCostTable, ISD, LT.second))
364 return LT.first * Entry->Cost;
365 }
366
367 static const CostTblEntry AVX512ConstCostTable[] = {
368 { ISD::SDIV, MVT::v16i32, 15 }, // vpmuldq sequence
369 { ISD::SREM, MVT::v16i32, 17 }, // vpmuldq+mul+sub sequence
370 { ISD::UDIV, MVT::v16i32, 15 }, // vpmuludq sequence
371 { ISD::UREM, MVT::v16i32, 17 }, // vpmuludq+mul+sub sequence
372 };
373
374 if ((Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
375 Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) &&
376 ST->hasAVX512()) {
377 if (const auto *Entry =
378 CostTableLookup(AVX512ConstCostTable, ISD, LT.second))
379 return LT.first * Entry->Cost;
380 }
381
382 static const CostTblEntry AVX2ConstCostTable[] = {
383 { ISD::SDIV, MVT::v32i8, 14 }, // 2*ext+2*pmulhw sequence
384 { ISD::SREM, MVT::v32i8, 16 }, // 2*ext+2*pmulhw+mul+sub sequence
385 { ISD::UDIV, MVT::v32i8, 14 }, // 2*ext+2*pmulhw sequence
386 { ISD::UREM, MVT::v32i8, 16 }, // 2*ext+2*pmulhw+mul+sub sequence
387 { ISD::SDIV, MVT::v16i16, 6 }, // vpmulhw sequence
388 { ISD::SREM, MVT::v16i16, 8 }, // vpmulhw+mul+sub sequence
389 { ISD::UDIV, MVT::v16i16, 6 }, // vpmulhuw sequence
390 { ISD::UREM, MVT::v16i16, 8 }, // vpmulhuw+mul+sub sequence
391 { ISD::SDIV, MVT::v8i32, 15 }, // vpmuldq sequence
392 { ISD::SREM, MVT::v8i32, 19 }, // vpmuldq+mul+sub sequence
393 { ISD::UDIV, MVT::v8i32, 15 }, // vpmuludq sequence
394 { ISD::UREM, MVT::v8i32, 19 }, // vpmuludq+mul+sub sequence
395 };
396
397 if ((Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
398 Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) &&
399 ST->hasAVX2()) {
400 if (const auto *Entry = CostTableLookup(AVX2ConstCostTable, ISD, LT.second))
401 return LT.first * Entry->Cost;
402 }
403
404 static const CostTblEntry SSE2ConstCostTable[] = {
405 { ISD::SDIV, MVT::v32i8, 28+2 }, // 4*ext+4*pmulhw sequence + split.
406 { ISD::SREM, MVT::v32i8, 32+2 }, // 4*ext+4*pmulhw+mul+sub sequence + split.
407 { ISD::SDIV, MVT::v16i8, 14 }, // 2*ext+2*pmulhw sequence
408 { ISD::SREM, MVT::v16i8, 16 }, // 2*ext+2*pmulhw+mul+sub sequence
409 { ISD::UDIV, MVT::v32i8, 28+2 }, // 4*ext+4*pmulhw sequence + split.
410 { ISD::UREM, MVT::v32i8, 32+2 }, // 4*ext+4*pmulhw+mul+sub sequence + split.
411 { ISD::UDIV, MVT::v16i8, 14 }, // 2*ext+2*pmulhw sequence
412 { ISD::UREM, MVT::v16i8, 16 }, // 2*ext+2*pmulhw+mul+sub sequence
413 { ISD::SDIV, MVT::v16i16, 12+2 }, // 2*pmulhw sequence + split.
414 { ISD::SREM, MVT::v16i16, 16+2 }, // 2*pmulhw+mul+sub sequence + split.
415 { ISD::SDIV, MVT::v8i16, 6 }, // pmulhw sequence
416 { ISD::SREM, MVT::v8i16, 8 }, // pmulhw+mul+sub sequence
417 { ISD::UDIV, MVT::v16i16, 12+2 }, // 2*pmulhuw sequence + split.
418 { ISD::UREM, MVT::v16i16, 16+2 }, // 2*pmulhuw+mul+sub sequence + split.
419 { ISD::UDIV, MVT::v8i16, 6 }, // pmulhuw sequence
420 { ISD::UREM, MVT::v8i16, 8 }, // pmulhuw+mul+sub sequence
421 { ISD::SDIV, MVT::v8i32, 38+2 }, // 2*pmuludq sequence + split.
422 { ISD::SREM, MVT::v8i32, 48+2 }, // 2*pmuludq+mul+sub sequence + split.
423 { ISD::SDIV, MVT::v4i32, 19 }, // pmuludq sequence
424 { ISD::SREM, MVT::v4i32, 24 }, // pmuludq+mul+sub sequence
425 { ISD::UDIV, MVT::v8i32, 30+2 }, // 2*pmuludq sequence + split.
426 { ISD::UREM, MVT::v8i32, 40+2 }, // 2*pmuludq+mul+sub sequence + split.
427 { ISD::UDIV, MVT::v4i32, 15 }, // pmuludq sequence
428 { ISD::UREM, MVT::v4i32, 20 }, // pmuludq+mul+sub sequence
429 };
430
431 if ((Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
432 Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) &&
433 ST->hasSSE2()) {
434 // pmuldq sequence.
435 if (ISD == ISD::SDIV && LT.second == MVT::v8i32 && ST->hasAVX())
436 return LT.first * 32;
437 if (ISD == ISD::SREM && LT.second == MVT::v8i32 && ST->hasAVX())
438 return LT.first * 38;
439 if (ISD == ISD::SDIV && LT.second == MVT::v4i32 && ST->hasSSE41())
440 return LT.first * 15;
441 if (ISD == ISD::SREM && LT.second == MVT::v4i32 && ST->hasSSE41())
442 return LT.first * 20;
443
444 if (const auto *Entry = CostTableLookup(SSE2ConstCostTable, ISD, LT.second))
445 return LT.first * Entry->Cost;
446 }
447
448 static const CostTblEntry AVX2UniformCostTable[] = {
449 // Uniform splats are cheaper for the following instructions.
450 { ISD::SHL, MVT::v16i16, 1 }, // psllw.
451 { ISD::SRL, MVT::v16i16, 1 }, // psrlw.
452 { ISD::SRA, MVT::v16i16, 1 }, // psraw.
453 };
454
455 if (ST->hasAVX2() &&
456 ((Op2Info == TargetTransformInfo::OK_UniformConstantValue) ||
457 (Op2Info == TargetTransformInfo::OK_UniformValue))) {
458 if (const auto *Entry =
459 CostTableLookup(AVX2UniformCostTable, ISD, LT.second))
460 return LT.first * Entry->Cost;
461 }
462
463 static const CostTblEntry SSE2UniformCostTable[] = {
464 // Uniform splats are cheaper for the following instructions.
465 { ISD::SHL, MVT::v8i16, 1 }, // psllw.
466 { ISD::SHL, MVT::v4i32, 1 }, // pslld
467 { ISD::SHL, MVT::v2i64, 1 }, // psllq.
468
469 { ISD::SRL, MVT::v8i16, 1 }, // psrlw.
470 { ISD::SRL, MVT::v4i32, 1 }, // psrld.
471 { ISD::SRL, MVT::v2i64, 1 }, // psrlq.
472
473 { ISD::SRA, MVT::v8i16, 1 }, // psraw.
474 { ISD::SRA, MVT::v4i32, 1 }, // psrad.
475 };
476
477 if (ST->hasSSE2() &&
478 ((Op2Info == TargetTransformInfo::OK_UniformConstantValue) ||
479 (Op2Info == TargetTransformInfo::OK_UniformValue))) {
480 if (const auto *Entry =
481 CostTableLookup(SSE2UniformCostTable, ISD, LT.second))
482 return LT.first * Entry->Cost;
483 }
484
485 static const CostTblEntry AVX512DQCostTable[] = {
486 { ISD::MUL, MVT::v2i64, 1 },
487 { ISD::MUL, MVT::v4i64, 1 },
488 { ISD::MUL, MVT::v8i64, 1 }
489 };
490
491 // Look for AVX512DQ lowering tricks for custom cases.
492 if (ST->hasDQI())
493 if (const auto *Entry = CostTableLookup(AVX512DQCostTable, ISD, LT.second))
494 return LT.first * Entry->Cost;
495
496 static const CostTblEntry AVX512BWCostTable[] = {
497 { ISD::SHL, MVT::v8i16, 1 }, // vpsllvw
498 { ISD::SRL, MVT::v8i16, 1 }, // vpsrlvw
499 { ISD::SRA, MVT::v8i16, 1 }, // vpsravw
500
501 { ISD::SHL, MVT::v16i16, 1 }, // vpsllvw
502 { ISD::SRL, MVT::v16i16, 1 }, // vpsrlvw
503 { ISD::SRA, MVT::v16i16, 1 }, // vpsravw
504
505 { ISD::SHL, MVT::v32i16, 1 }, // vpsllvw
506 { ISD::SRL, MVT::v32i16, 1 }, // vpsrlvw
507 { ISD::SRA, MVT::v32i16, 1 }, // vpsravw
508
509 { ISD::SHL, MVT::v64i8, 11 }, // vpblendvb sequence.
510 { ISD::SRL, MVT::v64i8, 11 }, // vpblendvb sequence.
511 { ISD::SRA, MVT::v64i8, 24 }, // vpblendvb sequence.
512
513 { ISD::MUL, MVT::v64i8, 11 }, // extend/pmullw/trunc sequence.
514 { ISD::MUL, MVT::v32i8, 4 }, // extend/pmullw/trunc sequence.
515 { ISD::MUL, MVT::v16i8, 4 }, // extend/pmullw/trunc sequence.
516 };
517
518 // Look for AVX512BW lowering tricks for custom cases.
519 if (ST->hasBWI())
520 if (const auto *Entry = CostTableLookup(AVX512BWCostTable, ISD, LT.second))
521 return LT.first * Entry->Cost;
522
523 static const CostTblEntry AVX512CostTable[] = {
524 { ISD::SHL, MVT::v16i32, 1 },
525 { ISD::SRL, MVT::v16i32, 1 },
526 { ISD::SRA, MVT::v16i32, 1 },
527
528 { ISD::SHL, MVT::v8i64, 1 },
529 { ISD::SRL, MVT::v8i64, 1 },
530
531 { ISD::SRA, MVT::v2i64, 1 },
532 { ISD::SRA, MVT::v4i64, 1 },
533 { ISD::SRA, MVT::v8i64, 1 },
534
535 { ISD::MUL, MVT::v32i8, 13 }, // extend/pmullw/trunc sequence.
536 { ISD::MUL, MVT::v16i8, 5 }, // extend/pmullw/trunc sequence.
537 { ISD::MUL, MVT::v16i32, 1 }, // pmulld (Skylake from agner.org)
538 { ISD::MUL, MVT::v8i32, 1 }, // pmulld (Skylake from agner.org)
539 { ISD::MUL, MVT::v4i32, 1 }, // pmulld (Skylake from agner.org)
540 { ISD::MUL, MVT::v8i64, 8 }, // 3*pmuludq/3*shift/2*add
541
542 { ISD::FADD, MVT::v8f64, 1 }, // Skylake from http://www.agner.org/
543 { ISD::FSUB, MVT::v8f64, 1 }, // Skylake from http://www.agner.org/
544 { ISD::FMUL, MVT::v8f64, 1 }, // Skylake from http://www.agner.org/
545
546 { ISD::FADD, MVT::v16f32, 1 }, // Skylake from http://www.agner.org/
547 { ISD::FSUB, MVT::v16f32, 1 }, // Skylake from http://www.agner.org/
548 { ISD::FMUL, MVT::v16f32, 1 }, // Skylake from http://www.agner.org/
549 };
550
551 if (ST->hasAVX512())
552 if (const auto *Entry = CostTableLookup(AVX512CostTable, ISD, LT.second))
553 return LT.first * Entry->Cost;
554
555 static const CostTblEntry AVX2ShiftCostTable[] = {
556 // Shifts on v4i64/v8i32 on AVX2 is legal even though we declare to
557 // customize them to detect the cases where shift amount is a scalar one.
558 { ISD::SHL, MVT::v4i32, 1 },
559 { ISD::SRL, MVT::v4i32, 1 },
560 { ISD::SRA, MVT::v4i32, 1 },
561 { ISD::SHL, MVT::v8i32, 1 },
562 { ISD::SRL, MVT::v8i32, 1 },
563 { ISD::SRA, MVT::v8i32, 1 },
564 { ISD::SHL, MVT::v2i64, 1 },
565 { ISD::SRL, MVT::v2i64, 1 },
566 { ISD::SHL, MVT::v4i64, 1 },
567 { ISD::SRL, MVT::v4i64, 1 },
568 };
569
570 // Look for AVX2 lowering tricks.
571 if (ST->hasAVX2()) {
572 if (ISD == ISD::SHL && LT.second == MVT::v16i16 &&
573 (Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
574 Op2Info == TargetTransformInfo::OK_NonUniformConstantValue))
575 // On AVX2, a packed v16i16 shift left by a constant build_vector
576 // is lowered into a vector multiply (vpmullw).
577 return getArithmeticInstrCost(Instruction::Mul, Ty, Op1Info, Op2Info,
578 TargetTransformInfo::OP_None,
579 TargetTransformInfo::OP_None);
580
581 if (const auto *Entry = CostTableLookup(AVX2ShiftCostTable, ISD, LT.second))
582 return LT.first * Entry->Cost;
583 }
584
585 static const CostTblEntry XOPShiftCostTable[] = {
586 // 128bit shifts take 1cy, but right shifts require negation beforehand.
587 { ISD::SHL, MVT::v16i8, 1 },
588 { ISD::SRL, MVT::v16i8, 2 },
589 { ISD::SRA, MVT::v16i8, 2 },
590 { ISD::SHL, MVT::v8i16, 1 },
591 { ISD::SRL, MVT::v8i16, 2 },
592 { ISD::SRA, MVT::v8i16, 2 },
593 { ISD::SHL, MVT::v4i32, 1 },
594 { ISD::SRL, MVT::v4i32, 2 },
595 { ISD::SRA, MVT::v4i32, 2 },
596 { ISD::SHL, MVT::v2i64, 1 },
597 { ISD::SRL, MVT::v2i64, 2 },
598 { ISD::SRA, MVT::v2i64, 2 },
599 // 256bit shifts require splitting if AVX2 didn't catch them above.
600 { ISD::SHL, MVT::v32i8, 2+2 },
601 { ISD::SRL, MVT::v32i8, 4+2 },
602 { ISD::SRA, MVT::v32i8, 4+2 },
603 { ISD::SHL, MVT::v16i16, 2+2 },
604 { ISD::SRL, MVT::v16i16, 4+2 },
605 { ISD::SRA, MVT::v16i16, 4+2 },
606 { ISD::SHL, MVT::v8i32, 2+2 },
607 { ISD::SRL, MVT::v8i32, 4+2 },
608 { ISD::SRA, MVT::v8i32, 4+2 },
609 { ISD::SHL, MVT::v4i64, 2+2 },
610 { ISD::SRL, MVT::v4i64, 4+2 },
611 { ISD::SRA, MVT::v4i64, 4+2 },
612 };
613
614 // Look for XOP lowering tricks.
615 if (ST->hasXOP()) {
616 // If the right shift is constant then we'll fold the negation so
617 // it's as cheap as a left shift.
618 int ShiftISD = ISD;
619 if ((ShiftISD == ISD::SRL || ShiftISD == ISD::SRA) &&
620 (Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
621 Op2Info == TargetTransformInfo::OK_NonUniformConstantValue))
622 ShiftISD = ISD::SHL;
623 if (const auto *Entry =
624 CostTableLookup(XOPShiftCostTable, ShiftISD, LT.second))
625 return LT.first * Entry->Cost;
626 }
627
628 static const CostTblEntry SSE2UniformShiftCostTable[] = {
629 // Uniform splats are cheaper for the following instructions.
630 { ISD::SHL, MVT::v16i16, 2+2 }, // 2*psllw + split.
631 { ISD::SHL, MVT::v8i32, 2+2 }, // 2*pslld + split.
632 { ISD::SHL, MVT::v4i64, 2+2 }, // 2*psllq + split.
633
634 { ISD::SRL, MVT::v16i16, 2+2 }, // 2*psrlw + split.
635 { ISD::SRL, MVT::v8i32, 2+2 }, // 2*psrld + split.
636 { ISD::SRL, MVT::v4i64, 2+2 }, // 2*psrlq + split.
637
638 { ISD::SRA, MVT::v16i16, 2+2 }, // 2*psraw + split.
639 { ISD::SRA, MVT::v8i32, 2+2 }, // 2*psrad + split.
640 { ISD::SRA, MVT::v2i64, 4 }, // 2*psrad + shuffle.
641 { ISD::SRA, MVT::v4i64, 8+2 }, // 2*(2*psrad + shuffle) + split.
642 };
643
644 if (ST->hasSSE2() &&
645 ((Op2Info == TargetTransformInfo::OK_UniformConstantValue) ||
646 (Op2Info == TargetTransformInfo::OK_UniformValue))) {
647
648 // Handle AVX2 uniform v4i64 ISD::SRA, it's not worth a table.
649 if (ISD == ISD::SRA && LT.second == MVT::v4i64 && ST->hasAVX2())
650 return LT.first * 4; // 2*psrad + shuffle.
651
652 if (const auto *Entry =
653 CostTableLookup(SSE2UniformShiftCostTable, ISD, LT.second))
654 return LT.first * Entry->Cost;
655 }
656
657 if (ISD == ISD::SHL &&
658 Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) {
659 MVT VT = LT.second;
660 // Vector shift left by non uniform constant can be lowered
661 // into vector multiply.
662 if (((VT == MVT::v8i16 || VT == MVT::v4i32) && ST->hasSSE2()) ||
663 ((VT == MVT::v16i16 || VT == MVT::v8i32) && ST->hasAVX()))
664 ISD = ISD::MUL;
665 }
666
667 static const CostTblEntry AVX2CostTable[] = {
668 { ISD::SHL, MVT::v32i8, 11 }, // vpblendvb sequence.
669 { ISD::SHL, MVT::v16i16, 10 }, // extend/vpsrlvd/pack sequence.
670
671 { ISD::SRL, MVT::v32i8, 11 }, // vpblendvb sequence.
672 { ISD::SRL, MVT::v16i16, 10 }, // extend/vpsrlvd/pack sequence.
673
674 { ISD::SRA, MVT::v32i8, 24 }, // vpblendvb sequence.
675 { ISD::SRA, MVT::v16i16, 10 }, // extend/vpsravd/pack sequence.
676 { ISD::SRA, MVT::v2i64, 4 }, // srl/xor/sub sequence.
677 { ISD::SRA, MVT::v4i64, 4 }, // srl/xor/sub sequence.
678
679 { ISD::SUB, MVT::v32i8, 1 }, // psubb
680 { ISD::ADD, MVT::v32i8, 1 }, // paddb
681 { ISD::SUB, MVT::v16i16, 1 }, // psubw
682 { ISD::ADD, MVT::v16i16, 1 }, // paddw
683 { ISD::SUB, MVT::v8i32, 1 }, // psubd
684 { ISD::ADD, MVT::v8i32, 1 }, // paddd
685 { ISD::SUB, MVT::v4i64, 1 }, // psubq
686 { ISD::ADD, MVT::v4i64, 1 }, // paddq
687
688 { ISD::MUL, MVT::v32i8, 17 }, // extend/pmullw/trunc sequence.
689 { ISD::MUL, MVT::v16i8, 7 }, // extend/pmullw/trunc sequence.
690 { ISD::MUL, MVT::v16i16, 1 }, // pmullw
691 { ISD::MUL, MVT::v8i32, 2 }, // pmulld (Haswell from agner.org)
692 { ISD::MUL, MVT::v4i64, 8 }, // 3*pmuludq/3*shift/2*add
693
694 { ISD::FADD, MVT::v4f64, 1 }, // Haswell from http://www.agner.org/
695 { ISD::FADD, MVT::v8f32, 1 }, // Haswell from http://www.agner.org/
696 { ISD::FSUB, MVT::v4f64, 1 }, // Haswell from http://www.agner.org/
697 { ISD::FSUB, MVT::v8f32, 1 }, // Haswell from http://www.agner.org/
698 { ISD::FMUL, MVT::v4f64, 1 }, // Haswell from http://www.agner.org/
699 { ISD::FMUL, MVT::v8f32, 1 }, // Haswell from http://www.agner.org/
700
701 { ISD::FDIV, MVT::f32, 7 }, // Haswell from http://www.agner.org/
702 { ISD::FDIV, MVT::v4f32, 7 }, // Haswell from http://www.agner.org/
703 { ISD::FDIV, MVT::v8f32, 14 }, // Haswell from http://www.agner.org/
704 { ISD::FDIV, MVT::f64, 14 }, // Haswell from http://www.agner.org/
705 { ISD::FDIV, MVT::v2f64, 14 }, // Haswell from http://www.agner.org/
706 { ISD::FDIV, MVT::v4f64, 28 }, // Haswell from http://www.agner.org/
707 };
708
709 // Look for AVX2 lowering tricks for custom cases.
710 if (ST->hasAVX2())
711 if (const auto *Entry = CostTableLookup(AVX2CostTable, ISD, LT.second))
712 return LT.first * Entry->Cost;
713
714 static const CostTblEntry AVX1CostTable[] = {
715 // We don't have to scalarize unsupported ops. We can issue two half-sized
716 // operations and we only need to extract the upper YMM half.
717 // Two ops + 1 extract + 1 insert = 4.
718 { ISD::MUL, MVT::v16i16, 4 },
719 { ISD::MUL, MVT::v8i32, 4 },
720 { ISD::SUB, MVT::v32i8, 4 },
721 { ISD::ADD, MVT::v32i8, 4 },
722 { ISD::SUB, MVT::v16i16, 4 },
723 { ISD::ADD, MVT::v16i16, 4 },
724 { ISD::SUB, MVT::v8i32, 4 },
725 { ISD::ADD, MVT::v8i32, 4 },
726 { ISD::SUB, MVT::v4i64, 4 },
727 { ISD::ADD, MVT::v4i64, 4 },
728
729 // A v4i64 multiply is custom lowered as two split v2i64 vectors that then
730 // are lowered as a series of long multiplies(3), shifts(3) and adds(2)
731 // Because we believe v4i64 to be a legal type, we must also include the
732 // extract+insert in the cost table. Therefore, the cost here is 18
733 // instead of 8.
734 { ISD::MUL, MVT::v4i64, 18 },
735
736 { ISD::MUL, MVT::v32i8, 26 }, // extend/pmullw/trunc sequence.
737
738 { ISD::FDIV, MVT::f32, 14 }, // SNB from http://www.agner.org/
739 { ISD::FDIV, MVT::v4f32, 14 }, // SNB from http://www.agner.org/
740 { ISD::FDIV, MVT::v8f32, 28 }, // SNB from http://www.agner.org/
741 { ISD::FDIV, MVT::f64, 22 }, // SNB from http://www.agner.org/
742 { ISD::FDIV, MVT::v2f64, 22 }, // SNB from http://www.agner.org/
743 { ISD::FDIV, MVT::v4f64, 44 }, // SNB from http://www.agner.org/
744 };
745
746 if (ST->hasAVX())
747 if (const auto *Entry = CostTableLookup(AVX1CostTable, ISD, LT.second))
748 return LT.first * Entry->Cost;
749
750 static const CostTblEntry SSE42CostTable[] = {
751 { ISD::FADD, MVT::f64, 1 }, // Nehalem from http://www.agner.org/
752 { ISD::FADD, MVT::f32, 1 }, // Nehalem from http://www.agner.org/
753 { ISD::FADD, MVT::v2f64, 1 }, // Nehalem from http://www.agner.org/
754 { ISD::FADD, MVT::v4f32, 1 }, // Nehalem from http://www.agner.org/
755
756 { ISD::FSUB, MVT::f64, 1 }, // Nehalem from http://www.agner.org/
757 { ISD::FSUB, MVT::f32 , 1 }, // Nehalem from http://www.agner.org/
758 { ISD::FSUB, MVT::v2f64, 1 }, // Nehalem from http://www.agner.org/
759 { ISD::FSUB, MVT::v4f32, 1 }, // Nehalem from http://www.agner.org/
760
761 { ISD::FMUL, MVT::f64, 1 }, // Nehalem from http://www.agner.org/
762 { ISD::FMUL, MVT::f32, 1 }, // Nehalem from http://www.agner.org/
763 { ISD::FMUL, MVT::v2f64, 1 }, // Nehalem from http://www.agner.org/
764 { ISD::FMUL, MVT::v4f32, 1 }, // Nehalem from http://www.agner.org/
765
766 { ISD::FDIV, MVT::f32, 14 }, // Nehalem from http://www.agner.org/
767 { ISD::FDIV, MVT::v4f32, 14 }, // Nehalem from http://www.agner.org/
768 { ISD::FDIV, MVT::f64, 22 }, // Nehalem from http://www.agner.org/
769 { ISD::FDIV, MVT::v2f64, 22 }, // Nehalem from http://www.agner.org/
770 };
771
772 if (ST->hasSSE42())
773 if (const auto *Entry = CostTableLookup(SSE42CostTable, ISD, LT.second))
774 return LT.first * Entry->Cost;
775
776 static const CostTblEntry SSE41CostTable[] = {
777 { ISD::SHL, MVT::v16i8, 11 }, // pblendvb sequence.
778 { ISD::SHL, MVT::v32i8, 2*11+2 }, // pblendvb sequence + split.
779 { ISD::SHL, MVT::v8i16, 14 }, // pblendvb sequence.
780 { ISD::SHL, MVT::v16i16, 2*14+2 }, // pblendvb sequence + split.
781 { ISD::SHL, MVT::v4i32, 4 }, // pslld/paddd/cvttps2dq/pmulld
782 { ISD::SHL, MVT::v8i32, 2*4+2 }, // pslld/paddd/cvttps2dq/pmulld + split
783
784 { ISD::SRL, MVT::v16i8, 12 }, // pblendvb sequence.
785 { ISD::SRL, MVT::v32i8, 2*12+2 }, // pblendvb sequence + split.
786 { ISD::SRL, MVT::v8i16, 14 }, // pblendvb sequence.
787 { ISD::SRL, MVT::v16i16, 2*14+2 }, // pblendvb sequence + split.
788 { ISD::SRL, MVT::v4i32, 11 }, // Shift each lane + blend.
789 { ISD::SRL, MVT::v8i32, 2*11+2 }, // Shift each lane + blend + split.
790
791 { ISD::SRA, MVT::v16i8, 24 }, // pblendvb sequence.
792 { ISD::SRA, MVT::v32i8, 2*24+2 }, // pblendvb sequence + split.
793 { ISD::SRA, MVT::v8i16, 14 }, // pblendvb sequence.
794 { ISD::SRA, MVT::v16i16, 2*14+2 }, // pblendvb sequence + split.
795 { ISD::SRA, MVT::v4i32, 12 }, // Shift each lane + blend.
796 { ISD::SRA, MVT::v8i32, 2*12+2 }, // Shift each lane + blend + split.
797
798 { ISD::MUL, MVT::v4i32, 2 } // pmulld (Nehalem from agner.org)
799 };
800
801 if (ST->hasSSE41())
802 if (const auto *Entry = CostTableLookup(SSE41CostTable, ISD, LT.second))
803 return LT.first * Entry->Cost;
804
805 static const CostTblEntry SSE2CostTable[] = {
806 // We don't correctly identify costs of casts because they are marked as
807 // custom.
808 { ISD::SHL, MVT::v16i8, 26 }, // cmpgtb sequence.
809 { ISD::SHL, MVT::v8i16, 32 }, // cmpgtb sequence.
810 { ISD::SHL, MVT::v4i32, 2*5 }, // We optimized this using mul.
811 { ISD::SHL, MVT::v2i64, 4 }, // splat+shuffle sequence.
812 { ISD::SHL, MVT::v4i64, 2*4+2 }, // splat+shuffle sequence + split.
813
814 { ISD::SRL, MVT::v16i8, 26 }, // cmpgtb sequence.
815 { ISD::SRL, MVT::v8i16, 32 }, // cmpgtb sequence.
816 { ISD::SRL, MVT::v4i32, 16 }, // Shift each lane + blend.
817 { ISD::SRL, MVT::v2i64, 4 }, // splat+shuffle sequence.
818 { ISD::SRL, MVT::v4i64, 2*4+2 }, // splat+shuffle sequence + split.
819
820 { ISD::SRA, MVT::v16i8, 54 }, // unpacked cmpgtb sequence.
821 { ISD::SRA, MVT::v8i16, 32 }, // cmpgtb sequence.
822 { ISD::SRA, MVT::v4i32, 16 }, // Shift each lane + blend.
823 { ISD::SRA, MVT::v2i64, 12 }, // srl/xor/sub sequence.
824 { ISD::SRA, MVT::v4i64, 2*12+2 }, // srl/xor/sub sequence+split.
825
826 { ISD::MUL, MVT::v16i8, 12 }, // extend/pmullw/trunc sequence.
827 { ISD::MUL, MVT::v8i16, 1 }, // pmullw
828 { ISD::MUL, MVT::v4i32, 6 }, // 3*pmuludq/4*shuffle
829 { ISD::MUL, MVT::v2i64, 8 }, // 3*pmuludq/3*shift/2*add
830
831 { ISD::FDIV, MVT::f32, 23 }, // Pentium IV from http://www.agner.org/
832 { ISD::FDIV, MVT::v4f32, 39 }, // Pentium IV from http://www.agner.org/
833 { ISD::FDIV, MVT::f64, 38 }, // Pentium IV from http://www.agner.org/
834 { ISD::FDIV, MVT::v2f64, 69 }, // Pentium IV from http://www.agner.org/
835
836 { ISD::FADD, MVT::f32, 2 }, // Pentium IV from http://www.agner.org/
837 { ISD::FADD, MVT::f64, 2 }, // Pentium IV from http://www.agner.org/
838
839 { ISD::FSUB, MVT::f32, 2 }, // Pentium IV from http://www.agner.org/
840 { ISD::FSUB, MVT::f64, 2 }, // Pentium IV from http://www.agner.org/
841 };
842
843 if (ST->hasSSE2())
844 if (const auto *Entry = CostTableLookup(SSE2CostTable, ISD, LT.second))
845 return LT.first * Entry->Cost;
846
847 static const CostTblEntry SSE1CostTable[] = {
848 { ISD::FDIV, MVT::f32, 17 }, // Pentium III from http://www.agner.org/
849 { ISD::FDIV, MVT::v4f32, 34 }, // Pentium III from http://www.agner.org/
850
851 { ISD::FADD, MVT::f32, 1 }, // Pentium III from http://www.agner.org/
852 { ISD::FADD, MVT::v4f32, 2 }, // Pentium III from http://www.agner.org/
853
854 { ISD::FSUB, MVT::f32, 1 }, // Pentium III from http://www.agner.org/
855 { ISD::FSUB, MVT::v4f32, 2 }, // Pentium III from http://www.agner.org/
856
857 { ISD::ADD, MVT::i8, 1 }, // Pentium III from http://www.agner.org/
858 { ISD::ADD, MVT::i16, 1 }, // Pentium III from http://www.agner.org/
859 { ISD::ADD, MVT::i32, 1 }, // Pentium III from http://www.agner.org/
860
861 { ISD::SUB, MVT::i8, 1 }, // Pentium III from http://www.agner.org/
862 { ISD::SUB, MVT::i16, 1 }, // Pentium III from http://www.agner.org/
863 { ISD::SUB, MVT::i32, 1 }, // Pentium III from http://www.agner.org/
864 };
865
866 if (ST->hasSSE1())
867 if (const auto *Entry = CostTableLookup(SSE1CostTable, ISD, LT.second))
868 return LT.first * Entry->Cost;
869
870 // It is not a good idea to vectorize division. We have to scalarize it and
871 // in the process we will often end up having to spilling regular
872 // registers. The overhead of division is going to dominate most kernels
873 // anyways so try hard to prevent vectorization of division - it is
874 // generally a bad idea. Assume somewhat arbitrarily that we have to be able
875 // to hide "20 cycles" for each lane.
876 if (LT.second.isVector() && (ISD == ISD::SDIV || ISD == ISD::SREM ||
877 ISD == ISD::UDIV || ISD == ISD::UREM)) {
878 int ScalarCost = getArithmeticInstrCost(
879 Opcode, Ty->getScalarType(), Op1Info, Op2Info,
880 TargetTransformInfo::OP_None, TargetTransformInfo::OP_None);
881 return 20 * LT.first * LT.second.getVectorNumElements() * ScalarCost;
882 }
883
884 // Fallback to the default implementation.
885 return BaseT::getArithmeticInstrCost(Opcode, Ty, Op1Info, Op2Info);
886}
887
888int X86TTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
889 Type *SubTp) {
890 // 64-bit packed float vectors (v2f32) are widened to type v4f32.
891 // 64-bit packed integer vectors (v2i32) are widened to type v4i32.
892 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
893
894 // Treat Transpose as 2-op shuffles - there's no difference in lowering.
895 if (Kind == TTI::SK_Transpose)
896 Kind = TTI::SK_PermuteTwoSrc;
897
898 // For Broadcasts we are splatting the first element from the first input
899 // register, so only need to reference that input and all the output
900 // registers are the same.
901 if (Kind == TTI::SK_Broadcast)
902 LT.first = 1;
903
904 // Subvector extractions are free if they start at the beginning of a
905 // vector and cheap if the subvectors are aligned.
906 if (Kind == TTI::SK_ExtractSubvector && LT.second.isVector()) {
907 int NumElts = LT.second.getVectorNumElements();
908 if ((Index % NumElts) == 0)
909 return 0;
910 std::pair<int, MVT> SubLT = TLI->getTypeLegalizationCost(DL, SubTp);
911 if (SubLT.second.isVector()) {
912 int NumSubElts = SubLT.second.getVectorNumElements();
913 if ((Index % NumSubElts) == 0 && (NumElts % NumSubElts) == 0)
914 return SubLT.first;
915 // Handle some cases for widening legalization. For now we only handle
916 // cases where the original subvector was naturally aligned and evenly
917 // fit in its legalized subvector type.
918 // FIXME: Remove some of the alignment restrictions.
919 // FIXME: We can use permq for 64-bit or larger extracts from 256-bit
920 // vectors.
921 int OrigSubElts = SubTp->getVectorNumElements();
922 if (NumSubElts > OrigSubElts &&
923 (Index % OrigSubElts) == 0 && (NumSubElts % OrigSubElts) == 0 &&
924 LT.second.getVectorElementType() ==
925 SubLT.second.getVectorElementType() &&
926 LT.second.getVectorElementType().getSizeInBits() ==
927 Tp->getVectorElementType()->getPrimitiveSizeInBits()) {
928 assert(NumElts >= NumSubElts && NumElts > OrigSubElts &&((NumElts >= NumSubElts && NumElts > OrigSubElts
&& "Unexpected number of elements!") ? static_cast<
void> (0) : __assert_fail ("NumElts >= NumSubElts && NumElts > OrigSubElts && \"Unexpected number of elements!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 929, __PRETTY_FUNCTION__))
929 "Unexpected number of elements!")((NumElts >= NumSubElts && NumElts > OrigSubElts
&& "Unexpected number of elements!") ? static_cast<
void> (0) : __assert_fail ("NumElts >= NumSubElts && NumElts > OrigSubElts && \"Unexpected number of elements!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 929, __PRETTY_FUNCTION__))
;
930 Type *VecTy = VectorType::get(Tp->getVectorElementType(),
931 LT.second.getVectorNumElements());
932 Type *SubTy = VectorType::get(Tp->getVectorElementType(),
933 SubLT.second.getVectorNumElements());
934 int ExtractIndex = alignDown((Index % NumElts), NumSubElts);
935 int ExtractCost = getShuffleCost(TTI::SK_ExtractSubvector, VecTy,
936 ExtractIndex, SubTy);
937
938 // If the original size is 32-bits or more, we can use pshufd. Otherwise
939 // if we have SSSE3 we can use pshufb.
940 if (SubTp->getPrimitiveSizeInBits() >= 32 || ST->hasSSSE3())
941 return ExtractCost + 1; // pshufd or pshufb
942
943 assert(SubTp->getPrimitiveSizeInBits() == 16 &&((SubTp->getPrimitiveSizeInBits() == 16 && "Unexpected vector size"
) ? static_cast<void> (0) : __assert_fail ("SubTp->getPrimitiveSizeInBits() == 16 && \"Unexpected vector size\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 944, __PRETTY_FUNCTION__))
944 "Unexpected vector size")((SubTp->getPrimitiveSizeInBits() == 16 && "Unexpected vector size"
) ? static_cast<void> (0) : __assert_fail ("SubTp->getPrimitiveSizeInBits() == 16 && \"Unexpected vector size\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 944, __PRETTY_FUNCTION__))
;
945
946 return ExtractCost + 2; // worst case pshufhw + pshufd
947 }
948 }
949 }
950
951 // We are going to permute multiple sources and the result will be in multiple
952 // destinations. Providing an accurate cost only for splits where the element
953 // type remains the same.
954 if (Kind == TTI::SK_PermuteSingleSrc && LT.first != 1) {
955 MVT LegalVT = LT.second;
956 if (LegalVT.isVector() &&
957 LegalVT.getVectorElementType().getSizeInBits() ==
958 Tp->getVectorElementType()->getPrimitiveSizeInBits() &&
959 LegalVT.getVectorNumElements() < Tp->getVectorNumElements()) {
960
961 unsigned VecTySize = DL.getTypeStoreSize(Tp);
962 unsigned LegalVTSize = LegalVT.getStoreSize();
963 // Number of source vectors after legalization:
964 unsigned NumOfSrcs = (VecTySize + LegalVTSize - 1) / LegalVTSize;
965 // Number of destination vectors after legalization:
966 unsigned NumOfDests = LT.first;
967
968 Type *SingleOpTy = VectorType::get(Tp->getVectorElementType(),
969 LegalVT.getVectorNumElements());
970
971 unsigned NumOfShuffles = (NumOfSrcs - 1) * NumOfDests;
972 return NumOfShuffles *
973 getShuffleCost(TTI::SK_PermuteTwoSrc, SingleOpTy, 0, nullptr);
974 }
975
976 return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
977 }
978
979 // For 2-input shuffles, we must account for splitting the 2 inputs into many.
980 if (Kind == TTI::SK_PermuteTwoSrc && LT.first != 1) {
981 // We assume that source and destination have the same vector type.
982 int NumOfDests = LT.first;
983 int NumOfShufflesPerDest = LT.first * 2 - 1;
984 LT.first = NumOfDests * NumOfShufflesPerDest;
985 }
986
987 static const CostTblEntry AVX512VBMIShuffleTbl[] = {
988 {TTI::SK_Reverse, MVT::v64i8, 1}, // vpermb
989 {TTI::SK_Reverse, MVT::v32i8, 1}, // vpermb
990
991 {TTI::SK_PermuteSingleSrc, MVT::v64i8, 1}, // vpermb
992 {TTI::SK_PermuteSingleSrc, MVT::v32i8, 1}, // vpermb
993
994 {TTI::SK_PermuteTwoSrc, MVT::v64i8, 1}, // vpermt2b
995 {TTI::SK_PermuteTwoSrc, MVT::v32i8, 1}, // vpermt2b
996 {TTI::SK_PermuteTwoSrc, MVT::v16i8, 1} // vpermt2b
997 };
998
999 if (ST->hasVBMI())
1000 if (const auto *Entry =
1001 CostTableLookup(AVX512VBMIShuffleTbl, Kind, LT.second))
1002 return LT.first * Entry->Cost;
1003
1004 static const CostTblEntry AVX512BWShuffleTbl[] = {
1005 {TTI::SK_Broadcast, MVT::v32i16, 1}, // vpbroadcastw
1006 {TTI::SK_Broadcast, MVT::v64i8, 1}, // vpbroadcastb
1007
1008 {TTI::SK_Reverse, MVT::v32i16, 1}, // vpermw
1009 {TTI::SK_Reverse, MVT::v16i16, 1}, // vpermw
1010 {TTI::SK_Reverse, MVT::v64i8, 2}, // pshufb + vshufi64x2
1011
1012 {TTI::SK_PermuteSingleSrc, MVT::v32i16, 1}, // vpermw
1013 {TTI::SK_PermuteSingleSrc, MVT::v16i16, 1}, // vpermw
1014 {TTI::SK_PermuteSingleSrc, MVT::v8i16, 1}, // vpermw
1015 {TTI::SK_PermuteSingleSrc, MVT::v64i8, 8}, // extend to v32i16
1016 {TTI::SK_PermuteSingleSrc, MVT::v32i8, 3}, // vpermw + zext/trunc
1017
1018 {TTI::SK_PermuteTwoSrc, MVT::v32i16, 1}, // vpermt2w
1019 {TTI::SK_PermuteTwoSrc, MVT::v16i16, 1}, // vpermt2w
1020 {TTI::SK_PermuteTwoSrc, MVT::v8i16, 1}, // vpermt2w
1021 {TTI::SK_PermuteTwoSrc, MVT::v32i8, 3}, // zext + vpermt2w + trunc
1022 {TTI::SK_PermuteTwoSrc, MVT::v64i8, 19}, // 6 * v32i8 + 1
1023 {TTI::SK_PermuteTwoSrc, MVT::v16i8, 3} // zext + vpermt2w + trunc
1024 };
1025
1026 if (ST->hasBWI())
1027 if (const auto *Entry =
1028 CostTableLookup(AVX512BWShuffleTbl, Kind, LT.second))
1029 return LT.first * Entry->Cost;
1030
1031 static const CostTblEntry AVX512ShuffleTbl[] = {
1032 {TTI::SK_Broadcast, MVT::v8f64, 1}, // vbroadcastpd
1033 {TTI::SK_Broadcast, MVT::v16f32, 1}, // vbroadcastps
1034 {TTI::SK_Broadcast, MVT::v8i64, 1}, // vpbroadcastq
1035 {TTI::SK_Broadcast, MVT::v16i32, 1}, // vpbroadcastd
1036
1037 {TTI::SK_Reverse, MVT::v8f64, 1}, // vpermpd
1038 {TTI::SK_Reverse, MVT::v16f32, 1}, // vpermps
1039 {TTI::SK_Reverse, MVT::v8i64, 1}, // vpermq
1040 {TTI::SK_Reverse, MVT::v16i32, 1}, // vpermd
1041
1042 {TTI::SK_PermuteSingleSrc, MVT::v8f64, 1}, // vpermpd
1043 {TTI::SK_PermuteSingleSrc, MVT::v4f64, 1}, // vpermpd
1044 {TTI::SK_PermuteSingleSrc, MVT::v2f64, 1}, // vpermpd
1045 {TTI::SK_PermuteSingleSrc, MVT::v16f32, 1}, // vpermps
1046 {TTI::SK_PermuteSingleSrc, MVT::v8f32, 1}, // vpermps
1047 {TTI::SK_PermuteSingleSrc, MVT::v4f32, 1}, // vpermps
1048 {TTI::SK_PermuteSingleSrc, MVT::v8i64, 1}, // vpermq
1049 {TTI::SK_PermuteSingleSrc, MVT::v4i64, 1}, // vpermq
1050 {TTI::SK_PermuteSingleSrc, MVT::v2i64, 1}, // vpermq
1051 {TTI::SK_PermuteSingleSrc, MVT::v16i32, 1}, // vpermd
1052 {TTI::SK_PermuteSingleSrc, MVT::v8i32, 1}, // vpermd
1053 {TTI::SK_PermuteSingleSrc, MVT::v4i32, 1}, // vpermd
1054 {TTI::SK_PermuteSingleSrc, MVT::v16i8, 1}, // pshufb
1055
1056 {TTI::SK_PermuteTwoSrc, MVT::v8f64, 1}, // vpermt2pd
1057 {TTI::SK_PermuteTwoSrc, MVT::v16f32, 1}, // vpermt2ps
1058 {TTI::SK_PermuteTwoSrc, MVT::v8i64, 1}, // vpermt2q
1059 {TTI::SK_PermuteTwoSrc, MVT::v16i32, 1}, // vpermt2d
1060 {TTI::SK_PermuteTwoSrc, MVT::v4f64, 1}, // vpermt2pd
1061 {TTI::SK_PermuteTwoSrc, MVT::v8f32, 1}, // vpermt2ps
1062 {TTI::SK_PermuteTwoSrc, MVT::v4i64, 1}, // vpermt2q
1063 {TTI::SK_PermuteTwoSrc, MVT::v8i32, 1}, // vpermt2d
1064 {TTI::SK_PermuteTwoSrc, MVT::v2f64, 1}, // vpermt2pd
1065 {TTI::SK_PermuteTwoSrc, MVT::v4f32, 1}, // vpermt2ps
1066 {TTI::SK_PermuteTwoSrc, MVT::v2i64, 1}, // vpermt2q
1067 {TTI::SK_PermuteTwoSrc, MVT::v4i32, 1} // vpermt2d
1068 };
1069
1070 if (ST->hasAVX512())
1071 if (const auto *Entry = CostTableLookup(AVX512ShuffleTbl, Kind, LT.second))
1072 return LT.first * Entry->Cost;
1073
1074 static const CostTblEntry AVX2ShuffleTbl[] = {
1075 {TTI::SK_Broadcast, MVT::v4f64, 1}, // vbroadcastpd
1076 {TTI::SK_Broadcast, MVT::v8f32, 1}, // vbroadcastps
1077 {TTI::SK_Broadcast, MVT::v4i64, 1}, // vpbroadcastq
1078 {TTI::SK_Broadcast, MVT::v8i32, 1}, // vpbroadcastd
1079 {TTI::SK_Broadcast, MVT::v16i16, 1}, // vpbroadcastw
1080 {TTI::SK_Broadcast, MVT::v32i8, 1}, // vpbroadcastb
1081
1082 {TTI::SK_Reverse, MVT::v4f64, 1}, // vpermpd
1083 {TTI::SK_Reverse, MVT::v8f32, 1}, // vpermps
1084 {TTI::SK_Reverse, MVT::v4i64, 1}, // vpermq
1085 {TTI::SK_Reverse, MVT::v8i32, 1}, // vpermd
1086 {TTI::SK_Reverse, MVT::v16i16, 2}, // vperm2i128 + pshufb
1087 {TTI::SK_Reverse, MVT::v32i8, 2}, // vperm2i128 + pshufb
1088
1089 {TTI::SK_Select, MVT::v16i16, 1}, // vpblendvb
1090 {TTI::SK_Select, MVT::v32i8, 1}, // vpblendvb
1091
1092 {TTI::SK_PermuteSingleSrc, MVT::v4f64, 1}, // vpermpd
1093 {TTI::SK_PermuteSingleSrc, MVT::v8f32, 1}, // vpermps
1094 {TTI::SK_PermuteSingleSrc, MVT::v4i64, 1}, // vpermq
1095 {TTI::SK_PermuteSingleSrc, MVT::v8i32, 1}, // vpermd
1096 {TTI::SK_PermuteSingleSrc, MVT::v16i16, 4}, // vperm2i128 + 2*vpshufb
1097 // + vpblendvb
1098 {TTI::SK_PermuteSingleSrc, MVT::v32i8, 4}, // vperm2i128 + 2*vpshufb
1099 // + vpblendvb
1100
1101 {TTI::SK_PermuteTwoSrc, MVT::v4f64, 3}, // 2*vpermpd + vblendpd
1102 {TTI::SK_PermuteTwoSrc, MVT::v8f32, 3}, // 2*vpermps + vblendps
1103 {TTI::SK_PermuteTwoSrc, MVT::v4i64, 3}, // 2*vpermq + vpblendd
1104 {TTI::SK_PermuteTwoSrc, MVT::v8i32, 3}, // 2*vpermd + vpblendd
1105 {TTI::SK_PermuteTwoSrc, MVT::v16i16, 7}, // 2*vperm2i128 + 4*vpshufb
1106 // + vpblendvb
1107 {TTI::SK_PermuteTwoSrc, MVT::v32i8, 7}, // 2*vperm2i128 + 4*vpshufb
1108 // + vpblendvb
1109 };
1110
1111 if (ST->hasAVX2())
1112 if (const auto *Entry = CostTableLookup(AVX2ShuffleTbl, Kind, LT.second))
1113 return LT.first * Entry->Cost;
1114
1115 static const CostTblEntry XOPShuffleTbl[] = {
1116 {TTI::SK_PermuteSingleSrc, MVT::v4f64, 2}, // vperm2f128 + vpermil2pd
1117 {TTI::SK_PermuteSingleSrc, MVT::v8f32, 2}, // vperm2f128 + vpermil2ps
1118 {TTI::SK_PermuteSingleSrc, MVT::v4i64, 2}, // vperm2f128 + vpermil2pd
1119 {TTI::SK_PermuteSingleSrc, MVT::v8i32, 2}, // vperm2f128 + vpermil2ps
1120 {TTI::SK_PermuteSingleSrc, MVT::v16i16, 4}, // vextractf128 + 2*vpperm
1121 // + vinsertf128
1122 {TTI::SK_PermuteSingleSrc, MVT::v32i8, 4}, // vextractf128 + 2*vpperm
1123 // + vinsertf128
1124
1125 {TTI::SK_PermuteTwoSrc, MVT::v16i16, 9}, // 2*vextractf128 + 6*vpperm
1126 // + vinsertf128
1127 {TTI::SK_PermuteTwoSrc, MVT::v8i16, 1}, // vpperm
1128 {TTI::SK_PermuteTwoSrc, MVT::v32i8, 9}, // 2*vextractf128 + 6*vpperm
1129 // + vinsertf128
1130 {TTI::SK_PermuteTwoSrc, MVT::v16i8, 1}, // vpperm
1131 };
1132
1133 if (ST->hasXOP())
1134 if (const auto *Entry = CostTableLookup(XOPShuffleTbl, Kind, LT.second))
1135 return LT.first * Entry->Cost;
1136
1137 static const CostTblEntry AVX1ShuffleTbl[] = {
1138 {TTI::SK_Broadcast, MVT::v4f64, 2}, // vperm2f128 + vpermilpd
1139 {TTI::SK_Broadcast, MVT::v8f32, 2}, // vperm2f128 + vpermilps
1140 {TTI::SK_Broadcast, MVT::v4i64, 2}, // vperm2f128 + vpermilpd
1141 {TTI::SK_Broadcast, MVT::v8i32, 2}, // vperm2f128 + vpermilps
1142 {TTI::SK_Broadcast, MVT::v16i16, 3}, // vpshuflw + vpshufd + vinsertf128
1143 {TTI::SK_Broadcast, MVT::v32i8, 2}, // vpshufb + vinsertf128
1144
1145 {TTI::SK_Reverse, MVT::v4f64, 2}, // vperm2f128 + vpermilpd
1146 {TTI::SK_Reverse, MVT::v8f32, 2}, // vperm2f128 + vpermilps
1147 {TTI::SK_Reverse, MVT::v4i64, 2}, // vperm2f128 + vpermilpd
1148 {TTI::SK_Reverse, MVT::v8i32, 2}, // vperm2f128 + vpermilps
1149 {TTI::SK_Reverse, MVT::v16i16, 4}, // vextractf128 + 2*pshufb
1150 // + vinsertf128
1151 {TTI::SK_Reverse, MVT::v32i8, 4}, // vextractf128 + 2*pshufb
1152 // + vinsertf128
1153
1154 {TTI::SK_Select, MVT::v4i64, 1}, // vblendpd
1155 {TTI::SK_Select, MVT::v4f64, 1}, // vblendpd
1156 {TTI::SK_Select, MVT::v8i32, 1}, // vblendps
1157 {TTI::SK_Select, MVT::v8f32, 1}, // vblendps
1158 {TTI::SK_Select, MVT::v16i16, 3}, // vpand + vpandn + vpor
1159 {TTI::SK_Select, MVT::v32i8, 3}, // vpand + vpandn + vpor
1160
1161 {TTI::SK_PermuteSingleSrc, MVT::v4f64, 2}, // vperm2f128 + vshufpd
1162 {TTI::SK_PermuteSingleSrc, MVT::v4i64, 2}, // vperm2f128 + vshufpd
1163 {TTI::SK_PermuteSingleSrc, MVT::v8f32, 4}, // 2*vperm2f128 + 2*vshufps
1164 {TTI::SK_PermuteSingleSrc, MVT::v8i32, 4}, // 2*vperm2f128 + 2*vshufps
1165 {TTI::SK_PermuteSingleSrc, MVT::v16i16, 8}, // vextractf128 + 4*pshufb
1166 // + 2*por + vinsertf128
1167 {TTI::SK_PermuteSingleSrc, MVT::v32i8, 8}, // vextractf128 + 4*pshufb
1168 // + 2*por + vinsertf128
1169
1170 {TTI::SK_PermuteTwoSrc, MVT::v4f64, 3}, // 2*vperm2f128 + vshufpd
1171 {TTI::SK_PermuteTwoSrc, MVT::v4i64, 3}, // 2*vperm2f128 + vshufpd
1172 {TTI::SK_PermuteTwoSrc, MVT::v8f32, 4}, // 2*vperm2f128 + 2*vshufps
1173 {TTI::SK_PermuteTwoSrc, MVT::v8i32, 4}, // 2*vperm2f128 + 2*vshufps
1174 {TTI::SK_PermuteTwoSrc, MVT::v16i16, 15}, // 2*vextractf128 + 8*pshufb
1175 // + 4*por + vinsertf128
1176 {TTI::SK_PermuteTwoSrc, MVT::v32i8, 15}, // 2*vextractf128 + 8*pshufb
1177 // + 4*por + vinsertf128
1178 };
1179
1180 if (ST->hasAVX())
1181 if (const auto *Entry = CostTableLookup(AVX1ShuffleTbl, Kind, LT.second))
1182 return LT.first * Entry->Cost;
1183
1184 static const CostTblEntry SSE41ShuffleTbl[] = {
1185 {TTI::SK_Select, MVT::v2i64, 1}, // pblendw
1186 {TTI::SK_Select, MVT::v2f64, 1}, // movsd
1187 {TTI::SK_Select, MVT::v4i32, 1}, // pblendw
1188 {TTI::SK_Select, MVT::v4f32, 1}, // blendps
1189 {TTI::SK_Select, MVT::v8i16, 1}, // pblendw
1190 {TTI::SK_Select, MVT::v16i8, 1} // pblendvb
1191 };
1192
1193 if (ST->hasSSE41())
1194 if (const auto *Entry = CostTableLookup(SSE41ShuffleTbl, Kind, LT.second))
1195 return LT.first * Entry->Cost;
1196
1197 static const CostTblEntry SSSE3ShuffleTbl[] = {
1198 {TTI::SK_Broadcast, MVT::v8i16, 1}, // pshufb
1199 {TTI::SK_Broadcast, MVT::v16i8, 1}, // pshufb
1200
1201 {TTI::SK_Reverse, MVT::v8i16, 1}, // pshufb
1202 {TTI::SK_Reverse, MVT::v16i8, 1}, // pshufb
1203
1204 {TTI::SK_Select, MVT::v8i16, 3}, // 2*pshufb + por
1205 {TTI::SK_Select, MVT::v16i8, 3}, // 2*pshufb + por
1206
1207 {TTI::SK_PermuteSingleSrc, MVT::v8i16, 1}, // pshufb
1208 {TTI::SK_PermuteSingleSrc, MVT::v16i8, 1}, // pshufb
1209
1210 {TTI::SK_PermuteTwoSrc, MVT::v8i16, 3}, // 2*pshufb + por
1211 {TTI::SK_PermuteTwoSrc, MVT::v16i8, 3}, // 2*pshufb + por
1212 };
1213
1214 if (ST->hasSSSE3())
1215 if (const auto *Entry = CostTableLookup(SSSE3ShuffleTbl, Kind, LT.second))
1216 return LT.first * Entry->Cost;
1217
1218 static const CostTblEntry SSE2ShuffleTbl[] = {
1219 {TTI::SK_Broadcast, MVT::v2f64, 1}, // shufpd
1220 {TTI::SK_Broadcast, MVT::v2i64, 1}, // pshufd
1221 {TTI::SK_Broadcast, MVT::v4i32, 1}, // pshufd
1222 {TTI::SK_Broadcast, MVT::v8i16, 2}, // pshuflw + pshufd
1223 {TTI::SK_Broadcast, MVT::v16i8, 3}, // unpck + pshuflw + pshufd
1224
1225 {TTI::SK_Reverse, MVT::v2f64, 1}, // shufpd
1226 {TTI::SK_Reverse, MVT::v2i64, 1}, // pshufd
1227 {TTI::SK_Reverse, MVT::v4i32, 1}, // pshufd
1228 {TTI::SK_Reverse, MVT::v8i16, 3}, // pshuflw + pshufhw + pshufd
1229 {TTI::SK_Reverse, MVT::v16i8, 9}, // 2*pshuflw + 2*pshufhw
1230 // + 2*pshufd + 2*unpck + packus
1231
1232 {TTI::SK_Select, MVT::v2i64, 1}, // movsd
1233 {TTI::SK_Select, MVT::v2f64, 1}, // movsd
1234 {TTI::SK_Select, MVT::v4i32, 2}, // 2*shufps
1235 {TTI::SK_Select, MVT::v8i16, 3}, // pand + pandn + por
1236 {TTI::SK_Select, MVT::v16i8, 3}, // pand + pandn + por
1237
1238 {TTI::SK_PermuteSingleSrc, MVT::v2f64, 1}, // shufpd
1239 {TTI::SK_PermuteSingleSrc, MVT::v2i64, 1}, // pshufd
1240 {TTI::SK_PermuteSingleSrc, MVT::v4i32, 1}, // pshufd
1241 {TTI::SK_PermuteSingleSrc, MVT::v8i16, 5}, // 2*pshuflw + 2*pshufhw
1242 // + pshufd/unpck
1243 { TTI::SK_PermuteSingleSrc, MVT::v16i8, 10 }, // 2*pshuflw + 2*pshufhw
1244 // + 2*pshufd + 2*unpck + 2*packus
1245
1246 { TTI::SK_PermuteTwoSrc, MVT::v2f64, 1 }, // shufpd
1247 { TTI::SK_PermuteTwoSrc, MVT::v2i64, 1 }, // shufpd
1248 { TTI::SK_PermuteTwoSrc, MVT::v4i32, 2 }, // 2*{unpck,movsd,pshufd}
1249 { TTI::SK_PermuteTwoSrc, MVT::v8i16, 8 }, // blend+permute
1250 { TTI::SK_PermuteTwoSrc, MVT::v16i8, 13 }, // blend+permute
1251 };
1252
1253 if (ST->hasSSE2())
1254 if (const auto *Entry = CostTableLookup(SSE2ShuffleTbl, Kind, LT.second))
1255 return LT.first * Entry->Cost;
1256
1257 static const CostTblEntry SSE1ShuffleTbl[] = {
1258 { TTI::SK_Broadcast, MVT::v4f32, 1 }, // shufps
1259 { TTI::SK_Reverse, MVT::v4f32, 1 }, // shufps
1260 { TTI::SK_Select, MVT::v4f32, 2 }, // 2*shufps
1261 { TTI::SK_PermuteSingleSrc, MVT::v4f32, 1 }, // shufps
1262 { TTI::SK_PermuteTwoSrc, MVT::v4f32, 2 }, // 2*shufps
1263 };
1264
1265 if (ST->hasSSE1())
1266 if (const auto *Entry = CostTableLookup(SSE1ShuffleTbl, Kind, LT.second))
1267 return LT.first * Entry->Cost;
1268
1269 return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
1270}
1271
1272int X86TTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
1273 const Instruction *I) {
1274 int ISD = TLI->InstructionOpcodeToISD(Opcode);
1275 assert(ISD && "Invalid opcode")((ISD && "Invalid opcode") ? static_cast<void> (
0) : __assert_fail ("ISD && \"Invalid opcode\"", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 1275, __PRETTY_FUNCTION__))
;
1276
1277 // FIXME: Need a better design of the cost table to handle non-simple types of
1278 // potential massive combinations (elem_num x src_type x dst_type).
1279
1280 static const TypeConversionCostTblEntry AVX512BWConversionTbl[] {
1281 { ISD::SIGN_EXTEND, MVT::v32i16, MVT::v32i8, 1 },
1282 { ISD::ZERO_EXTEND, MVT::v32i16, MVT::v32i8, 1 },
1283
1284 // Mask sign extend has an instruction.
1285 { ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i1, 1 },
1286 { ISD::SIGN_EXTEND, MVT::v16i8, MVT::v16i1, 1 },
1287 { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i1, 1 },
1288 { ISD::SIGN_EXTEND, MVT::v32i8, MVT::v32i1, 1 },
1289 { ISD::SIGN_EXTEND, MVT::v32i16, MVT::v32i1, 1 },
1290 { ISD::SIGN_EXTEND, MVT::v64i8, MVT::v64i1, 1 },
1291
1292 // Mask zero extend is a load + broadcast.
1293 { ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i1, 2 },
1294 { ISD::ZERO_EXTEND, MVT::v16i8, MVT::v16i1, 2 },
1295 { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i1, 2 },
1296 { ISD::ZERO_EXTEND, MVT::v32i8, MVT::v32i1, 2 },
1297 { ISD::ZERO_EXTEND, MVT::v32i16, MVT::v32i1, 2 },
1298 { ISD::ZERO_EXTEND, MVT::v64i8, MVT::v64i1, 2 },
1299 };
1300
1301 static const TypeConversionCostTblEntry AVX512DQConversionTbl[] = {
1302 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i64, 1 },
1303 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i64, 1 },
1304 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i64, 1 },
1305 { ISD::SINT_TO_FP, MVT::v4f64, MVT::v4i64, 1 },
1306 { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i64, 1 },
1307 { ISD::SINT_TO_FP, MVT::v8f64, MVT::v8i64, 1 },
1308
1309 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i64, 1 },
1310 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i64, 1 },
1311 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i64, 1 },
1312 { ISD::UINT_TO_FP, MVT::v4f64, MVT::v4i64, 1 },
1313 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i64, 1 },
1314 { ISD::UINT_TO_FP, MVT::v8f64, MVT::v8i64, 1 },
1315
1316 { ISD::FP_TO_SINT, MVT::v2i64, MVT::v2f32, 1 },
1317 { ISD::FP_TO_SINT, MVT::v4i64, MVT::v4f32, 1 },
1318 { ISD::FP_TO_SINT, MVT::v8i64, MVT::v8f32, 1 },
1319 { ISD::FP_TO_SINT, MVT::v2i64, MVT::v2f64, 1 },
1320 { ISD::FP_TO_SINT, MVT::v4i64, MVT::v4f64, 1 },
1321 { ISD::FP_TO_SINT, MVT::v8i64, MVT::v8f64, 1 },
1322
1323 { ISD::FP_TO_UINT, MVT::v2i64, MVT::v2f32, 1 },
1324 { ISD::FP_TO_UINT, MVT::v4i64, MVT::v4f32, 1 },
1325 { ISD::FP_TO_UINT, MVT::v8i64, MVT::v8f32, 1 },
1326 { ISD::FP_TO_UINT, MVT::v2i64, MVT::v2f64, 1 },
1327 { ISD::FP_TO_UINT, MVT::v4i64, MVT::v4f64, 1 },
1328 { ISD::FP_TO_UINT, MVT::v8i64, MVT::v8f64, 1 },
1329 };
1330
1331 // TODO: For AVX512DQ + AVX512VL, we also have cheap casts for 128-bit and
1332 // 256-bit wide vectors.
1333
1334 static const TypeConversionCostTblEntry AVX512FConversionTbl[] = {
1335 { ISD::FP_EXTEND, MVT::v8f64, MVT::v8f32, 1 },
1336 { ISD::FP_EXTEND, MVT::v8f64, MVT::v16f32, 3 },
1337 { ISD::FP_ROUND, MVT::v8f32, MVT::v8f64, 1 },
1338
1339 { ISD::TRUNCATE, MVT::v16i8, MVT::v16i32, 1 },
1340 { ISD::TRUNCATE, MVT::v16i16, MVT::v16i32, 1 },
1341 { ISD::TRUNCATE, MVT::v8i16, MVT::v8i64, 1 },
1342 { ISD::TRUNCATE, MVT::v8i32, MVT::v8i64, 1 },
1343
1344 // v16i1 -> v16i32 - load + broadcast
1345 { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i1, 2 },
1346 { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i1, 2 },
1347 { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 1 },
1348 { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 1 },
1349 { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i16, 1 },
1350 { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i16, 1 },
1351 { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i8, 1 },
1352 { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i8, 1 },
1353 { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i16, 1 },
1354 { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i16, 1 },
1355 { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i32, 1 },
1356 { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i32, 1 },
1357
1358 { ISD::SINT_TO_FP, MVT::v8f64, MVT::v8i1, 4 },
1359 { ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i1, 3 },
1360 { ISD::SINT_TO_FP, MVT::v8f64, MVT::v8i8, 2 },
1361 { ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i8, 2 },
1362 { ISD::SINT_TO_FP, MVT::v8f64, MVT::v8i16, 2 },
1363 { ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i16, 2 },
1364 { ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i32, 1 },
1365 { ISD::SINT_TO_FP, MVT::v8f64, MVT::v8i32, 1 },
1366
1367 { ISD::UINT_TO_FP, MVT::v8f64, MVT::v8i1, 4 },
1368 { ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i1, 3 },
1369 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i8, 2 },
1370 { ISD::UINT_TO_FP, MVT::v4f64, MVT::v4i8, 2 },
1371 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i8, 2 },
1372 { ISD::UINT_TO_FP, MVT::v8f64, MVT::v8i8, 2 },
1373 { ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i8, 2 },
1374 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i16, 5 },
1375 { ISD::UINT_TO_FP, MVT::v4f64, MVT::v4i16, 2 },
1376 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i16, 2 },
1377 { ISD::UINT_TO_FP, MVT::v8f64, MVT::v8i16, 2 },
1378 { ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i16, 2 },
1379 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i32, 2 },
1380 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 1 },
1381 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
1382 { ISD::UINT_TO_FP, MVT::v4f64, MVT::v4i32, 1 },
1383 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i32, 1 },
1384 { ISD::UINT_TO_FP, MVT::v8f64, MVT::v8i32, 1 },
1385 { ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i32, 1 },
1386 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i64, 5 },
1387 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i64, 26 },
1388 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i64, 5 },
1389 { ISD::UINT_TO_FP, MVT::v4f64, MVT::v4i64, 5 },
1390 { ISD::UINT_TO_FP, MVT::v8f64, MVT::v8i64, 5 },
1391
1392 { ISD::UINT_TO_FP, MVT::f64, MVT::i64, 1 },
1393 { ISD::FP_TO_UINT, MVT::i64, MVT::f32, 1 },
1394 { ISD::FP_TO_UINT, MVT::i64, MVT::f64, 1 },
1395
1396 { ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f32, 1 },
1397 { ISD::FP_TO_UINT, MVT::v4i32, MVT::v4f32, 1 },
1398 { ISD::FP_TO_UINT, MVT::v4i32, MVT::v4f64, 1 },
1399 { ISD::FP_TO_UINT, MVT::v8i32, MVT::v8f32, 1 },
1400 { ISD::FP_TO_UINT, MVT::v8i16, MVT::v8f64, 2 },
1401 { ISD::FP_TO_UINT, MVT::v8i8, MVT::v8f64, 2 },
1402 { ISD::FP_TO_UINT, MVT::v16i32, MVT::v16f32, 1 },
1403 { ISD::FP_TO_UINT, MVT::v16i16, MVT::v16f32, 2 },
1404 { ISD::FP_TO_UINT, MVT::v16i8, MVT::v16f32, 2 },
1405 };
1406
1407 static const TypeConversionCostTblEntry AVX2ConversionTbl[] = {
1408 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i1, 3 },
1409 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i1, 3 },
1410 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i1, 3 },
1411 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i1, 3 },
1412 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i8, 1 },
1413 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i8, 1 },
1414 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i8, 1 },
1415 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i8, 1 },
1416 { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 1 },
1417 { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 1 },
1418 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16, 1 },
1419 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16, 1 },
1420 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 1 },
1421 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 1 },
1422 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32, 1 },
1423 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32, 1 },
1424
1425 { ISD::TRUNCATE, MVT::v4i8, MVT::v4i64, 2 },
1426 { ISD::TRUNCATE, MVT::v4i16, MVT::v4i64, 2 },
1427 { ISD::TRUNCATE, MVT::v4i32, MVT::v4i64, 2 },
1428 { ISD::TRUNCATE, MVT::v8i8, MVT::v8i32, 2 },
1429 { ISD::TRUNCATE, MVT::v8i16, MVT::v8i32, 2 },
1430 { ISD::TRUNCATE, MVT::v8i32, MVT::v8i64, 4 },
1431
1432 { ISD::FP_EXTEND, MVT::v8f64, MVT::v8f32, 3 },
1433 { ISD::FP_ROUND, MVT::v8f32, MVT::v8f64, 3 },
1434
1435 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i32, 8 },
1436 };
1437
1438 static const TypeConversionCostTblEntry AVXConversionTbl[] = {
1439 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i1, 6 },
1440 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i1, 4 },
1441 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i1, 7 },
1442 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i1, 4 },
1443 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i8, 4 },
1444 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i8, 4 },
1445 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i8, 4 },
1446 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i8, 4 },
1447 { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 4 },
1448 { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 4 },
1449 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16, 4 },
1450 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
1451 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 4 },
1452 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 4 },
1453 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32, 4 },
1454 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32, 4 },
1455
1456 { ISD::TRUNCATE, MVT::v16i8, MVT::v16i16, 4 },
1457 { ISD::TRUNCATE, MVT::v8i8, MVT::v8i32, 4 },
1458 { ISD::TRUNCATE, MVT::v8i16, MVT::v8i32, 5 },
1459 { ISD::TRUNCATE, MVT::v4i8, MVT::v4i64, 4 },
1460 { ISD::TRUNCATE, MVT::v4i16, MVT::v4i64, 4 },
1461 { ISD::TRUNCATE, MVT::v4i32, MVT::v4i64, 4 },
1462 { ISD::TRUNCATE, MVT::v8i8, MVT::v8i64, 11 },
1463 { ISD::TRUNCATE, MVT::v8i16, MVT::v8i64, 9 },
1464 { ISD::TRUNCATE, MVT::v8i32, MVT::v8i64, 9 },
1465 { ISD::TRUNCATE, MVT::v16i8, MVT::v16i64, 11 },
1466
1467 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i1, 3 },
1468 { ISD::SINT_TO_FP, MVT::v4f64, MVT::v4i1, 3 },
1469 { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i1, 8 },
1470 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i8, 3 },
1471 { ISD::SINT_TO_FP, MVT::v4f64, MVT::v4i8, 3 },
1472 { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i8, 8 },
1473 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i16, 3 },
1474 { ISD::SINT_TO_FP, MVT::v4f64, MVT::v4i16, 3 },
1475 { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i16, 5 },
1476 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
1477 { ISD::SINT_TO_FP, MVT::v4f64, MVT::v4i32, 1 },
1478 { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i32, 1 },
1479
1480 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i1, 7 },
1481 { ISD::UINT_TO_FP, MVT::v4f64, MVT::v4i1, 7 },
1482 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i1, 6 },
1483 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i8, 2 },
1484 { ISD::UINT_TO_FP, MVT::v4f64, MVT::v4i8, 2 },
1485 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i8, 5 },
1486 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 },
1487 { ISD::UINT_TO_FP, MVT::v4f64, MVT::v4i16, 2 },
1488 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i16, 5 },
1489 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 6 },
1490 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 6 },
1491 { ISD::UINT_TO_FP, MVT::v4f64, MVT::v4i32, 6 },
1492 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i32, 9 },
1493 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i64, 5 },
1494 { ISD::UINT_TO_FP, MVT::v4f64, MVT::v4i64, 6 },
1495 // The generic code to compute the scalar overhead is currently broken.
1496 // Workaround this limitation by estimating the scalarization overhead
1497 // here. We have roughly 10 instructions per scalar element.
1498 // Multiply that by the vector width.
1499 // FIXME: remove that when PR19268 is fixed.
1500 { ISD::SINT_TO_FP, MVT::v4f64, MVT::v4i64, 13 },
1501 { ISD::SINT_TO_FP, MVT::v4f64, MVT::v4i64, 13 },
1502
1503 { ISD::FP_TO_SINT, MVT::v4i8, MVT::v4f32, 1 },
1504 { ISD::FP_TO_SINT, MVT::v8i8, MVT::v8f32, 7 },
1505 // This node is expanded into scalarized operations but BasicTTI is overly
1506 // optimistic estimating its cost. It computes 3 per element (one
1507 // vector-extract, one scalar conversion and one vector-insert). The
1508 // problem is that the inserts form a read-modify-write chain so latency
1509 // should be factored in too. Inflating the cost per element by 1.
1510 { ISD::FP_TO_UINT, MVT::v8i32, MVT::v8f32, 8*4 },
1511 { ISD::FP_TO_UINT, MVT::v4i32, MVT::v4f64, 4*4 },
1512
1513 { ISD::FP_EXTEND, MVT::v4f64, MVT::v4f32, 1 },
1514 { ISD::FP_ROUND, MVT::v4f32, MVT::v4f64, 1 },
1515 };
1516
1517 static const TypeConversionCostTblEntry SSE41ConversionTbl[] = {
1518 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i8, 2 },
1519 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i8, 2 },
1520 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16, 2 },
1521 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16, 2 },
1522 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32, 2 },
1523 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32, 2 },
1524
1525 { ISD::ZERO_EXTEND, MVT::v4i16, MVT::v4i8, 1 },
1526 { ISD::SIGN_EXTEND, MVT::v4i16, MVT::v4i8, 2 },
1527 { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 1 },
1528 { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 1 },
1529 { ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
1530 { ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
1531 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i8, 2 },
1532 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i8, 2 },
1533 { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 2 },
1534 { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 2 },
1535 { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 4 },
1536 { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 4 },
1537 { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
1538 { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
1539 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 2 },
1540 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 2 },
1541 { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i16, 4 },
1542 { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i16, 4 },
1543
1544 { ISD::TRUNCATE, MVT::v4i8, MVT::v4i16, 2 },
1545 { ISD::TRUNCATE, MVT::v8i8, MVT::v8i16, 1 },
1546 { ISD::TRUNCATE, MVT::v4i8, MVT::v4i32, 1 },
1547 { ISD::TRUNCATE, MVT::v4i16, MVT::v4i32, 1 },
1548 { ISD::TRUNCATE, MVT::v8i8, MVT::v8i32, 3 },
1549 { ISD::TRUNCATE, MVT::v8i16, MVT::v8i32, 3 },
1550 { ISD::TRUNCATE, MVT::v16i16, MVT::v16i32, 6 },
1551 { ISD::TRUNCATE, MVT::v2i8, MVT::v2i64, 1 }, // PSHUFB
1552
1553 { ISD::UINT_TO_FP, MVT::f64, MVT::i64, 4 },
1554 };
1555
1556 static const TypeConversionCostTblEntry SSE2ConversionTbl[] = {
1557 // These are somewhat magic numbers justified by looking at the output of
1558 // Intel's IACA, running some kernels and making sure when we take
1559 // legalization into account the throughput will be overestimated.
1560 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v16i8, 8 },
1561 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v16i8, 16*10 },
1562 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v8i16, 15 },
1563 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v8i16, 8*10 },
1564 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i32, 5 },
1565 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v4i32, 2*10 },
1566 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 2*10 },
1567 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v2i64, 15 },
1568 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i64, 2*10 },
1569
1570 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v16i8, 16*10 },
1571 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v16i8, 8 },
1572 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v8i16, 15 },
1573 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v8i16, 8*10 },
1574 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v4i32, 4*10 },
1575 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 8 },
1576 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i64, 6 },
1577 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v2i64, 15 },
1578
1579 { ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f64, 3 },
1580
1581 { ISD::UINT_TO_FP, MVT::f64, MVT::i64, 6 },
1582 { ISD::FP_TO_UINT, MVT::i64, MVT::f32, 4 },
1583 { ISD::FP_TO_UINT, MVT::i64, MVT::f64, 4 },
1584
1585 { ISD::ZERO_EXTEND, MVT::v4i16, MVT::v4i8, 1 },
1586 { ISD::SIGN_EXTEND, MVT::v4i16, MVT::v4i8, 6 },
1587 { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 2 },
1588 { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 3 },
1589 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i8, 4 },
1590 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i8, 8 },
1591 { ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
1592 { ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 2 },
1593 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i8, 6 },
1594 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i8, 6 },
1595 { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 3 },
1596 { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 4 },
1597 { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 9 },
1598 { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 12 },
1599 { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
1600 { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 2 },
1601 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
1602 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16, 10 },
1603 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 3 },
1604 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 4 },
1605 { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i16, 6 },
1606 { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i16, 8 },
1607 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32, 3 },
1608 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32, 5 },
1609
1610 { ISD::TRUNCATE, MVT::v2i8, MVT::v2i16, 2 }, // PAND+PACKUSWB
1611 { ISD::TRUNCATE, MVT::v4i8, MVT::v4i16, 4 },
1612 { ISD::TRUNCATE, MVT::v8i8, MVT::v8i16, 2 },
1613 { ISD::TRUNCATE, MVT::v16i8, MVT::v16i16, 3 },
1614 { ISD::TRUNCATE, MVT::v2i8, MVT::v2i32, 3 }, // PAND+3*PACKUSWB
1615 { ISD::TRUNCATE, MVT::v2i16, MVT::v2i32, 1 },
1616 { ISD::TRUNCATE, MVT::v4i8, MVT::v4i32, 3 },
1617 { ISD::TRUNCATE, MVT::v4i16, MVT::v4i32, 3 },
1618 { ISD::TRUNCATE, MVT::v8i8, MVT::v8i32, 4 },
1619 { ISD::TRUNCATE, MVT::v16i8, MVT::v16i32, 7 },
1620 { ISD::TRUNCATE, MVT::v8i16, MVT::v8i32, 5 },
1621 { ISD::TRUNCATE, MVT::v16i16, MVT::v16i32, 10 },
1622 { ISD::TRUNCATE, MVT::v2i8, MVT::v2i64, 4 }, // PAND+3*PACKUSWB
1623 { ISD::TRUNCATE, MVT::v2i16, MVT::v2i64, 2 }, // PSHUFD+PSHUFLW
1624 { ISD::TRUNCATE, MVT::v2i32, MVT::v2i64, 1 }, // PSHUFD
1625 };
1626
1627 std::pair<int, MVT> LTSrc = TLI->getTypeLegalizationCost(DL, Src);
1628 std::pair<int, MVT> LTDest = TLI->getTypeLegalizationCost(DL, Dst);
1629
1630 if (ST->hasSSE2() && !ST->hasAVX()) {
1631 if (const auto *Entry = ConvertCostTableLookup(SSE2ConversionTbl, ISD,
1632 LTDest.second, LTSrc.second))
1633 return LTSrc.first * Entry->Cost;
1634 }
1635
1636 EVT SrcTy = TLI->getValueType(DL, Src);
1637 EVT DstTy = TLI->getValueType(DL, Dst);
1638
1639 // The function getSimpleVT only handles simple value types.
1640 if (!SrcTy.isSimple() || !DstTy.isSimple())
1641 return BaseT::getCastInstrCost(Opcode, Dst, Src);
1642
1643 MVT SimpleSrcTy = SrcTy.getSimpleVT();
1644 MVT SimpleDstTy = DstTy.getSimpleVT();
1645
1646 // Make sure that neither type is going to be split before using the
1647 // AVX512 tables. This handles -mprefer-vector-width=256
1648 // with -min-legal-vector-width<=256
1649 if (TLI->getTypeAction(SimpleSrcTy) != TargetLowering::TypeSplitVector &&
1650 TLI->getTypeAction(SimpleDstTy) != TargetLowering::TypeSplitVector) {
1651 if (ST->hasBWI())
1652 if (const auto *Entry = ConvertCostTableLookup(AVX512BWConversionTbl, ISD,
1653 SimpleDstTy, SimpleSrcTy))
1654 return Entry->Cost;
1655
1656 if (ST->hasDQI())
1657 if (const auto *Entry = ConvertCostTableLookup(AVX512DQConversionTbl, ISD,
1658 SimpleDstTy, SimpleSrcTy))
1659 return Entry->Cost;
1660
1661 if (ST->hasAVX512())
1662 if (const auto *Entry = ConvertCostTableLookup(AVX512FConversionTbl, ISD,
1663 SimpleDstTy, SimpleSrcTy))
1664 return Entry->Cost;
1665 }
1666
1667 if (ST->hasAVX2()) {
1668 if (const auto *Entry = ConvertCostTableLookup(AVX2ConversionTbl, ISD,
1669 SimpleDstTy, SimpleSrcTy))
1670 return Entry->Cost;
1671 }
1672
1673 if (ST->hasAVX()) {
1674 if (const auto *Entry = ConvertCostTableLookup(AVXConversionTbl, ISD,
1675 SimpleDstTy, SimpleSrcTy))
1676 return Entry->Cost;
1677 }
1678
1679 if (ST->hasSSE41()) {
1680 if (const auto *Entry = ConvertCostTableLookup(SSE41ConversionTbl, ISD,
1681 SimpleDstTy, SimpleSrcTy))
1682 return Entry->Cost;
1683 }
1684
1685 if (ST->hasSSE2()) {
1686 if (const auto *Entry = ConvertCostTableLookup(SSE2ConversionTbl, ISD,
1687 SimpleDstTy, SimpleSrcTy))
1688 return Entry->Cost;
1689 }
1690
1691 return BaseT::getCastInstrCost(Opcode, Dst, Src, I);
1692}
1693
1694int X86TTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
1695 const Instruction *I) {
1696 // Legalize the type.
1697 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
1698
1699 MVT MTy = LT.second;
1700
1701 int ISD = TLI->InstructionOpcodeToISD(Opcode);
1702 assert(ISD && "Invalid opcode")((ISD && "Invalid opcode") ? static_cast<void> (
0) : __assert_fail ("ISD && \"Invalid opcode\"", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 1702, __PRETTY_FUNCTION__))
;
1703
1704 unsigned ExtraCost = 0;
1705 if (I && (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp)) {
1706 // Some vector comparison predicates cost extra instructions.
1707 if (MTy.isVector() &&
1708 !((ST->hasXOP() && (!ST->hasAVX2() || MTy.is128BitVector())) ||
1709 (ST->hasAVX512() && 32 <= MTy.getScalarSizeInBits()) ||
1710 ST->hasBWI())) {
1711 switch (cast<CmpInst>(I)->getPredicate()) {
1712 case CmpInst::Predicate::ICMP_NE:
1713 // xor(cmpeq(x,y),-1)
1714 ExtraCost = 1;
1715 break;
1716 case CmpInst::Predicate::ICMP_SGE:
1717 case CmpInst::Predicate::ICMP_SLE:
1718 // xor(cmpgt(x,y),-1)
1719 ExtraCost = 1;
1720 break;
1721 case CmpInst::Predicate::ICMP_ULT:
1722 case CmpInst::Predicate::ICMP_UGT:
1723 // cmpgt(xor(x,signbit),xor(y,signbit))
1724 // xor(cmpeq(pmaxu(x,y),x),-1)
1725 ExtraCost = 2;
1726 break;
1727 case CmpInst::Predicate::ICMP_ULE:
1728 case CmpInst::Predicate::ICMP_UGE:
1729 if ((ST->hasSSE41() && MTy.getScalarSizeInBits() == 32) ||
1730 (ST->hasSSE2() && MTy.getScalarSizeInBits() < 32)) {
1731 // cmpeq(psubus(x,y),0)
1732 // cmpeq(pminu(x,y),x)
1733 ExtraCost = 1;
1734 } else {
1735 // xor(cmpgt(xor(x,signbit),xor(y,signbit)),-1)
1736 ExtraCost = 3;
1737 }
1738 break;
1739 default:
1740 break;
1741 }
1742 }
1743 }
1744
1745 static const CostTblEntry SLMCostTbl[] = {
1746 // slm pcmpeq/pcmpgt throughput is 2
1747 { ISD::SETCC, MVT::v2i64, 2 },
1748 };
1749
1750 static const CostTblEntry AVX512BWCostTbl[] = {
1751 { ISD::SETCC, MVT::v32i16, 1 },
1752 { ISD::SETCC, MVT::v64i8, 1 },
1753
1754 { ISD::SELECT, MVT::v32i16, 1 },
1755 { ISD::SELECT, MVT::v64i8, 1 },
1756 };
1757
1758 static const CostTblEntry AVX512CostTbl[] = {
1759 { ISD::SETCC, MVT::v8i64, 1 },
1760 { ISD::SETCC, MVT::v16i32, 1 },
1761 { ISD::SETCC, MVT::v8f64, 1 },
1762 { ISD::SETCC, MVT::v16f32, 1 },
1763
1764 { ISD::SELECT, MVT::v8i64, 1 },
1765 { ISD::SELECT, MVT::v16i32, 1 },
1766 { ISD::SELECT, MVT::v8f64, 1 },
1767 { ISD::SELECT, MVT::v16f32, 1 },
1768 };
1769
1770 static const CostTblEntry AVX2CostTbl[] = {
1771 { ISD::SETCC, MVT::v4i64, 1 },
1772 { ISD::SETCC, MVT::v8i32, 1 },
1773 { ISD::SETCC, MVT::v16i16, 1 },
1774 { ISD::SETCC, MVT::v32i8, 1 },
1775
1776 { ISD::SELECT, MVT::v4i64, 1 }, // pblendvb
1777 { ISD::SELECT, MVT::v8i32, 1 }, // pblendvb
1778 { ISD::SELECT, MVT::v16i16, 1 }, // pblendvb
1779 { ISD::SELECT, MVT::v32i8, 1 }, // pblendvb
1780 };
1781
1782 static const CostTblEntry AVX1CostTbl[] = {
1783 { ISD::SETCC, MVT::v4f64, 1 },
1784 { ISD::SETCC, MVT::v8f32, 1 },
1785 // AVX1 does not support 8-wide integer compare.
1786 { ISD::SETCC, MVT::v4i64, 4 },
1787 { ISD::SETCC, MVT::v8i32, 4 },
1788 { ISD::SETCC, MVT::v16i16, 4 },
1789 { ISD::SETCC, MVT::v32i8, 4 },
1790
1791 { ISD::SELECT, MVT::v4f64, 1 }, // vblendvpd
1792 { ISD::SELECT, MVT::v8f32, 1 }, // vblendvps
1793 { ISD::SELECT, MVT::v4i64, 1 }, // vblendvpd
1794 { ISD::SELECT, MVT::v8i32, 1 }, // vblendvps
1795 { ISD::SELECT, MVT::v16i16, 3 }, // vandps + vandnps + vorps
1796 { ISD::SELECT, MVT::v32i8, 3 }, // vandps + vandnps + vorps
1797 };
1798
1799 static const CostTblEntry SSE42CostTbl[] = {
1800 { ISD::SETCC, MVT::v2f64, 1 },
1801 { ISD::SETCC, MVT::v4f32, 1 },
1802 { ISD::SETCC, MVT::v2i64, 1 },
1803 };
1804
1805 static const CostTblEntry SSE41CostTbl[] = {
1806 { ISD::SELECT, MVT::v2f64, 1 }, // blendvpd
1807 { ISD::SELECT, MVT::v4f32, 1 }, // blendvps
1808 { ISD::SELECT, MVT::v2i64, 1 }, // pblendvb
1809 { ISD::SELECT, MVT::v4i32, 1 }, // pblendvb
1810 { ISD::SELECT, MVT::v8i16, 1 }, // pblendvb
1811 { ISD::SELECT, MVT::v16i8, 1 }, // pblendvb
1812 };
1813
1814 static const CostTblEntry SSE2CostTbl[] = {
1815 { ISD::SETCC, MVT::v2f64, 2 },
1816 { ISD::SETCC, MVT::f64, 1 },
1817 { ISD::SETCC, MVT::v2i64, 8 },
1818 { ISD::SETCC, MVT::v4i32, 1 },
1819 { ISD::SETCC, MVT::v8i16, 1 },
1820 { ISD::SETCC, MVT::v16i8, 1 },
1821
1822 { ISD::SELECT, MVT::v2f64, 3 }, // andpd + andnpd + orpd
1823 { ISD::SELECT, MVT::v2i64, 3 }, // pand + pandn + por
1824 { ISD::SELECT, MVT::v4i32, 3 }, // pand + pandn + por
1825 { ISD::SELECT, MVT::v8i16, 3 }, // pand + pandn + por
1826 { ISD::SELECT, MVT::v16i8, 3 }, // pand + pandn + por
1827 };
1828
1829 static const CostTblEntry SSE1CostTbl[] = {
1830 { ISD::SETCC, MVT::v4f32, 2 },
1831 { ISD::SETCC, MVT::f32, 1 },
1832
1833 { ISD::SELECT, MVT::v4f32, 3 }, // andps + andnps + orps
1834 };
1835
1836 if (ST->isSLM())
1837 if (const auto *Entry = CostTableLookup(SLMCostTbl, ISD, MTy))
1838 return LT.first * (ExtraCost + Entry->Cost);
1839
1840 if (ST->hasBWI())
1841 if (const auto *Entry = CostTableLookup(AVX512BWCostTbl, ISD, MTy))
1842 return LT.first * (ExtraCost + Entry->Cost);
1843
1844 if (ST->hasAVX512())
1845 if (const auto *Entry = CostTableLookup(AVX512CostTbl, ISD, MTy))
1846 return LT.first * (ExtraCost + Entry->Cost);
1847
1848 if (ST->hasAVX2())
1849 if (const auto *Entry = CostTableLookup(AVX2CostTbl, ISD, MTy))
1850 return LT.first * (ExtraCost + Entry->Cost);
1851
1852 if (ST->hasAVX())
1853 if (const auto *Entry = CostTableLookup(AVX1CostTbl, ISD, MTy))
1854 return LT.first * (ExtraCost + Entry->Cost);
1855
1856 if (ST->hasSSE42())
1857 if (const auto *Entry = CostTableLookup(SSE42CostTbl, ISD, MTy))
1858 return LT.first * (ExtraCost + Entry->Cost);
1859
1860 if (ST->hasSSE41())
1861 if (const auto *Entry = CostTableLookup(SSE41CostTbl, ISD, MTy))
1862 return LT.first * (ExtraCost + Entry->Cost);
1863
1864 if (ST->hasSSE2())
1865 if (const auto *Entry = CostTableLookup(SSE2CostTbl, ISD, MTy))
1866 return LT.first * (ExtraCost + Entry->Cost);
1867
1868 if (ST->hasSSE1())
1869 if (const auto *Entry = CostTableLookup(SSE1CostTbl, ISD, MTy))
1870 return LT.first * (ExtraCost + Entry->Cost);
1871
1872 return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, I);
1873}
1874
1875unsigned X86TTIImpl::getAtomicMemIntrinsicMaxElementSize() const { return 16; }
1876
1877int X86TTIImpl::getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
1878 ArrayRef<Type *> Tys, FastMathFlags FMF,
1879 unsigned ScalarizationCostPassed) {
1880 // Costs should match the codegen from:
1881 // BITREVERSE: llvm\test\CodeGen\X86\vector-bitreverse.ll
1882 // BSWAP: llvm\test\CodeGen\X86\bswap-vector.ll
1883 // CTLZ: llvm\test\CodeGen\X86\vector-lzcnt-*.ll
1884 // CTPOP: llvm\test\CodeGen\X86\vector-popcnt-*.ll
1885 // CTTZ: llvm\test\CodeGen\X86\vector-tzcnt-*.ll
1886 static const CostTblEntry AVX512CDCostTbl[] = {
1887 { ISD::CTLZ, MVT::v8i64, 1 },
1888 { ISD::CTLZ, MVT::v16i32, 1 },
1889 { ISD::CTLZ, MVT::v32i16, 8 },
1890 { ISD::CTLZ, MVT::v64i8, 20 },
1891 { ISD::CTLZ, MVT::v4i64, 1 },
1892 { ISD::CTLZ, MVT::v8i32, 1 },
1893 { ISD::CTLZ, MVT::v16i16, 4 },
1894 { ISD::CTLZ, MVT::v32i8, 10 },
1895 { ISD::CTLZ, MVT::v2i64, 1 },
1896 { ISD::CTLZ, MVT::v4i32, 1 },
1897 { ISD::CTLZ, MVT::v8i16, 4 },
1898 { ISD::CTLZ, MVT::v16i8, 4 },
1899 };
1900 static const CostTblEntry AVX512BWCostTbl[] = {
1901 { ISD::BITREVERSE, MVT::v8i64, 5 },
1902 { ISD::BITREVERSE, MVT::v16i32, 5 },
1903 { ISD::BITREVERSE, MVT::v32i16, 5 },
1904 { ISD::BITREVERSE, MVT::v64i8, 5 },
1905 { ISD::CTLZ, MVT::v8i64, 23 },
1906 { ISD::CTLZ, MVT::v16i32, 22 },
1907 { ISD::CTLZ, MVT::v32i16, 18 },
1908 { ISD::CTLZ, MVT::v64i8, 17 },
1909 { ISD::CTPOP, MVT::v8i64, 7 },
1910 { ISD::CTPOP, MVT::v16i32, 11 },
1911 { ISD::CTPOP, MVT::v32i16, 9 },
1912 { ISD::CTPOP, MVT::v64i8, 6 },
1913 { ISD::CTTZ, MVT::v8i64, 10 },
1914 { ISD::CTTZ, MVT::v16i32, 14 },
1915 { ISD::CTTZ, MVT::v32i16, 12 },
1916 { ISD::CTTZ, MVT::v64i8, 9 },
1917 { ISD::SADDSAT, MVT::v32i16, 1 },
1918 { ISD::SADDSAT, MVT::v64i8, 1 },
1919 { ISD::SSUBSAT, MVT::v32i16, 1 },
1920 { ISD::SSUBSAT, MVT::v64i8, 1 },
1921 { ISD::UADDSAT, MVT::v32i16, 1 },
1922 { ISD::UADDSAT, MVT::v64i8, 1 },
1923 { ISD::USUBSAT, MVT::v32i16, 1 },
1924 { ISD::USUBSAT, MVT::v64i8, 1 },
1925 };
1926 static const CostTblEntry AVX512CostTbl[] = {
1927 { ISD::BITREVERSE, MVT::v8i64, 36 },
1928 { ISD::BITREVERSE, MVT::v16i32, 24 },
1929 { ISD::CTLZ, MVT::v8i64, 29 },
1930 { ISD::CTLZ, MVT::v16i32, 35 },
1931 { ISD::CTPOP, MVT::v8i64, 16 },
1932 { ISD::CTPOP, MVT::v16i32, 24 },
1933 { ISD::CTTZ, MVT::v8i64, 20 },
1934 { ISD::CTTZ, MVT::v16i32, 28 },
1935 { ISD::USUBSAT, MVT::v16i32, 2 }, // pmaxud + psubd
1936 { ISD::USUBSAT, MVT::v2i64, 2 }, // pmaxuq + psubq
1937 { ISD::USUBSAT, MVT::v4i64, 2 }, // pmaxuq + psubq
1938 { ISD::USUBSAT, MVT::v8i64, 2 }, // pmaxuq + psubq
1939 { ISD::UADDSAT, MVT::v16i32, 3 }, // not + pminud + paddd
1940 { ISD::UADDSAT, MVT::v2i64, 3 }, // not + pminuq + paddq
1941 { ISD::UADDSAT, MVT::v4i64, 3 }, // not + pminuq + paddq
1942 { ISD::UADDSAT, MVT::v8i64, 3 }, // not + pminuq + paddq
1943 };
1944 static const CostTblEntry XOPCostTbl[] = {
1945 { ISD::BITREVERSE, MVT::v4i64, 4 },
1946 { ISD::BITREVERSE, MVT::v8i32, 4 },
1947 { ISD::BITREVERSE, MVT::v16i16, 4 },
1948 { ISD::BITREVERSE, MVT::v32i8, 4 },
1949 { ISD::BITREVERSE, MVT::v2i64, 1 },
1950 { ISD::BITREVERSE, MVT::v4i32, 1 },
1951 { ISD::BITREVERSE, MVT::v8i16, 1 },
1952 { ISD::BITREVERSE, MVT::v16i8, 1 },
1953 { ISD::BITREVERSE, MVT::i64, 3 },
1954 { ISD::BITREVERSE, MVT::i32, 3 },
1955 { ISD::BITREVERSE, MVT::i16, 3 },
1956 { ISD::BITREVERSE, MVT::i8, 3 }
1957 };
1958 static const CostTblEntry AVX2CostTbl[] = {
1959 { ISD::BITREVERSE, MVT::v4i64, 5 },
1960 { ISD::BITREVERSE, MVT::v8i32, 5 },
1961 { ISD::BITREVERSE, MVT::v16i16, 5 },
1962 { ISD::BITREVERSE, MVT::v32i8, 5 },
1963 { ISD::BSWAP, MVT::v4i64, 1 },
1964 { ISD::BSWAP, MVT::v8i32, 1 },
1965 { ISD::BSWAP, MVT::v16i16, 1 },
1966 { ISD::CTLZ, MVT::v4i64, 23 },
1967 { ISD::CTLZ, MVT::v8i32, 18 },
1968 { ISD::CTLZ, MVT::v16i16, 14 },
1969 { ISD::CTLZ, MVT::v32i8, 9 },
1970 { ISD::CTPOP, MVT::v4i64, 7 },
1971 { ISD::CTPOP, MVT::v8i32, 11 },
1972 { ISD::CTPOP, MVT::v16i16, 9 },
1973 { ISD::CTPOP, MVT::v32i8, 6 },
1974 { ISD::CTTZ, MVT::v4i64, 10 },
1975 { ISD::CTTZ, MVT::v8i32, 14 },
1976 { ISD::CTTZ, MVT::v16i16, 12 },
1977 { ISD::CTTZ, MVT::v32i8, 9 },
1978 { ISD::SADDSAT, MVT::v16i16, 1 },
1979 { ISD::SADDSAT, MVT::v32i8, 1 },
1980 { ISD::SSUBSAT, MVT::v16i16, 1 },
1981 { ISD::SSUBSAT, MVT::v32i8, 1 },
1982 { ISD::UADDSAT, MVT::v16i16, 1 },
1983 { ISD::UADDSAT, MVT::v32i8, 1 },
1984 { ISD::UADDSAT, MVT::v8i32, 3 }, // not + pminud + paddd
1985 { ISD::USUBSAT, MVT::v16i16, 1 },
1986 { ISD::USUBSAT, MVT::v32i8, 1 },
1987 { ISD::USUBSAT, MVT::v8i32, 2 }, // pmaxud + psubd
1988 { ISD::FSQRT, MVT::f32, 7 }, // Haswell from http://www.agner.org/
1989 { ISD::FSQRT, MVT::v4f32, 7 }, // Haswell from http://www.agner.org/
1990 { ISD::FSQRT, MVT::v8f32, 14 }, // Haswell from http://www.agner.org/
1991 { ISD::FSQRT, MVT::f64, 14 }, // Haswell from http://www.agner.org/
1992 { ISD::FSQRT, MVT::v2f64, 14 }, // Haswell from http://www.agner.org/
1993 { ISD::FSQRT, MVT::v4f64, 28 }, // Haswell from http://www.agner.org/
1994 };
1995 static const CostTblEntry AVX1CostTbl[] = {
1996 { ISD::BITREVERSE, MVT::v4i64, 12 }, // 2 x 128-bit Op + extract/insert
1997 { ISD::BITREVERSE, MVT::v8i32, 12 }, // 2 x 128-bit Op + extract/insert
1998 { ISD::BITREVERSE, MVT::v16i16, 12 }, // 2 x 128-bit Op + extract/insert
1999 { ISD::BITREVERSE, MVT::v32i8, 12 }, // 2 x 128-bit Op + extract/insert
2000 { ISD::BSWAP, MVT::v4i64, 4 },
2001 { ISD::BSWAP, MVT::v8i32, 4 },
2002 { ISD::BSWAP, MVT::v16i16, 4 },
2003 { ISD::CTLZ, MVT::v4i64, 48 }, // 2 x 128-bit Op + extract/insert
2004 { ISD::CTLZ, MVT::v8i32, 38 }, // 2 x 128-bit Op + extract/insert
2005 { ISD::CTLZ, MVT::v16i16, 30 }, // 2 x 128-bit Op + extract/insert
2006 { ISD::CTLZ, MVT::v32i8, 20 }, // 2 x 128-bit Op + extract/insert
2007 { ISD::CTPOP, MVT::v4i64, 16 }, // 2 x 128-bit Op + extract/insert
2008 { ISD::CTPOP, MVT::v8i32, 24 }, // 2 x 128-bit Op + extract/insert
2009 { ISD::CTPOP, MVT::v16i16, 20 }, // 2 x 128-bit Op + extract/insert
2010 { ISD::CTPOP, MVT::v32i8, 14 }, // 2 x 128-bit Op + extract/insert
2011 { ISD::CTTZ, MVT::v4i64, 22 }, // 2 x 128-bit Op + extract/insert
2012 { ISD::CTTZ, MVT::v8i32, 30 }, // 2 x 128-bit Op + extract/insert
2013 { ISD::CTTZ, MVT::v16i16, 26 }, // 2 x 128-bit Op + extract/insert
2014 { ISD::CTTZ, MVT::v32i8, 20 }, // 2 x 128-bit Op + extract/insert
2015 { ISD::SADDSAT, MVT::v16i16, 4 }, // 2 x 128-bit Op + extract/insert
2016 { ISD::SADDSAT, MVT::v32i8, 4 }, // 2 x 128-bit Op + extract/insert
2017 { ISD::SSUBSAT, MVT::v16i16, 4 }, // 2 x 128-bit Op + extract/insert
2018 { ISD::SSUBSAT, MVT::v32i8, 4 }, // 2 x 128-bit Op + extract/insert
2019 { ISD::UADDSAT, MVT::v16i16, 4 }, // 2 x 128-bit Op + extract/insert
2020 { ISD::UADDSAT, MVT::v32i8, 4 }, // 2 x 128-bit Op + extract/insert
2021 { ISD::UADDSAT, MVT::v8i32, 8 }, // 2 x 128-bit Op + extract/insert
2022 { ISD::USUBSAT, MVT::v16i16, 4 }, // 2 x 128-bit Op + extract/insert
2023 { ISD::USUBSAT, MVT::v32i8, 4 }, // 2 x 128-bit Op + extract/insert
2024 { ISD::USUBSAT, MVT::v8i32, 6 }, // 2 x 128-bit Op + extract/insert
2025 { ISD::FSQRT, MVT::f32, 14 }, // SNB from http://www.agner.org/
2026 { ISD::FSQRT, MVT::v4f32, 14 }, // SNB from http://www.agner.org/
2027 { ISD::FSQRT, MVT::v8f32, 28 }, // SNB from http://www.agner.org/
2028 { ISD::FSQRT, MVT::f64, 21 }, // SNB from http://www.agner.org/
2029 { ISD::FSQRT, MVT::v2f64, 21 }, // SNB from http://www.agner.org/
2030 { ISD::FSQRT, MVT::v4f64, 43 }, // SNB from http://www.agner.org/
2031 };
2032 static const CostTblEntry GLMCostTbl[] = {
2033 { ISD::FSQRT, MVT::f32, 19 }, // sqrtss
2034 { ISD::FSQRT, MVT::v4f32, 37 }, // sqrtps
2035 { ISD::FSQRT, MVT::f64, 34 }, // sqrtsd
2036 { ISD::FSQRT, MVT::v2f64, 67 }, // sqrtpd
2037 };
2038 static const CostTblEntry SLMCostTbl[] = {
2039 { ISD::FSQRT, MVT::f32, 20 }, // sqrtss
2040 { ISD::FSQRT, MVT::v4f32, 40 }, // sqrtps
2041 { ISD::FSQRT, MVT::f64, 35 }, // sqrtsd
2042 { ISD::FSQRT, MVT::v2f64, 70 }, // sqrtpd
2043 };
2044 static const CostTblEntry SSE42CostTbl[] = {
2045 { ISD::USUBSAT, MVT::v4i32, 2 }, // pmaxud + psubd
2046 { ISD::UADDSAT, MVT::v4i32, 3 }, // not + pminud + paddd
2047 { ISD::FSQRT, MVT::f32, 18 }, // Nehalem from http://www.agner.org/
2048 { ISD::FSQRT, MVT::v4f32, 18 }, // Nehalem from http://www.agner.org/
2049 };
2050 static const CostTblEntry SSSE3CostTbl[] = {
2051 { ISD::BITREVERSE, MVT::v2i64, 5 },
2052 { ISD::BITREVERSE, MVT::v4i32, 5 },
2053 { ISD::BITREVERSE, MVT::v8i16, 5 },
2054 { ISD::BITREVERSE, MVT::v16i8, 5 },
2055 { ISD::BSWAP, MVT::v2i64, 1 },
2056 { ISD::BSWAP, MVT::v4i32, 1 },
2057 { ISD::BSWAP, MVT::v8i16, 1 },
2058 { ISD::CTLZ, MVT::v2i64, 23 },
2059 { ISD::CTLZ, MVT::v4i32, 18 },
2060 { ISD::CTLZ, MVT::v8i16, 14 },
2061 { ISD::CTLZ, MVT::v16i8, 9 },
2062 { ISD::CTPOP, MVT::v2i64, 7 },
2063 { ISD::CTPOP, MVT::v4i32, 11 },
2064 { ISD::CTPOP, MVT::v8i16, 9 },
2065 { ISD::CTPOP, MVT::v16i8, 6 },
2066 { ISD::CTTZ, MVT::v2i64, 10 },
2067 { ISD::CTTZ, MVT::v4i32, 14 },
2068 { ISD::CTTZ, MVT::v8i16, 12 },
2069 { ISD::CTTZ, MVT::v16i8, 9 }
2070 };
2071 static const CostTblEntry SSE2CostTbl[] = {
2072 { ISD::BITREVERSE, MVT::v2i64, 29 },
2073 { ISD::BITREVERSE, MVT::v4i32, 27 },
2074 { ISD::BITREVERSE, MVT::v8i16, 27 },
2075 { ISD::BITREVERSE, MVT::v16i8, 20 },
2076 { ISD::BSWAP, MVT::v2i64, 7 },
2077 { ISD::BSWAP, MVT::v4i32, 7 },
2078 { ISD::BSWAP, MVT::v8i16, 7 },
2079 { ISD::CTLZ, MVT::v2i64, 25 },
2080 { ISD::CTLZ, MVT::v4i32, 26 },
2081 { ISD::CTLZ, MVT::v8i16, 20 },
2082 { ISD::CTLZ, MVT::v16i8, 17 },
2083 { ISD::CTPOP, MVT::v2i64, 12 },
2084 { ISD::CTPOP, MVT::v4i32, 15 },
2085 { ISD::CTPOP, MVT::v8i16, 13 },
2086 { ISD::CTPOP, MVT::v16i8, 10 },
2087 { ISD::CTTZ, MVT::v2i64, 14 },
2088 { ISD::CTTZ, MVT::v4i32, 18 },
2089 { ISD::CTTZ, MVT::v8i16, 16 },
2090 { ISD::CTTZ, MVT::v16i8, 13 },
2091 { ISD::SADDSAT, MVT::v8i16, 1 },
2092 { ISD::SADDSAT, MVT::v16i8, 1 },
2093 { ISD::SSUBSAT, MVT::v8i16, 1 },
2094 { ISD::SSUBSAT, MVT::v16i8, 1 },
2095 { ISD::UADDSAT, MVT::v8i16, 1 },
2096 { ISD::UADDSAT, MVT::v16i8, 1 },
2097 { ISD::USUBSAT, MVT::v8i16, 1 },
2098 { ISD::USUBSAT, MVT::v16i8, 1 },
2099 { ISD::FSQRT, MVT::f64, 32 }, // Nehalem from http://www.agner.org/
2100 { ISD::FSQRT, MVT::v2f64, 32 }, // Nehalem from http://www.agner.org/
2101 };
2102 static const CostTblEntry SSE1CostTbl[] = {
2103 { ISD::FSQRT, MVT::f32, 28 }, // Pentium III from http://www.agner.org/
2104 { ISD::FSQRT, MVT::v4f32, 56 }, // Pentium III from http://www.agner.org/
2105 };
2106 static const CostTblEntry LZCNT64CostTbl[] = { // 64-bit targets
2107 { ISD::CTLZ, MVT::i64, 1 },
2108 };
2109 static const CostTblEntry LZCNT32CostTbl[] = { // 32 or 64-bit targets
2110 { ISD::CTLZ, MVT::i32, 1 },
2111 { ISD::CTLZ, MVT::i16, 1 },
2112 { ISD::CTLZ, MVT::i8, 1 },
2113 };
2114 static const CostTblEntry POPCNT64CostTbl[] = { // 64-bit targets
2115 { ISD::CTPOP, MVT::i64, 1 },
2116 };
2117 static const CostTblEntry POPCNT32CostTbl[] = { // 32 or 64-bit targets
2118 { ISD::CTPOP, MVT::i32, 1 },
2119 { ISD::CTPOP, MVT::i16, 1 },
2120 { ISD::CTPOP, MVT::i8, 1 },
2121 };
2122 static const CostTblEntry X64CostTbl[] = { // 64-bit targets
2123 { ISD::BITREVERSE, MVT::i64, 14 },
2124 { ISD::CTLZ, MVT::i64, 4 }, // BSR+XOR or BSR+XOR+CMOV
2125 { ISD::CTPOP, MVT::i64, 10 },
2126 { ISD::SADDO, MVT::i64, 1 },
2127 { ISD::UADDO, MVT::i64, 1 },
2128 };
2129 static const CostTblEntry X86CostTbl[] = { // 32 or 64-bit targets
2130 { ISD::BITREVERSE, MVT::i32, 14 },
2131 { ISD::BITREVERSE, MVT::i16, 14 },
2132 { ISD::BITREVERSE, MVT::i8, 11 },
2133 { ISD::CTLZ, MVT::i32, 4 }, // BSR+XOR or BSR+XOR+CMOV
2134 { ISD::CTLZ, MVT::i16, 4 }, // BSR+XOR or BSR+XOR+CMOV
2135 { ISD::CTLZ, MVT::i8, 4 }, // BSR+XOR or BSR+XOR+CMOV
2136 { ISD::CTPOP, MVT::i32, 8 },
2137 { ISD::CTPOP, MVT::i16, 9 },
2138 { ISD::CTPOP, MVT::i8, 7 },
2139 { ISD::SADDO, MVT::i32, 1 },
2140 { ISD::SADDO, MVT::i16, 1 },
2141 { ISD::SADDO, MVT::i8, 1 },
2142 { ISD::UADDO, MVT::i32, 1 },
2143 { ISD::UADDO, MVT::i16, 1 },
2144 { ISD::UADDO, MVT::i8, 1 },
2145 };
2146
2147 Type *OpTy = RetTy;
2148 unsigned ISD = ISD::DELETED_NODE;
2149 switch (IID) {
2150 default:
2151 break;
2152 case Intrinsic::bitreverse:
2153 ISD = ISD::BITREVERSE;
2154 break;
2155 case Intrinsic::bswap:
2156 ISD = ISD::BSWAP;
2157 break;
2158 case Intrinsic::ctlz:
2159 ISD = ISD::CTLZ;
2160 break;
2161 case Intrinsic::ctpop:
2162 ISD = ISD::CTPOP;
2163 break;
2164 case Intrinsic::cttz:
2165 ISD = ISD::CTTZ;
2166 break;
2167 case Intrinsic::sadd_sat:
2168 ISD = ISD::SADDSAT;
2169 break;
2170 case Intrinsic::ssub_sat:
2171 ISD = ISD::SSUBSAT;
2172 break;
2173 case Intrinsic::uadd_sat:
2174 ISD = ISD::UADDSAT;
2175 break;
2176 case Intrinsic::usub_sat:
2177 ISD = ISD::USUBSAT;
2178 break;
2179 case Intrinsic::sqrt:
2180 ISD = ISD::FSQRT;
2181 break;
2182 case Intrinsic::sadd_with_overflow:
2183 case Intrinsic::ssub_with_overflow:
2184 // SSUBO has same costs so don't duplicate.
2185 ISD = ISD::SADDO;
2186 OpTy = RetTy->getContainedType(0);
2187 break;
2188 case Intrinsic::uadd_with_overflow:
2189 case Intrinsic::usub_with_overflow:
2190 // USUBO has same costs so don't duplicate.
2191 ISD = ISD::UADDO;
2192 OpTy = RetTy->getContainedType(0);
2193 break;
2194 }
2195
2196 if (ISD != ISD::DELETED_NODE) {
2197 // Legalize the type.
2198 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, OpTy);
2199 MVT MTy = LT.second;
2200
2201 // Attempt to lookup cost.
2202 if (ST->isGLM())
2203 if (const auto *Entry = CostTableLookup(GLMCostTbl, ISD, MTy))
2204 return LT.first * Entry->Cost;
2205
2206 if (ST->isSLM())
2207 if (const auto *Entry = CostTableLookup(SLMCostTbl, ISD, MTy))
2208 return LT.first * Entry->Cost;
2209
2210 if (ST->hasCDI())
2211 if (const auto *Entry = CostTableLookup(AVX512CDCostTbl, ISD, MTy))
2212 return LT.first * Entry->Cost;
2213
2214 if (ST->hasBWI())
2215 if (const auto *Entry = CostTableLookup(AVX512BWCostTbl, ISD, MTy))
2216 return LT.first * Entry->Cost;
2217
2218 if (ST->hasAVX512())
2219 if (const auto *Entry = CostTableLookup(AVX512CostTbl, ISD, MTy))
2220 return LT.first * Entry->Cost;
2221
2222 if (ST->hasXOP())
2223 if (const auto *Entry = CostTableLookup(XOPCostTbl, ISD, MTy))
2224 return LT.first * Entry->Cost;
2225
2226 if (ST->hasAVX2())
2227 if (const auto *Entry = CostTableLookup(AVX2CostTbl, ISD, MTy))
2228 return LT.first * Entry->Cost;
2229
2230 if (ST->hasAVX())
2231 if (const auto *Entry = CostTableLookup(AVX1CostTbl, ISD, MTy))
2232 return LT.first * Entry->Cost;
2233
2234 if (ST->hasSSE42())
2235 if (const auto *Entry = CostTableLookup(SSE42CostTbl, ISD, MTy))
2236 return LT.first * Entry->Cost;
2237
2238 if (ST->hasSSSE3())
2239 if (const auto *Entry = CostTableLookup(SSSE3CostTbl, ISD, MTy))
2240 return LT.first * Entry->Cost;
2241
2242 if (ST->hasSSE2())
2243 if (const auto *Entry = CostTableLookup(SSE2CostTbl, ISD, MTy))
2244 return LT.first * Entry->Cost;
2245
2246 if (ST->hasSSE1())
2247 if (const auto *Entry = CostTableLookup(SSE1CostTbl, ISD, MTy))
2248 return LT.first * Entry->Cost;
2249
2250 if (ST->hasLZCNT()) {
2251 if (ST->is64Bit())
2252 if (const auto *Entry = CostTableLookup(LZCNT64CostTbl, ISD, MTy))
2253 return LT.first * Entry->Cost;
2254
2255 if (const auto *Entry = CostTableLookup(LZCNT32CostTbl, ISD, MTy))
2256 return LT.first * Entry->Cost;
2257 }
2258
2259 if (ST->hasPOPCNT()) {
2260 if (ST->is64Bit())
2261 if (const auto *Entry = CostTableLookup(POPCNT64CostTbl, ISD, MTy))
2262 return LT.first * Entry->Cost;
2263
2264 if (const auto *Entry = CostTableLookup(POPCNT32CostTbl, ISD, MTy))
2265 return LT.first * Entry->Cost;
2266 }
2267
2268 // TODO - add BMI (TZCNT) scalar handling
2269
2270 if (ST->is64Bit())
2271 if (const auto *Entry = CostTableLookup(X64CostTbl, ISD, MTy))
2272 return LT.first * Entry->Cost;
2273
2274 if (const auto *Entry = CostTableLookup(X86CostTbl, ISD, MTy))
2275 return LT.first * Entry->Cost;
2276 }
2277
2278 return BaseT::getIntrinsicInstrCost(IID, RetTy, Tys, FMF, ScalarizationCostPassed);
2279}
2280
2281int X86TTIImpl::getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
2282 ArrayRef<Value *> Args, FastMathFlags FMF,
2283 unsigned VF) {
2284 static const CostTblEntry AVX512CostTbl[] = {
2285 { ISD::ROTL, MVT::v8i64, 1 },
2286 { ISD::ROTL, MVT::v4i64, 1 },
2287 { ISD::ROTL, MVT::v2i64, 1 },
2288 { ISD::ROTL, MVT::v16i32, 1 },
2289 { ISD::ROTL, MVT::v8i32, 1 },
2290 { ISD::ROTL, MVT::v4i32, 1 },
2291 { ISD::ROTR, MVT::v8i64, 1 },
2292 { ISD::ROTR, MVT::v4i64, 1 },
2293 { ISD::ROTR, MVT::v2i64, 1 },
2294 { ISD::ROTR, MVT::v16i32, 1 },
2295 { ISD::ROTR, MVT::v8i32, 1 },
2296 { ISD::ROTR, MVT::v4i32, 1 }
2297 };
2298 // XOP: ROTL = VPROT(X,Y), ROTR = VPROT(X,SUB(0,Y))
2299 static const CostTblEntry XOPCostTbl[] = {
2300 { ISD::ROTL, MVT::v4i64, 4 },
2301 { ISD::ROTL, MVT::v8i32, 4 },
2302 { ISD::ROTL, MVT::v16i16, 4 },
2303 { ISD::ROTL, MVT::v32i8, 4 },
2304 { ISD::ROTL, MVT::v2i64, 1 },
2305 { ISD::ROTL, MVT::v4i32, 1 },
2306 { ISD::ROTL, MVT::v8i16, 1 },
2307 { ISD::ROTL, MVT::v16i8, 1 },
2308 { ISD::ROTR, MVT::v4i64, 6 },
2309 { ISD::ROTR, MVT::v8i32, 6 },
2310 { ISD::ROTR, MVT::v16i16, 6 },
2311 { ISD::ROTR, MVT::v32i8, 6 },
2312 { ISD::ROTR, MVT::v2i64, 2 },
2313 { ISD::ROTR, MVT::v4i32, 2 },
2314 { ISD::ROTR, MVT::v8i16, 2 },
2315 { ISD::ROTR, MVT::v16i8, 2 }
2316 };
2317 static const CostTblEntry X64CostTbl[] = { // 64-bit targets
2318 { ISD::ROTL, MVT::i64, 1 },
2319 { ISD::ROTR, MVT::i64, 1 },
2320 { ISD::FSHL, MVT::i64, 4 }
2321 };
2322 static const CostTblEntry X86CostTbl[] = { // 32 or 64-bit targets
2323 { ISD::ROTL, MVT::i32, 1 },
2324 { ISD::ROTL, MVT::i16, 1 },
2325 { ISD::ROTL, MVT::i8, 1 },
2326 { ISD::ROTR, MVT::i32, 1 },
2327 { ISD::ROTR, MVT::i16, 1 },
2328 { ISD::ROTR, MVT::i8, 1 },
2329 { ISD::FSHL, MVT::i32, 4 },
2330 { ISD::FSHL, MVT::i16, 4 },
2331 { ISD::FSHL, MVT::i8, 4 }
2332 };
2333
2334 unsigned ISD = ISD::DELETED_NODE;
2335 switch (IID) {
2336 default:
2337 break;
2338 case Intrinsic::fshl:
2339 ISD = ISD::FSHL;
2340 if (Args[0] == Args[1])
2341 ISD = ISD::ROTL;
2342 break;
2343 case Intrinsic::fshr:
2344 // FSHR has same costs so don't duplicate.
2345 ISD = ISD::FSHL;
2346 if (Args[0] == Args[1])
2347 ISD = ISD::ROTR;
2348 break;
2349 }
2350
2351 if (ISD != ISD::DELETED_NODE) {
2352 // Legalize the type.
2353 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, RetTy);
2354 MVT MTy = LT.second;
2355
2356 // Attempt to lookup cost.
2357 if (ST->hasAVX512())
2358 if (const auto *Entry = CostTableLookup(AVX512CostTbl, ISD, MTy))
2359 return LT.first * Entry->Cost;
2360
2361 if (ST->hasXOP())
2362 if (const auto *Entry = CostTableLookup(XOPCostTbl, ISD, MTy))
2363 return LT.first * Entry->Cost;
2364
2365 if (ST->is64Bit())
2366 if (const auto *Entry = CostTableLookup(X64CostTbl, ISD, MTy))
2367 return LT.first * Entry->Cost;
2368
2369 if (const auto *Entry = CostTableLookup(X86CostTbl, ISD, MTy))
2370 return LT.first * Entry->Cost;
2371 }
2372
2373 return BaseT::getIntrinsicInstrCost(IID, RetTy, Args, FMF, VF);
2374}
2375
2376int X86TTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
2377 assert(Val->isVectorTy() && "This must be a vector type")((Val->isVectorTy() && "This must be a vector type"
) ? static_cast<void> (0) : __assert_fail ("Val->isVectorTy() && \"This must be a vector type\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 2377, __PRETTY_FUNCTION__))
;
2378
2379 Type *ScalarType = Val->getScalarType();
2380
2381 if (Index != -1U) {
2382 // Legalize the type.
2383 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Val);
2384
2385 // This type is legalized to a scalar type.
2386 if (!LT.second.isVector())
2387 return 0;
2388
2389 // The type may be split. Normalize the index to the new type.
2390 unsigned Width = LT.second.getVectorNumElements();
2391 Index = Index % Width;
2392
2393 // Floating point scalars are already located in index #0.
2394 if (ScalarType->isFloatingPointTy() && Index == 0)
2395 return 0;
2396 }
2397
2398 // Add to the base cost if we know that the extracted element of a vector is
2399 // destined to be moved to and used in the integer register file.
2400 int RegisterFileMoveCost = 0;
2401 if (Opcode == Instruction::ExtractElement && ScalarType->isPointerTy())
2402 RegisterFileMoveCost = 1;
2403
2404 return BaseT::getVectorInstrCost(Opcode, Val, Index) + RegisterFileMoveCost;
2405}
2406
2407int X86TTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
2408 MaybeAlign Alignment, unsigned AddressSpace,
2409 const Instruction *I) {
2410 // Handle non-power-of-two vectors such as <3 x float>
2411 if (VectorType *VTy = dyn_cast<VectorType>(Src)) {
2412 unsigned NumElem = VTy->getVectorNumElements();
2413
2414 // Handle a few common cases:
2415 // <3 x float>
2416 if (NumElem == 3 && VTy->getScalarSizeInBits() == 32)
2417 // Cost = 64 bit store + extract + 32 bit store.
2418 return 3;
2419
2420 // <3 x double>
2421 if (NumElem == 3 && VTy->getScalarSizeInBits() == 64)
2422 // Cost = 128 bit store + unpack + 64 bit store.
2423 return 3;
2424
2425 // Assume that all other non-power-of-two numbers are scalarized.
2426 if (!isPowerOf2_32(NumElem)) {
2427 int Cost = BaseT::getMemoryOpCost(Opcode, VTy->getScalarType(), Alignment,
2428 AddressSpace);
2429 int SplitCost = getScalarizationOverhead(Src, Opcode == Instruction::Load,
2430 Opcode == Instruction::Store);
2431 return NumElem * Cost + SplitCost;
2432 }
2433 }
2434
2435 // Legalize the type.
2436 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
2437 assert((Opcode == Instruction::Load || Opcode == Instruction::Store) &&(((Opcode == Instruction::Load || Opcode == Instruction::Store
) && "Invalid Opcode") ? static_cast<void> (0) :
__assert_fail ("(Opcode == Instruction::Load || Opcode == Instruction::Store) && \"Invalid Opcode\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 2438, __PRETTY_FUNCTION__))
2438 "Invalid Opcode")(((Opcode == Instruction::Load || Opcode == Instruction::Store
) && "Invalid Opcode") ? static_cast<void> (0) :
__assert_fail ("(Opcode == Instruction::Load || Opcode == Instruction::Store) && \"Invalid Opcode\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 2438, __PRETTY_FUNCTION__))
;
2439
2440 // Each load/store unit costs 1.
2441 int Cost = LT.first * 1;
2442
2443 // This isn't exactly right. We're using slow unaligned 32-byte accesses as a
2444 // proxy for a double-pumped AVX memory interface such as on Sandybridge.
2445 if (LT.second.getStoreSize() == 32 && ST->isUnalignedMem32Slow())
2446 Cost *= 2;
2447
2448 return Cost;
2449}
2450
2451int X86TTIImpl::getMaskedMemoryOpCost(unsigned Opcode, Type *SrcTy,
2452 unsigned Alignment,
2453 unsigned AddressSpace) {
2454 bool IsLoad = (Instruction::Load == Opcode);
2455 bool IsStore = (Instruction::Store == Opcode);
2456
2457 VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy);
2458 if (!SrcVTy)
2459 // To calculate scalar take the regular cost, without mask
2460 return getMemoryOpCost(Opcode, SrcTy, MaybeAlign(Alignment), AddressSpace);
2461
2462 unsigned NumElem = SrcVTy->getVectorNumElements();
2463 VectorType *MaskTy =
2464 VectorType::get(Type::getInt8Ty(SrcVTy->getContext()), NumElem);
2465 if ((IsLoad && !isLegalMaskedLoad(SrcVTy, MaybeAlign(Alignment))) ||
2466 (IsStore && !isLegalMaskedStore(SrcVTy, MaybeAlign(Alignment))) ||
2467 !isPowerOf2_32(NumElem)) {
2468 // Scalarization
2469 int MaskSplitCost = getScalarizationOverhead(MaskTy, false, true);
2470 int ScalarCompareCost = getCmpSelInstrCost(
2471 Instruction::ICmp, Type::getInt8Ty(SrcVTy->getContext()), nullptr);
2472 int BranchCost = getCFInstrCost(Instruction::Br);
2473 int MaskCmpCost = NumElem * (BranchCost + ScalarCompareCost);
2474
2475 int ValueSplitCost = getScalarizationOverhead(SrcVTy, IsLoad, IsStore);
2476 int MemopCost =
2477 NumElem * BaseT::getMemoryOpCost(Opcode, SrcVTy->getScalarType(),
2478 MaybeAlign(Alignment), AddressSpace);
2479 return MemopCost + ValueSplitCost + MaskSplitCost + MaskCmpCost;
2480 }
2481
2482 // Legalize the type.
2483 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, SrcVTy);
2484 auto VT = TLI->getValueType(DL, SrcVTy);
2485 int Cost = 0;
2486 if (VT.isSimple() && LT.second != VT.getSimpleVT() &&
2487 LT.second.getVectorNumElements() == NumElem)
2488 // Promotion requires expand/truncate for data and a shuffle for mask.
2489 Cost += getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVTy, 0, nullptr) +
2490 getShuffleCost(TTI::SK_PermuteTwoSrc, MaskTy, 0, nullptr);
2491
2492 else if (LT.second.getVectorNumElements() > NumElem) {
2493 VectorType *NewMaskTy = VectorType::get(MaskTy->getVectorElementType(),
2494 LT.second.getVectorNumElements());
2495 // Expanding requires fill mask with zeroes
2496 Cost += getShuffleCost(TTI::SK_InsertSubvector, NewMaskTy, 0, MaskTy);
2497 }
2498
2499 // Pre-AVX512 - each maskmov load costs 2 + store costs ~8.
2500 if (!ST->hasAVX512())
2501 return Cost + LT.first * (IsLoad ? 2 : 8);
2502
2503 // AVX-512 masked load/store is cheapper
2504 return Cost + LT.first;
2505}
2506
2507int X86TTIImpl::getAddressComputationCost(Type *Ty, ScalarEvolution *SE,
2508 const SCEV *Ptr) {
2509 // Address computations in vectorized code with non-consecutive addresses will
2510 // likely result in more instructions compared to scalar code where the
2511 // computation can more often be merged into the index mode. The resulting
2512 // extra micro-ops can significantly decrease throughput.
2513 const unsigned NumVectorInstToHideOverhead = 10;
2514
2515 // Cost modeling of Strided Access Computation is hidden by the indexing
2516 // modes of X86 regardless of the stride value. We dont believe that there
2517 // is a difference between constant strided access in gerenal and constant
2518 // strided value which is less than or equal to 64.
2519 // Even in the case of (loop invariant) stride whose value is not known at
2520 // compile time, the address computation will not incur more than one extra
2521 // ADD instruction.
2522 if (Ty->isVectorTy() && SE) {
2523 if (!BaseT::isStridedAccess(Ptr))
2524 return NumVectorInstToHideOverhead;
2525 if (!BaseT::getConstantStrideStep(SE, Ptr))
2526 return 1;
2527 }
2528
2529 return BaseT::getAddressComputationCost(Ty, SE, Ptr);
2530}
2531
2532int X86TTIImpl::getArithmeticReductionCost(unsigned Opcode, Type *ValTy,
2533 bool IsPairwise) {
2534 // We use the Intel Architecture Code Analyzer(IACA) to measure the throughput
2535 // and make it as the cost.
2536
2537 static const CostTblEntry SLMCostTblPairWise[] = {
2538 { ISD::FADD, MVT::v2f64, 3 },
2539 { ISD::ADD, MVT::v2i64, 5 },
2540 };
2541
2542 static const CostTblEntry SSE2CostTblPairWise[] = {
2543 { ISD::FADD, MVT::v2f64, 2 },
2544 { ISD::FADD, MVT::v4f32, 4 },
2545 { ISD::ADD, MVT::v2i64, 2 }, // The data reported by the IACA tool is "1.6".
2546 { ISD::ADD, MVT::v2i32, 2 }, // FIXME: chosen to be less than v4i32.
2547 { ISD::ADD, MVT::v4i32, 3 }, // The data reported by the IACA tool is "3.5".
2548 { ISD::ADD, MVT::v2i16, 3 }, // FIXME: chosen to be less than v4i16
2549 { ISD::ADD, MVT::v4i16, 4 }, // FIXME: chosen to be less than v8i16
2550 { ISD::ADD, MVT::v8i16, 5 },
2551 { ISD::ADD, MVT::v2i8, 2 },
2552 { ISD::ADD, MVT::v4i8, 2 },
2553 { ISD::ADD, MVT::v8i8, 2 },
2554 { ISD::ADD, MVT::v16i8, 3 },
2555 };
2556
2557 static const CostTblEntry AVX1CostTblPairWise[] = {
2558 { ISD::FADD, MVT::v4f64, 5 },
2559 { ISD::FADD, MVT::v8f32, 7 },
2560 { ISD::ADD, MVT::v2i64, 1 }, // The data reported by the IACA tool is "1.5".
2561 { ISD::ADD, MVT::v4i64, 5 }, // The data reported by the IACA tool is "4.8".
2562 { ISD::ADD, MVT::v8i32, 5 },
2563 { ISD::ADD, MVT::v16i16, 6 },
2564 { ISD::ADD, MVT::v32i8, 4 },
2565 };
2566
2567 static const CostTblEntry SLMCostTblNoPairWise[] = {
2568 { ISD::FADD, MVT::v2f64, 3 },
2569 { ISD::ADD, MVT::v2i64, 5 },
2570 };
2571
2572 static const CostTblEntry SSE2CostTblNoPairWise[] = {
2573 { ISD::FADD, MVT::v2f64, 2 },
2574 { ISD::FADD, MVT::v4f32, 4 },
2575 { ISD::ADD, MVT::v2i64, 2 }, // The data reported by the IACA tool is "1.6".
2576 { ISD::ADD, MVT::v2i32, 2 }, // FIXME: chosen to be less than v4i32
2577 { ISD::ADD, MVT::v4i32, 3 }, // The data reported by the IACA tool is "3.3".
2578 { ISD::ADD, MVT::v2i16, 2 }, // The data reported by the IACA tool is "4.3".
2579 { ISD::ADD, MVT::v4i16, 3 }, // The data reported by the IACA tool is "4.3".
2580 { ISD::ADD, MVT::v8i16, 4 }, // The data reported by the IACA tool is "4.3".
2581 { ISD::ADD, MVT::v2i8, 2 },
2582 { ISD::ADD, MVT::v4i8, 2 },
2583 { ISD::ADD, MVT::v8i8, 2 },
2584 { ISD::ADD, MVT::v16i8, 3 },
2585 };
2586
2587 static const CostTblEntry AVX1CostTblNoPairWise[] = {
2588 { ISD::FADD, MVT::v4f64, 3 },
2589 { ISD::FADD, MVT::v4f32, 3 },
2590 { ISD::FADD, MVT::v8f32, 4 },
2591 { ISD::ADD, MVT::v2i64, 1 }, // The data reported by the IACA tool is "1.5".
2592 { ISD::ADD, MVT::v4i64, 3 },
2593 { ISD::ADD, MVT::v8i32, 5 },
2594 { ISD::ADD, MVT::v16i16, 5 },
2595 { ISD::ADD, MVT::v32i8, 4 },
2596 };
2597
2598 int ISD = TLI->InstructionOpcodeToISD(Opcode);
2599 assert(ISD && "Invalid opcode")((ISD && "Invalid opcode") ? static_cast<void> (
0) : __assert_fail ("ISD && \"Invalid opcode\"", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 2599, __PRETTY_FUNCTION__))
;
2600
2601 // Before legalizing the type, give a chance to look up illegal narrow types
2602 // in the table.
2603 // FIXME: Is there a better way to do this?
2604 EVT VT = TLI->getValueType(DL, ValTy);
2605 if (VT.isSimple()) {
2606 MVT MTy = VT.getSimpleVT();
2607 if (IsPairwise) {
2608 if (ST->isSLM())
2609 if (const auto *Entry = CostTableLookup(SLMCostTblPairWise, ISD, MTy))
2610 return Entry->Cost;
2611
2612 if (ST->hasAVX())
2613 if (const auto *Entry = CostTableLookup(AVX1CostTblPairWise, ISD, MTy))
2614 return Entry->Cost;
2615
2616 if (ST->hasSSE2())
2617 if (const auto *Entry = CostTableLookup(SSE2CostTblPairWise, ISD, MTy))
2618 return Entry->Cost;
2619 } else {
2620 if (ST->isSLM())
2621 if (const auto *Entry = CostTableLookup(SLMCostTblNoPairWise, ISD, MTy))
2622 return Entry->Cost;
2623
2624 if (ST->hasAVX())
2625 if (const auto *Entry = CostTableLookup(AVX1CostTblNoPairWise, ISD, MTy))
2626 return Entry->Cost;
2627
2628 if (ST->hasSSE2())
2629 if (const auto *Entry = CostTableLookup(SSE2CostTblNoPairWise, ISD, MTy))
2630 return Entry->Cost;
2631 }
2632 }
2633
2634 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
2635
2636 MVT MTy = LT.second;
2637
2638 if (IsPairwise) {
2639 if (ST->isSLM())
2640 if (const auto *Entry = CostTableLookup(SLMCostTblPairWise, ISD, MTy))
2641 return LT.first * Entry->Cost;
2642
2643 if (ST->hasAVX())
2644 if (const auto *Entry = CostTableLookup(AVX1CostTblPairWise, ISD, MTy))
2645 return LT.first * Entry->Cost;
2646
2647 if (ST->hasSSE2())
2648 if (const auto *Entry = CostTableLookup(SSE2CostTblPairWise, ISD, MTy))
2649 return LT.first * Entry->Cost;
2650 } else {
2651 if (ST->isSLM())
2652 if (const auto *Entry = CostTableLookup(SLMCostTblNoPairWise, ISD, MTy))
2653 return LT.first * Entry->Cost;
2654
2655 if (ST->hasAVX())
2656 if (const auto *Entry = CostTableLookup(AVX1CostTblNoPairWise, ISD, MTy))
2657 return LT.first * Entry->Cost;
2658
2659 if (ST->hasSSE2())
2660 if (const auto *Entry = CostTableLookup(SSE2CostTblNoPairWise, ISD, MTy))
2661 return LT.first * Entry->Cost;
2662 }
2663
2664 // FIXME: These assume a naive kshift+binop lowering, which is probably
2665 // conservative in most cases.
2666 // FIXME: This doesn't cost large types like v128i1 correctly.
2667 static const CostTblEntry AVX512BoolReduction[] = {
2668 { ISD::AND, MVT::v2i1, 3 },
2669 { ISD::AND, MVT::v4i1, 5 },
2670 { ISD::AND, MVT::v8i1, 7 },
2671 { ISD::AND, MVT::v16i1, 9 },
2672 { ISD::AND, MVT::v32i1, 11 },
2673 { ISD::AND, MVT::v64i1, 13 },
2674 { ISD::OR, MVT::v2i1, 3 },
2675 { ISD::OR, MVT::v4i1, 5 },
2676 { ISD::OR, MVT::v8i1, 7 },
2677 { ISD::OR, MVT::v16i1, 9 },
2678 { ISD::OR, MVT::v32i1, 11 },
2679 { ISD::OR, MVT::v64i1, 13 },
2680 };
2681
2682 static const CostTblEntry AVX2BoolReduction[] = {
2683 { ISD::AND, MVT::v16i16, 2 }, // vpmovmskb + cmp
2684 { ISD::AND, MVT::v32i8, 2 }, // vpmovmskb + cmp
2685 { ISD::OR, MVT::v16i16, 2 }, // vpmovmskb + cmp
2686 { ISD::OR, MVT::v32i8, 2 }, // vpmovmskb + cmp
2687 };
2688
2689 static const CostTblEntry AVX1BoolReduction[] = {
2690 { ISD::AND, MVT::v4i64, 2 }, // vmovmskpd + cmp
2691 { ISD::AND, MVT::v8i32, 2 }, // vmovmskps + cmp
2692 { ISD::AND, MVT::v16i16, 4 }, // vextractf128 + vpand + vpmovmskb + cmp
2693 { ISD::AND, MVT::v32i8, 4 }, // vextractf128 + vpand + vpmovmskb + cmp
2694 { ISD::OR, MVT::v4i64, 2 }, // vmovmskpd + cmp
2695 { ISD::OR, MVT::v8i32, 2 }, // vmovmskps + cmp
2696 { ISD::OR, MVT::v16i16, 4 }, // vextractf128 + vpor + vpmovmskb + cmp
2697 { ISD::OR, MVT::v32i8, 4 }, // vextractf128 + vpor + vpmovmskb + cmp
2698 };
2699
2700 static const CostTblEntry SSE2BoolReduction[] = {
2701 { ISD::AND, MVT::v2i64, 2 }, // movmskpd + cmp
2702 { ISD::AND, MVT::v4i32, 2 }, // movmskps + cmp
2703 { ISD::AND, MVT::v8i16, 2 }, // pmovmskb + cmp
2704 { ISD::AND, MVT::v16i8, 2 }, // pmovmskb + cmp
2705 { ISD::OR, MVT::v2i64, 2 }, // movmskpd + cmp
2706 { ISD::OR, MVT::v4i32, 2 }, // movmskps + cmp
2707 { ISD::OR, MVT::v8i16, 2 }, // pmovmskb + cmp
2708 { ISD::OR, MVT::v16i8, 2 }, // pmovmskb + cmp
2709 };
2710
2711 // Handle bool allof/anyof patterns.
2712 if (!IsPairwise && ValTy->getVectorElementType()->isIntegerTy(1)) {
2713 if (ST->hasAVX512())
2714 if (const auto *Entry = CostTableLookup(AVX512BoolReduction, ISD, MTy))
2715 return LT.first * Entry->Cost;
2716 if (ST->hasAVX2())
2717 if (const auto *Entry = CostTableLookup(AVX2BoolReduction, ISD, MTy))
2718 return LT.first * Entry->Cost;
2719 if (ST->hasAVX())
2720 if (const auto *Entry = CostTableLookup(AVX1BoolReduction, ISD, MTy))
2721 return LT.first * Entry->Cost;
2722 if (ST->hasSSE2())
2723 if (const auto *Entry = CostTableLookup(SSE2BoolReduction, ISD, MTy))
2724 return LT.first * Entry->Cost;
2725 }
2726
2727 return BaseT::getArithmeticReductionCost(Opcode, ValTy, IsPairwise);
2728}
2729
2730int X86TTIImpl::getMinMaxReductionCost(Type *ValTy, Type *CondTy,
2731 bool IsPairwise, bool IsUnsigned) {
2732 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
2733
2734 MVT MTy = LT.second;
2735
2736 int ISD;
2737 if (ValTy->isIntOrIntVectorTy()) {
2738 ISD = IsUnsigned ? ISD::UMIN : ISD::SMIN;
2739 } else {
2740 assert(ValTy->isFPOrFPVectorTy() &&((ValTy->isFPOrFPVectorTy() && "Expected float point or integer vector type."
) ? static_cast<void> (0) : __assert_fail ("ValTy->isFPOrFPVectorTy() && \"Expected float point or integer vector type.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 2741, __PRETTY_FUNCTION__))
2741 "Expected float point or integer vector type.")((ValTy->isFPOrFPVectorTy() && "Expected float point or integer vector type."
) ? static_cast<void> (0) : __assert_fail ("ValTy->isFPOrFPVectorTy() && \"Expected float point or integer vector type.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 2741, __PRETTY_FUNCTION__))
;
2742 ISD = ISD::FMINNUM;
2743 }
2744
2745 // We use the Intel Architecture Code Analyzer(IACA) to measure the throughput
2746 // and make it as the cost.
2747
2748 static const CostTblEntry SSE1CostTblPairWise[] = {
2749 {ISD::FMINNUM, MVT::v4f32, 4},
2750 };
2751
2752 static const CostTblEntry SSE2CostTblPairWise[] = {
2753 {ISD::FMINNUM, MVT::v2f64, 3},
2754 {ISD::SMIN, MVT::v2i64, 6},
2755 {ISD::UMIN, MVT::v2i64, 8},
2756 {ISD::SMIN, MVT::v4i32, 6},
2757 {ISD::UMIN, MVT::v4i32, 8},
2758 {ISD::SMIN, MVT::v8i16, 4},
2759 {ISD::UMIN, MVT::v8i16, 6},
2760 {ISD::SMIN, MVT::v16i8, 8},
2761 {ISD::UMIN, MVT::v16i8, 6},
2762 };
2763
2764 static const CostTblEntry SSE41CostTblPairWise[] = {
2765 {ISD::FMINNUM, MVT::v4f32, 2},
2766 {ISD::SMIN, MVT::v2i64, 9},
2767 {ISD::UMIN, MVT::v2i64,10},
2768 {ISD::SMIN, MVT::v4i32, 1}, // The data reported by the IACA is "1.5"
2769 {ISD::UMIN, MVT::v4i32, 2}, // The data reported by the IACA is "1.8"
2770 {ISD::SMIN, MVT::v8i16, 2},
2771 {ISD::UMIN, MVT::v8i16, 2},
2772 {ISD::SMIN, MVT::v16i8, 3},
2773 {ISD::UMIN, MVT::v16i8, 3},
2774 };
2775
2776 static const CostTblEntry SSE42CostTblPairWise[] = {
2777 {ISD::SMIN, MVT::v2i64, 7}, // The data reported by the IACA is "6.8"
2778 {ISD::UMIN, MVT::v2i64, 8}, // The data reported by the IACA is "8.6"
2779 };
2780
2781 static const CostTblEntry AVX1CostTblPairWise[] = {
2782 {ISD::FMINNUM, MVT::v4f32, 1},
2783 {ISD::FMINNUM, MVT::v4f64, 1},
2784 {ISD::FMINNUM, MVT::v8f32, 2},
2785 {ISD::SMIN, MVT::v2i64, 3},
2786 {ISD::UMIN, MVT::v2i64, 3},
2787 {ISD::SMIN, MVT::v4i32, 1},
2788 {ISD::UMIN, MVT::v4i32, 1},
2789 {ISD::SMIN, MVT::v8i16, 1},
2790 {ISD::UMIN, MVT::v8i16, 1},
2791 {ISD::SMIN, MVT::v16i8, 2},
2792 {ISD::UMIN, MVT::v16i8, 2},
2793 {ISD::SMIN, MVT::v4i64, 7},
2794 {ISD::UMIN, MVT::v4i64, 7},
2795 {ISD::SMIN, MVT::v8i32, 3},
2796 {ISD::UMIN, MVT::v8i32, 3},
2797 {ISD::SMIN, MVT::v16i16, 3},
2798 {ISD::UMIN, MVT::v16i16, 3},
2799 {ISD::SMIN, MVT::v32i8, 3},
2800 {ISD::UMIN, MVT::v32i8, 3},
2801 };
2802
2803 static const CostTblEntry AVX2CostTblPairWise[] = {
2804 {ISD::SMIN, MVT::v4i64, 2},
2805 {ISD::UMIN, MVT::v4i64, 2},
2806 {ISD::SMIN, MVT::v8i32, 1},
2807 {ISD::UMIN, MVT::v8i32, 1},
2808 {ISD::SMIN, MVT::v16i16, 1},
2809 {ISD::UMIN, MVT::v16i16, 1},
2810 {ISD::SMIN, MVT::v32i8, 2},
2811 {ISD::UMIN, MVT::v32i8, 2},
2812 };
2813
2814 static const CostTblEntry AVX512CostTblPairWise[] = {
2815 {ISD::FMINNUM, MVT::v8f64, 1},
2816 {ISD::FMINNUM, MVT::v16f32, 2},
2817 {ISD::SMIN, MVT::v8i64, 2},
2818 {ISD::UMIN, MVT::v8i64, 2},
2819 {ISD::SMIN, MVT::v16i32, 1},
2820 {ISD::UMIN, MVT::v16i32, 1},
2821 };
2822
2823 static const CostTblEntry SSE1CostTblNoPairWise[] = {
2824 {ISD::FMINNUM, MVT::v4f32, 4},
2825 };
2826
2827 static const CostTblEntry SSE2CostTblNoPairWise[] = {
2828 {ISD::FMINNUM, MVT::v2f64, 3},
2829 {ISD::SMIN, MVT::v2i64, 6},
2830 {ISD::UMIN, MVT::v2i64, 8},
2831 {ISD::SMIN, MVT::v4i32, 6},
2832 {ISD::UMIN, MVT::v4i32, 8},
2833 {ISD::SMIN, MVT::v8i16, 4},
2834 {ISD::UMIN, MVT::v8i16, 6},
2835 {ISD::SMIN, MVT::v16i8, 8},
2836 {ISD::UMIN, MVT::v16i8, 6},
2837 };
2838
2839 static const CostTblEntry SSE41CostTblNoPairWise[] = {
2840 {ISD::FMINNUM, MVT::v4f32, 3},
2841 {ISD::SMIN, MVT::v2i64, 9},
2842 {ISD::UMIN, MVT::v2i64,11},
2843 {ISD::SMIN, MVT::v4i32, 1}, // The data reported by the IACA is "1.5"
2844 {ISD::UMIN, MVT::v4i32, 2}, // The data reported by the IACA is "1.8"
2845 {ISD::SMIN, MVT::v8i16, 1}, // The data reported by the IACA is "1.5"
2846 {ISD::UMIN, MVT::v8i16, 2}, // The data reported by the IACA is "1.8"
2847 {ISD::SMIN, MVT::v16i8, 3},
2848 {ISD::UMIN, MVT::v16i8, 3},
2849 };
2850
2851 static const CostTblEntry SSE42CostTblNoPairWise[] = {
2852 {ISD::SMIN, MVT::v2i64, 7}, // The data reported by the IACA is "6.8"
2853 {ISD::UMIN, MVT::v2i64, 9}, // The data reported by the IACA is "8.6"
2854 };
2855
2856 static const CostTblEntry AVX1CostTblNoPairWise[] = {
2857 {ISD::FMINNUM, MVT::v4f32, 1},
2858 {ISD::FMINNUM, MVT::v4f64, 1},
2859 {ISD::FMINNUM, MVT::v8f32, 1},
2860 {ISD::SMIN, MVT::v2i64, 3},
2861 {ISD::UMIN, MVT::v2i64, 3},
2862 {ISD::SMIN, MVT::v4i32, 1},
2863 {ISD::UMIN, MVT::v4i32, 1},
2864 {ISD::SMIN, MVT::v8i16, 1},
2865 {ISD::UMIN, MVT::v8i16, 1},
2866 {ISD::SMIN, MVT::v16i8, 2},
2867 {ISD::UMIN, MVT::v16i8, 2},
2868 {ISD::SMIN, MVT::v4i64, 7},
2869 {ISD::UMIN, MVT::v4i64, 7},
2870 {ISD::SMIN, MVT::v8i32, 2},
2871 {ISD::UMIN, MVT::v8i32, 2},
2872 {ISD::SMIN, MVT::v16i16, 2},
2873 {ISD::UMIN, MVT::v16i16, 2},
2874 {ISD::SMIN, MVT::v32i8, 2},
2875 {ISD::UMIN, MVT::v32i8, 2},
2876 };
2877
2878 static const CostTblEntry AVX2CostTblNoPairWise[] = {
2879 {ISD::SMIN, MVT::v4i64, 1},
2880 {ISD::UMIN, MVT::v4i64, 1},
2881 {ISD::SMIN, MVT::v8i32, 1},
2882 {ISD::UMIN, MVT::v8i32, 1},
2883 {ISD::SMIN, MVT::v16i16, 1},
2884 {ISD::UMIN, MVT::v16i16, 1},
2885 {ISD::SMIN, MVT::v32i8, 1},
2886 {ISD::UMIN, MVT::v32i8, 1},
2887 };
2888
2889 static const CostTblEntry AVX512CostTblNoPairWise[] = {
2890 {ISD::FMINNUM, MVT::v8f64, 1},
2891 {ISD::FMINNUM, MVT::v16f32, 2},
2892 {ISD::SMIN, MVT::v8i64, 1},
2893 {ISD::UMIN, MVT::v8i64, 1},
2894 {ISD::SMIN, MVT::v16i32, 1},
2895 {ISD::UMIN, MVT::v16i32, 1},
2896 };
2897
2898 if (IsPairwise) {
2899 if (ST->hasAVX512())
2900 if (const auto *Entry = CostTableLookup(AVX512CostTblPairWise, ISD, MTy))
2901 return LT.first * Entry->Cost;
2902
2903 if (ST->hasAVX2())
2904 if (const auto *Entry = CostTableLookup(AVX2CostTblPairWise, ISD, MTy))
2905 return LT.first * Entry->Cost;
2906
2907 if (ST->hasAVX())
2908 if (const auto *Entry = CostTableLookup(AVX1CostTblPairWise, ISD, MTy))
2909 return LT.first * Entry->Cost;
2910
2911 if (ST->hasSSE42())
2912 if (const auto *Entry = CostTableLookup(SSE42CostTblPairWise, ISD, MTy))
2913 return LT.first * Entry->Cost;
2914
2915 if (ST->hasSSE41())
2916 if (const auto *Entry = CostTableLookup(SSE41CostTblPairWise, ISD, MTy))
2917 return LT.first * Entry->Cost;
2918
2919 if (ST->hasSSE2())
2920 if (const auto *Entry = CostTableLookup(SSE2CostTblPairWise, ISD, MTy))
2921 return LT.first * Entry->Cost;
2922
2923 if (ST->hasSSE1())
2924 if (const auto *Entry = CostTableLookup(SSE1CostTblPairWise, ISD, MTy))
2925 return LT.first * Entry->Cost;
2926 } else {
2927 if (ST->hasAVX512())
2928 if (const auto *Entry =
2929 CostTableLookup(AVX512CostTblNoPairWise, ISD, MTy))
2930 return LT.first * Entry->Cost;
2931
2932 if (ST->hasAVX2())
2933 if (const auto *Entry = CostTableLookup(AVX2CostTblNoPairWise, ISD, MTy))
2934 return LT.first * Entry->Cost;
2935
2936 if (ST->hasAVX())
2937 if (const auto *Entry = CostTableLookup(AVX1CostTblNoPairWise, ISD, MTy))
2938 return LT.first * Entry->Cost;
2939
2940 if (ST->hasSSE42())
2941 if (const auto *Entry = CostTableLookup(SSE42CostTblNoPairWise, ISD, MTy))
2942 return LT.first * Entry->Cost;
2943
2944 if (ST->hasSSE41())
2945 if (const auto *Entry = CostTableLookup(SSE41CostTblNoPairWise, ISD, MTy))
2946 return LT.first * Entry->Cost;
2947
2948 if (ST->hasSSE2())
2949 if (const auto *Entry = CostTableLookup(SSE2CostTblNoPairWise, ISD, MTy))
2950 return LT.first * Entry->Cost;
2951
2952 if (ST->hasSSE1())
2953 if (const auto *Entry = CostTableLookup(SSE1CostTblNoPairWise, ISD, MTy))
2954 return LT.first * Entry->Cost;
2955 }
2956
2957 return BaseT::getMinMaxReductionCost(ValTy, CondTy, IsPairwise, IsUnsigned);
2958}
2959
2960/// Calculate the cost of materializing a 64-bit value. This helper
2961/// method might only calculate a fraction of a larger immediate. Therefore it
2962/// is valid to return a cost of ZERO.
2963int X86TTIImpl::getIntImmCost(int64_t Val) {
2964 if (Val == 0)
2965 return TTI::TCC_Free;
2966
2967 if (isInt<32>(Val))
2968 return TTI::TCC_Basic;
2969
2970 return 2 * TTI::TCC_Basic;
2971}
2972
2973int X86TTIImpl::getIntImmCost(const APInt &Imm, Type *Ty) {
2974 assert(Ty->isIntegerTy())((Ty->isIntegerTy()) ? static_cast<void> (0) : __assert_fail
("Ty->isIntegerTy()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 2974, __PRETTY_FUNCTION__))
;
2975
2976 unsigned BitSize = Ty->getPrimitiveSizeInBits();
2977 if (BitSize == 0)
2978 return ~0U;
2979
2980 // Never hoist constants larger than 128bit, because this might lead to
2981 // incorrect code generation or assertions in codegen.
2982 // Fixme: Create a cost model for types larger than i128 once the codegen
2983 // issues have been fixed.
2984 if (BitSize > 128)
2985 return TTI::TCC_Free;
2986
2987 if (Imm == 0)
2988 return TTI::TCC_Free;
2989
2990 // Sign-extend all constants to a multiple of 64-bit.
2991 APInt ImmVal = Imm;
2992 if (BitSize % 64 != 0)
2993 ImmVal = Imm.sext(alignTo(BitSize, 64));
2994
2995 // Split the constant into 64-bit chunks and calculate the cost for each
2996 // chunk.
2997 int Cost = 0;
2998 for (unsigned ShiftVal = 0; ShiftVal < BitSize; ShiftVal += 64) {
2999 APInt Tmp = ImmVal.ashr(ShiftVal).sextOrTrunc(64);
3000 int64_t Val = Tmp.getSExtValue();
3001 Cost += getIntImmCost(Val);
3002 }
3003 // We need at least one instruction to materialize the constant.
3004 return std::max(1, Cost);
3005}
3006
3007int X86TTIImpl::getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
3008 Type *Ty) {
3009 assert(Ty->isIntegerTy())((Ty->isIntegerTy()) ? static_cast<void> (0) : __assert_fail
("Ty->isIntegerTy()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 3009, __PRETTY_FUNCTION__))
;
3010
3011 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3012 // There is no cost model for constants with a bit size of 0. Return TCC_Free
3013 // here, so that constant hoisting will ignore this constant.
3014 if (BitSize == 0)
3015 return TTI::TCC_Free;
3016
3017 unsigned ImmIdx = ~0U;
3018 switch (Opcode) {
3019 default:
3020 return TTI::TCC_Free;
3021 case Instruction::GetElementPtr:
3022 // Always hoist the base address of a GetElementPtr. This prevents the
3023 // creation of new constants for every base constant that gets constant
3024 // folded with the offset.
3025 if (Idx == 0)
3026 return 2 * TTI::TCC_Basic;
3027 return TTI::TCC_Free;
3028 case Instruction::Store:
3029 ImmIdx = 0;
3030 break;
3031 case Instruction::ICmp:
3032 // This is an imperfect hack to prevent constant hoisting of
3033 // compares that might be trying to check if a 64-bit value fits in
3034 // 32-bits. The backend can optimize these cases using a right shift by 32.
3035 // Ideally we would check the compare predicate here. There also other
3036 // similar immediates the backend can use shifts for.
3037 if (Idx == 1 && Imm.getBitWidth() == 64) {
3038 uint64_t ImmVal = Imm.getZExtValue();
3039 if (ImmVal == 0x100000000ULL || ImmVal == 0xffffffff)
3040 return TTI::TCC_Free;
3041 }
3042 ImmIdx = 1;
3043 break;
3044 case Instruction::And:
3045 // We support 64-bit ANDs with immediates with 32-bits of leading zeroes
3046 // by using a 32-bit operation with implicit zero extension. Detect such
3047 // immediates here as the normal path expects bit 31 to be sign extended.
3048 if (Idx == 1 && Imm.getBitWidth() == 64 && isUInt<32>(Imm.getZExtValue()))
3049 return TTI::TCC_Free;
3050 ImmIdx = 1;
3051 break;
3052 case Instruction::Add:
3053 case Instruction::Sub:
3054 // For add/sub, we can use the opposite instruction for INT32_MIN.
3055 if (Idx == 1 && Imm.getBitWidth() == 64 && Imm.getZExtValue() == 0x80000000)
3056 return TTI::TCC_Free;
3057 ImmIdx = 1;
3058 break;
3059 case Instruction::UDiv:
3060 case Instruction::SDiv:
3061 case Instruction::URem:
3062 case Instruction::SRem:
3063 // Division by constant is typically expanded later into a different
3064 // instruction sequence. This completely changes the constants.
3065 // Report them as "free" to stop ConstantHoist from marking them as opaque.
3066 return TTI::TCC_Free;
3067 case Instruction::Mul:
3068 case Instruction::Or:
3069 case Instruction::Xor:
3070 ImmIdx = 1;
3071 break;
3072 // Always return TCC_Free for the shift value of a shift instruction.
3073 case Instruction::Shl:
3074 case Instruction::LShr:
3075 case Instruction::AShr:
3076 if (Idx == 1)
3077 return TTI::TCC_Free;
3078 break;
3079 case Instruction::Trunc:
3080 case Instruction::ZExt:
3081 case Instruction::SExt:
3082 case Instruction::IntToPtr:
3083 case Instruction::PtrToInt:
3084 case Instruction::BitCast:
3085 case Instruction::PHI:
3086 case Instruction::Call:
3087 case Instruction::Select:
3088 case Instruction::Ret:
3089 case Instruction::Load:
3090 break;
3091 }
3092
3093 if (Idx == ImmIdx) {
3094 int NumConstants = divideCeil(BitSize, 64);
3095 int Cost = X86TTIImpl::getIntImmCost(Imm, Ty);
3096 return (Cost <= NumConstants * TTI::TCC_Basic)
3097 ? static_cast<int>(TTI::TCC_Free)
3098 : Cost;
3099 }
3100
3101 return X86TTIImpl::getIntImmCost(Imm, Ty);
3102}
3103
3104int X86TTIImpl::getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
3105 Type *Ty) {
3106 assert(Ty->isIntegerTy())((Ty->isIntegerTy()) ? static_cast<void> (0) : __assert_fail
("Ty->isIntegerTy()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 3106, __PRETTY_FUNCTION__))
;
3107
3108 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3109 // There is no cost model for constants with a bit size of 0. Return TCC_Free
3110 // here, so that constant hoisting will ignore this constant.
3111 if (BitSize == 0)
3112 return TTI::TCC_Free;
3113
3114 switch (IID) {
3115 default:
3116 return TTI::TCC_Free;
3117 case Intrinsic::sadd_with_overflow:
3118 case Intrinsic::uadd_with_overflow:
3119 case Intrinsic::ssub_with_overflow:
3120 case Intrinsic::usub_with_overflow:
3121 case Intrinsic::smul_with_overflow:
3122 case Intrinsic::umul_with_overflow:
3123 if ((Idx == 1) && Imm.getBitWidth() <= 64 && isInt<32>(Imm.getSExtValue()))
3124 return TTI::TCC_Free;
3125 break;
3126 case Intrinsic::experimental_stackmap:
3127 if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
3128 return TTI::TCC_Free;
3129 break;
3130 case Intrinsic::experimental_patchpoint_void:
3131 case Intrinsic::experimental_patchpoint_i64:
3132 if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
3133 return TTI::TCC_Free;
3134 break;
3135 }
3136 return X86TTIImpl::getIntImmCost(Imm, Ty);
3137}
3138
3139unsigned X86TTIImpl::getUserCost(const User *U,
3140 ArrayRef<const Value *> Operands) {
3141 if (isa<StoreInst>(U)) {
1
Assuming 'U' is not a 'StoreInst'
2
Taking false branch
3142 Value *Ptr = U->getOperand(1);
3143 // Store instruction with index and scale costs 2 Uops.
3144 // Check the preceding GEP to identify non-const indices.
3145 if (auto GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
3146 if (!all_of(GEP->indices(), [](Value *V) { return isa<Constant>(V); }))
3147 return TTI::TCC_Basic * 2;
3148 }
3149 return TTI::TCC_Basic;
3150 }
3151 return BaseT::getUserCost(U, Operands);
3
Calling 'TargetTransformInfoImplCRTPBase::getUserCost'
3152}
3153
3154// Return an average cost of Gather / Scatter instruction, maybe improved later
3155int X86TTIImpl::getGSVectorCost(unsigned Opcode, Type *SrcVTy, Value *Ptr,
3156 unsigned Alignment, unsigned AddressSpace) {
3157
3158 assert(isa<VectorType>(SrcVTy) && "Unexpected type in getGSVectorCost")((isa<VectorType>(SrcVTy) && "Unexpected type in getGSVectorCost"
) ? static_cast<void> (0) : __assert_fail ("isa<VectorType>(SrcVTy) && \"Unexpected type in getGSVectorCost\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 3158, __PRETTY_FUNCTION__))
;
3159 unsigned VF = SrcVTy->getVectorNumElements();
3160
3161 // Try to reduce index size from 64 bit (default for GEP)
3162 // to 32. It is essential for VF 16. If the index can't be reduced to 32, the
3163 // operation will use 16 x 64 indices which do not fit in a zmm and needs
3164 // to split. Also check that the base pointer is the same for all lanes,
3165 // and that there's at most one variable index.
3166 auto getIndexSizeInBits = [](Value *Ptr, const DataLayout& DL) {
3167 unsigned IndexSize = DL.getPointerSizeInBits();
3168 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3169 if (IndexSize < 64 || !GEP)
3170 return IndexSize;
3171
3172 unsigned NumOfVarIndices = 0;
3173 Value *Ptrs = GEP->getPointerOperand();
3174 if (Ptrs->getType()->isVectorTy() && !getSplatValue(Ptrs))
3175 return IndexSize;
3176 for (unsigned i = 1; i < GEP->getNumOperands(); ++i) {
3177 if (isa<Constant>(GEP->getOperand(i)))
3178 continue;
3179 Type *IndxTy = GEP->getOperand(i)->getType();
3180 if (IndxTy->isVectorTy())
3181 IndxTy = IndxTy->getVectorElementType();
3182 if ((IndxTy->getPrimitiveSizeInBits() == 64 &&
3183 !isa<SExtInst>(GEP->getOperand(i))) ||
3184 ++NumOfVarIndices > 1)
3185 return IndexSize; // 64
3186 }
3187 return (unsigned)32;
3188 };
3189
3190
3191 // Trying to reduce IndexSize to 32 bits for vector 16.
3192 // By default the IndexSize is equal to pointer size.
3193 unsigned IndexSize = (ST->hasAVX512() && VF >= 16)
3194 ? getIndexSizeInBits(Ptr, DL)
3195 : DL.getPointerSizeInBits();
3196
3197 Type *IndexVTy = VectorType::get(IntegerType::get(SrcVTy->getContext(),
3198 IndexSize), VF);
3199 std::pair<int, MVT> IdxsLT = TLI->getTypeLegalizationCost(DL, IndexVTy);
3200 std::pair<int, MVT> SrcLT = TLI->getTypeLegalizationCost(DL, SrcVTy);
3201 int SplitFactor = std::max(IdxsLT.first, SrcLT.first);
3202 if (SplitFactor > 1) {
3203 // Handle splitting of vector of pointers
3204 Type *SplitSrcTy = VectorType::get(SrcVTy->getScalarType(), VF / SplitFactor);
3205 return SplitFactor * getGSVectorCost(Opcode, SplitSrcTy, Ptr, Alignment,
3206 AddressSpace);
3207 }
3208
3209 // The gather / scatter cost is given by Intel architects. It is a rough
3210 // number since we are looking at one instruction in a time.
3211 const int GSOverhead = (Opcode == Instruction::Load)
3212 ? ST->getGatherOverhead()
3213 : ST->getScatterOverhead();
3214 return GSOverhead + VF * getMemoryOpCost(Opcode, SrcVTy->getScalarType(),
3215 MaybeAlign(Alignment), AddressSpace);
3216}
3217
3218/// Return the cost of full scalarization of gather / scatter operation.
3219///
3220/// Opcode - Load or Store instruction.
3221/// SrcVTy - The type of the data vector that should be gathered or scattered.
3222/// VariableMask - The mask is non-constant at compile time.
3223/// Alignment - Alignment for one element.
3224/// AddressSpace - pointer[s] address space.
3225///
3226int X86TTIImpl::getGSScalarCost(unsigned Opcode, Type *SrcVTy,
3227 bool VariableMask, unsigned Alignment,
3228 unsigned AddressSpace) {
3229 unsigned VF = SrcVTy->getVectorNumElements();
3230
3231 int MaskUnpackCost = 0;
3232 if (VariableMask) {
3233 VectorType *MaskTy =
3234 VectorType::get(Type::getInt1Ty(SrcVTy->getContext()), VF);
3235 MaskUnpackCost = getScalarizationOverhead(MaskTy, false, true);
3236 int ScalarCompareCost =
3237 getCmpSelInstrCost(Instruction::ICmp, Type::getInt1Ty(SrcVTy->getContext()),
3238 nullptr);
3239 int BranchCost = getCFInstrCost(Instruction::Br);
3240 MaskUnpackCost += VF * (BranchCost + ScalarCompareCost);
3241 }
3242
3243 // The cost of the scalar loads/stores.
3244 int MemoryOpCost = VF * getMemoryOpCost(Opcode, SrcVTy->getScalarType(),
3245 MaybeAlign(Alignment), AddressSpace);
3246
3247 int InsertExtractCost = 0;
3248 if (Opcode == Instruction::Load)
3249 for (unsigned i = 0; i < VF; ++i)
3250 // Add the cost of inserting each scalar load into the vector
3251 InsertExtractCost +=
3252 getVectorInstrCost(Instruction::InsertElement, SrcVTy, i);
3253 else
3254 for (unsigned i = 0; i < VF; ++i)
3255 // Add the cost of extracting each element out of the data vector
3256 InsertExtractCost +=
3257 getVectorInstrCost(Instruction::ExtractElement, SrcVTy, i);
3258
3259 return MemoryOpCost + MaskUnpackCost + InsertExtractCost;
3260}
3261
3262/// Calculate the cost of Gather / Scatter operation
3263int X86TTIImpl::getGatherScatterOpCost(unsigned Opcode, Type *SrcVTy,
3264 Value *Ptr, bool VariableMask,
3265 unsigned Alignment) {
3266 assert(SrcVTy->isVectorTy() && "Unexpected data type for Gather/Scatter")((SrcVTy->isVectorTy() && "Unexpected data type for Gather/Scatter"
) ? static_cast<void> (0) : __assert_fail ("SrcVTy->isVectorTy() && \"Unexpected data type for Gather/Scatter\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 3266, __PRETTY_FUNCTION__))
;
3267 unsigned VF = SrcVTy->getVectorNumElements();
3268 PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
3269 if (!PtrTy && Ptr->getType()->isVectorTy())
3270 PtrTy = dyn_cast<PointerType>(Ptr->getType()->getVectorElementType());
3271 assert(PtrTy && "Unexpected type for Ptr argument")((PtrTy && "Unexpected type for Ptr argument") ? static_cast
<void> (0) : __assert_fail ("PtrTy && \"Unexpected type for Ptr argument\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 3271, __PRETTY_FUNCTION__))
;
3272 unsigned AddressSpace = PtrTy->getAddressSpace();
3273
3274 bool Scalarize = false;
3275 if ((Opcode == Instruction::Load && !isLegalMaskedGather(SrcVTy)) ||
3276 (Opcode == Instruction::Store && !isLegalMaskedScatter(SrcVTy)))
3277 Scalarize = true;
3278 // Gather / Scatter for vector 2 is not profitable on KNL / SKX
3279 // Vector-4 of gather/scatter instruction does not exist on KNL.
3280 // We can extend it to 8 elements, but zeroing upper bits of
3281 // the mask vector will add more instructions. Right now we give the scalar
3282 // cost of vector-4 for KNL. TODO: Check, maybe the gather/scatter instruction
3283 // is better in the VariableMask case.
3284 if (ST->hasAVX512() && (VF == 2 || (VF == 4 && !ST->hasVLX())))
3285 Scalarize = true;
3286
3287 if (Scalarize)
3288 return getGSScalarCost(Opcode, SrcVTy, VariableMask, Alignment,
3289 AddressSpace);
3290
3291 return getGSVectorCost(Opcode, SrcVTy, Ptr, Alignment, AddressSpace);
3292}
3293
3294bool X86TTIImpl::isLSRCostLess(TargetTransformInfo::LSRCost &C1,
3295 TargetTransformInfo::LSRCost &C2) {
3296 // X86 specific here are "instruction number 1st priority".
3297 return std::tie(C1.Insns, C1.NumRegs, C1.AddRecCost,
3298 C1.NumIVMuls, C1.NumBaseAdds,
3299 C1.ScaleCost, C1.ImmCost, C1.SetupCost) <
3300 std::tie(C2.Insns, C2.NumRegs, C2.AddRecCost,
3301 C2.NumIVMuls, C2.NumBaseAdds,
3302 C2.ScaleCost, C2.ImmCost, C2.SetupCost);
3303}
3304
3305bool X86TTIImpl::canMacroFuseCmp() {
3306 return ST->hasMacroFusion() || ST->hasBranchFusion();
3307}
3308
3309bool X86TTIImpl::isLegalMaskedLoad(Type *DataTy, MaybeAlign Alignment) {
3310 if (!ST->hasAVX())
3311 return false;
3312
3313 // The backend can't handle a single element vector.
3314 if (isa<VectorType>(DataTy) && DataTy->getVectorNumElements() == 1)
3315 return false;
3316 Type *ScalarTy = DataTy->getScalarType();
3317
3318 if (ScalarTy->isPointerTy())
3319 return true;
3320
3321 if (ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
3322 return true;
3323
3324 if (!ScalarTy->isIntegerTy())
3325 return false;
3326
3327 unsigned IntWidth = ScalarTy->getIntegerBitWidth();
3328 return IntWidth == 32 || IntWidth == 64 ||
3329 ((IntWidth == 8 || IntWidth == 16) && ST->hasBWI());
3330}
3331
3332bool X86TTIImpl::isLegalMaskedStore(Type *DataType, MaybeAlign Alignment) {
3333 return isLegalMaskedLoad(DataType, Alignment);
3334}
3335
3336bool X86TTIImpl::isLegalNTLoad(Type *DataType, Align Alignment) {
3337 unsigned DataSize = DL.getTypeStoreSize(DataType);
3338 // The only supported nontemporal loads are for aligned vectors of 16 or 32
3339 // bytes. Note that 32-byte nontemporal vector loads are supported by AVX2
3340 // (the equivalent stores only require AVX).
3341 if (Alignment >= DataSize && (DataSize == 16 || DataSize == 32))
3342 return DataSize == 16 ? ST->hasSSE1() : ST->hasAVX2();
3343
3344 return false;
3345}
3346
3347bool X86TTIImpl::isLegalNTStore(Type *DataType, Align Alignment) {
3348 unsigned DataSize = DL.getTypeStoreSize(DataType);
3349
3350 // SSE4A supports nontemporal stores of float and double at arbitrary
3351 // alignment.
3352 if (ST->hasSSE4A() && (DataType->isFloatTy() || DataType->isDoubleTy()))
3353 return true;
3354
3355 // Besides the SSE4A subtarget exception above, only aligned stores are
3356 // available nontemporaly on any other subtarget. And only stores with a size
3357 // of 4..32 bytes (powers of 2, only) are permitted.
3358 if (Alignment < DataSize || DataSize < 4 || DataSize > 32 ||
3359 !isPowerOf2_32(DataSize))
3360 return false;
3361
3362 // 32-byte vector nontemporal stores are supported by AVX (the equivalent
3363 // loads require AVX2).
3364 if (DataSize == 32)
3365 return ST->hasAVX();
3366 else if (DataSize == 16)
3367 return ST->hasSSE1();
3368 return true;
3369}
3370
3371bool X86TTIImpl::isLegalMaskedExpandLoad(Type *DataTy) {
3372 if (!isa<VectorType>(DataTy))
3373 return false;
3374
3375 if (!ST->hasAVX512())
3376 return false;
3377
3378 // The backend can't handle a single element vector.
3379 if (DataTy->getVectorNumElements() == 1)
3380 return false;
3381
3382 Type *ScalarTy = DataTy->getVectorElementType();
3383
3384 if (ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
3385 return true;
3386
3387 if (!ScalarTy->isIntegerTy())
3388 return false;
3389
3390 unsigned IntWidth = ScalarTy->getIntegerBitWidth();
3391 return IntWidth == 32 || IntWidth == 64 ||
3392 ((IntWidth == 8 || IntWidth == 16) && ST->hasVBMI2());
3393}
3394
3395bool X86TTIImpl::isLegalMaskedCompressStore(Type *DataTy) {
3396 return isLegalMaskedExpandLoad(DataTy);
3397}
3398
3399bool X86TTIImpl::isLegalMaskedGather(Type *DataTy) {
3400 // Some CPUs have better gather performance than others.
3401 // TODO: Remove the explicit ST->hasAVX512()?, That would mean we would only
3402 // enable gather with a -march.
3403 if (!(ST->hasAVX512() || (ST->hasFastGather() && ST->hasAVX2())))
3404 return false;
3405
3406 // This function is called now in two cases: from the Loop Vectorizer
3407 // and from the Scalarizer.
3408 // When the Loop Vectorizer asks about legality of the feature,
3409 // the vectorization factor is not calculated yet. The Loop Vectorizer
3410 // sends a scalar type and the decision is based on the width of the
3411 // scalar element.
3412 // Later on, the cost model will estimate usage this intrinsic based on
3413 // the vector type.
3414 // The Scalarizer asks again about legality. It sends a vector type.
3415 // In this case we can reject non-power-of-2 vectors.
3416 // We also reject single element vectors as the type legalizer can't
3417 // scalarize it.
3418 if (isa<VectorType>(DataTy)) {
3419 unsigned NumElts = DataTy->getVectorNumElements();
3420 if (NumElts == 1 || !isPowerOf2_32(NumElts))
3421 return false;
3422 }
3423 Type *ScalarTy = DataTy->getScalarType();
3424 if (ScalarTy->isPointerTy())
3425 return true;
3426
3427 if (ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
3428 return true;
3429
3430 if (!ScalarTy->isIntegerTy())
3431 return false;
3432
3433 unsigned IntWidth = ScalarTy->getIntegerBitWidth();
3434 return IntWidth == 32 || IntWidth == 64;
3435}
3436
3437bool X86TTIImpl::isLegalMaskedScatter(Type *DataType) {
3438 // AVX2 doesn't support scatter
3439 if (!ST->hasAVX512())
3440 return false;
3441 return isLegalMaskedGather(DataType);
3442}
3443
3444bool X86TTIImpl::hasDivRemOp(Type *DataType, bool IsSigned) {
3445 EVT VT = TLI->getValueType(DL, DataType);
3446 return TLI->isOperationLegal(IsSigned ? ISD::SDIVREM : ISD::UDIVREM, VT);
3447}
3448
3449bool X86TTIImpl::isFCmpOrdCheaperThanFCmpZero(Type *Ty) {
3450 return false;
3451}
3452
3453bool X86TTIImpl::areInlineCompatible(const Function *Caller,
3454 const Function *Callee) const {
3455 const TargetMachine &TM = getTLI()->getTargetMachine();
3456
3457 // Work this as a subsetting of subtarget features.
3458 const FeatureBitset &CallerBits =
3459 TM.getSubtargetImpl(*Caller)->getFeatureBits();
3460 const FeatureBitset &CalleeBits =
3461 TM.getSubtargetImpl(*Callee)->getFeatureBits();
3462
3463 FeatureBitset RealCallerBits = CallerBits & ~InlineFeatureIgnoreList;
3464 FeatureBitset RealCalleeBits = CalleeBits & ~InlineFeatureIgnoreList;
3465 return (RealCallerBits & RealCalleeBits) == RealCalleeBits;
3466}
3467
3468bool X86TTIImpl::areFunctionArgsABICompatible(
3469 const Function *Caller, const Function *Callee,
3470 SmallPtrSetImpl<Argument *> &Args) const {
3471 if (!BaseT::areFunctionArgsABICompatible(Caller, Callee, Args))
3472 return false;
3473
3474 // If we get here, we know the target features match. If one function
3475 // considers 512-bit vectors legal and the other does not, consider them
3476 // incompatible.
3477 // FIXME Look at the arguments and only consider 512 bit or larger vectors?
3478 const TargetMachine &TM = getTLI()->getTargetMachine();
3479
3480 return TM.getSubtarget<X86Subtarget>(*Caller).useAVX512Regs() ==
3481 TM.getSubtarget<X86Subtarget>(*Callee).useAVX512Regs();
3482}
3483
3484X86TTIImpl::TTI::MemCmpExpansionOptions
3485X86TTIImpl::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const {
3486 TTI::MemCmpExpansionOptions Options;
3487 Options.MaxNumLoads = TLI->getMaxExpandSizeMemcmp(OptSize);
3488 Options.NumLoadsPerBlock = 2;
3489 if (IsZeroCmp) {
3490 // Only enable vector loads for equality comparison. Right now the vector
3491 // version is not as fast for three way compare (see #33329).
3492 const unsigned PreferredWidth = ST->getPreferVectorWidth();
3493 if (PreferredWidth >= 512 && ST->hasAVX512()) Options.LoadSizes.push_back(64);
3494 if (PreferredWidth >= 256 && ST->hasAVX()) Options.LoadSizes.push_back(32);
3495 if (PreferredWidth >= 128 && ST->hasSSE2()) Options.LoadSizes.push_back(16);
3496 // All GPR and vector loads can be unaligned.
3497 Options.AllowOverlappingLoads = true;
3498 }
3499 if (ST->is64Bit()) {
3500 Options.LoadSizes.push_back(8);
3501 }
3502 Options.LoadSizes.push_back(4);
3503 Options.LoadSizes.push_back(2);
3504 Options.LoadSizes.push_back(1);
3505 return Options;
3506}
3507
3508bool X86TTIImpl::enableInterleavedAccessVectorization() {
3509 // TODO: We expect this to be beneficial regardless of arch,
3510 // but there are currently some unexplained performance artifacts on Atom.
3511 // As a temporary solution, disable on Atom.
3512 return !(ST->isAtom());
3513}
3514
3515// Get estimation for interleaved load/store operations for AVX2.
3516// \p Factor is the interleaved-access factor (stride) - number of
3517// (interleaved) elements in the group.
3518// \p Indices contains the indices for a strided load: when the
3519// interleaved load has gaps they indicate which elements are used.
3520// If Indices is empty (or if the number of indices is equal to the size
3521// of the interleaved-access as given in \p Factor) the access has no gaps.
3522//
3523// As opposed to AVX-512, AVX2 does not have generic shuffles that allow
3524// computing the cost using a generic formula as a function of generic
3525// shuffles. We therefore use a lookup table instead, filled according to
3526// the instruction sequences that codegen currently generates.
3527int X86TTIImpl::getInterleavedMemoryOpCostAVX2(unsigned Opcode, Type *VecTy,
3528 unsigned Factor,
3529 ArrayRef<unsigned> Indices,
3530 unsigned Alignment,
3531 unsigned AddressSpace,
3532 bool UseMaskForCond,
3533 bool UseMaskForGaps) {
3534
3535 if (UseMaskForCond || UseMaskForGaps)
3536 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
3537 Alignment, AddressSpace,
3538 UseMaskForCond, UseMaskForGaps);
3539
3540 // We currently Support only fully-interleaved groups, with no gaps.
3541 // TODO: Support also strided loads (interleaved-groups with gaps).
3542 if (Indices.size() && Indices.size() != Factor)
3543 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
3544 Alignment, AddressSpace);
3545
3546 // VecTy for interleave memop is <VF*Factor x Elt>.
3547 // So, for VF=4, Interleave Factor = 3, Element type = i32 we have
3548 // VecTy = <12 x i32>.
3549 MVT LegalVT = getTLI()->getTypeLegalizationCost(DL, VecTy).second;
3550
3551 // This function can be called with VecTy=<6xi128>, Factor=3, in which case
3552 // the VF=2, while v2i128 is an unsupported MVT vector type
3553 // (see MachineValueType.h::getVectorVT()).
3554 if (!LegalVT.isVector())
3555 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
3556 Alignment, AddressSpace);
3557
3558 unsigned VF = VecTy->getVectorNumElements() / Factor;
3559 Type *ScalarTy = VecTy->getVectorElementType();
3560
3561 // Calculate the number of memory operations (NumOfMemOps), required
3562 // for load/store the VecTy.
3563 unsigned VecTySize = DL.getTypeStoreSize(VecTy);
3564 unsigned LegalVTSize = LegalVT.getStoreSize();
3565 unsigned NumOfMemOps = (VecTySize + LegalVTSize - 1) / LegalVTSize;
3566
3567 // Get the cost of one memory operation.
3568 Type *SingleMemOpTy = VectorType::get(VecTy->getVectorElementType(),
3569 LegalVT.getVectorNumElements());
3570 unsigned MemOpCost = getMemoryOpCost(Opcode, SingleMemOpTy,
3571 MaybeAlign(Alignment), AddressSpace);
3572
3573 VectorType *VT = VectorType::get(ScalarTy, VF);
3574 EVT ETy = TLI->getValueType(DL, VT);
3575 if (!ETy.isSimple())
3576 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
3577 Alignment, AddressSpace);
3578
3579 // TODO: Complete for other data-types and strides.
3580 // Each combination of Stride, ElementTy and VF results in a different
3581 // sequence; The cost tables are therefore accessed with:
3582 // Factor (stride) and VectorType=VFxElemType.
3583 // The Cost accounts only for the shuffle sequence;
3584 // The cost of the loads/stores is accounted for separately.
3585 //
3586 static const CostTblEntry AVX2InterleavedLoadTbl[] = {
3587 { 2, MVT::v4i64, 6 }, //(load 8i64 and) deinterleave into 2 x 4i64
3588 { 2, MVT::v4f64, 6 }, //(load 8f64 and) deinterleave into 2 x 4f64
3589
3590 { 3, MVT::v2i8, 10 }, //(load 6i8 and) deinterleave into 3 x 2i8
3591 { 3, MVT::v4i8, 4 }, //(load 12i8 and) deinterleave into 3 x 4i8
3592 { 3, MVT::v8i8, 9 }, //(load 24i8 and) deinterleave into 3 x 8i8
3593 { 3, MVT::v16i8, 11}, //(load 48i8 and) deinterleave into 3 x 16i8
3594 { 3, MVT::v32i8, 13}, //(load 96i8 and) deinterleave into 3 x 32i8
3595 { 3, MVT::v8f32, 17 }, //(load 24f32 and)deinterleave into 3 x 8f32
3596
3597 { 4, MVT::v2i8, 12 }, //(load 8i8 and) deinterleave into 4 x 2i8
3598 { 4, MVT::v4i8, 4 }, //(load 16i8 and) deinterleave into 4 x 4i8
3599 { 4, MVT::v8i8, 20 }, //(load 32i8 and) deinterleave into 4 x 8i8
3600 { 4, MVT::v16i8, 39 }, //(load 64i8 and) deinterleave into 4 x 16i8
3601 { 4, MVT::v32i8, 80 }, //(load 128i8 and) deinterleave into 4 x 32i8
3602
3603 { 8, MVT::v8f32, 40 } //(load 64f32 and)deinterleave into 8 x 8f32
3604 };
3605
3606 static const CostTblEntry AVX2InterleavedStoreTbl[] = {
3607 { 2, MVT::v4i64, 6 }, //interleave into 2 x 4i64 into 8i64 (and store)
3608 { 2, MVT::v4f64, 6 }, //interleave into 2 x 4f64 into 8f64 (and store)
3609
3610 { 3, MVT::v2i8, 7 }, //interleave 3 x 2i8 into 6i8 (and store)
3611 { 3, MVT::v4i8, 8 }, //interleave 3 x 4i8 into 12i8 (and store)
3612 { 3, MVT::v8i8, 11 }, //interleave 3 x 8i8 into 24i8 (and store)
3613 { 3, MVT::v16i8, 11 }, //interleave 3 x 16i8 into 48i8 (and store)
3614 { 3, MVT::v32i8, 13 }, //interleave 3 x 32i8 into 96i8 (and store)
3615
3616 { 4, MVT::v2i8, 12 }, //interleave 4 x 2i8 into 8i8 (and store)
3617 { 4, MVT::v4i8, 9 }, //interleave 4 x 4i8 into 16i8 (and store)
3618 { 4, MVT::v8i8, 10 }, //interleave 4 x 8i8 into 32i8 (and store)
3619 { 4, MVT::v16i8, 10 }, //interleave 4 x 16i8 into 64i8 (and store)
3620 { 4, MVT::v32i8, 12 } //interleave 4 x 32i8 into 128i8 (and store)
3621 };
3622
3623 if (Opcode == Instruction::Load) {
3624 if (const auto *Entry =
3625 CostTableLookup(AVX2InterleavedLoadTbl, Factor, ETy.getSimpleVT()))
3626 return NumOfMemOps * MemOpCost + Entry->Cost;
3627 } else {
3628 assert(Opcode == Instruction::Store &&((Opcode == Instruction::Store && "Expected Store Instruction at this point"
) ? static_cast<void> (0) : __assert_fail ("Opcode == Instruction::Store && \"Expected Store Instruction at this point\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 3629, __PRETTY_FUNCTION__))
3629 "Expected Store Instruction at this point")((Opcode == Instruction::Store && "Expected Store Instruction at this point"
) ? static_cast<void> (0) : __assert_fail ("Opcode == Instruction::Store && \"Expected Store Instruction at this point\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 3629, __PRETTY_FUNCTION__))
;
3630 if (const auto *Entry =
3631 CostTableLookup(AVX2InterleavedStoreTbl, Factor, ETy.getSimpleVT()))
3632 return NumOfMemOps * MemOpCost + Entry->Cost;
3633 }
3634
3635 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
3636 Alignment, AddressSpace);
3637}
3638
3639// Get estimation for interleaved load/store operations and strided load.
3640// \p Indices contains indices for strided load.
3641// \p Factor - the factor of interleaving.
3642// AVX-512 provides 3-src shuffles that significantly reduces the cost.
3643int X86TTIImpl::getInterleavedMemoryOpCostAVX512(unsigned Opcode, Type *VecTy,
3644 unsigned Factor,
3645 ArrayRef<unsigned> Indices,
3646 unsigned Alignment,
3647 unsigned AddressSpace,
3648 bool UseMaskForCond,
3649 bool UseMaskForGaps) {
3650
3651 if (UseMaskForCond || UseMaskForGaps)
3652 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
3653 Alignment, AddressSpace,
3654 UseMaskForCond, UseMaskForGaps);
3655
3656 // VecTy for interleave memop is <VF*Factor x Elt>.
3657 // So, for VF=4, Interleave Factor = 3, Element type = i32 we have
3658 // VecTy = <12 x i32>.
3659
3660 // Calculate the number of memory operations (NumOfMemOps), required
3661 // for load/store the VecTy.
3662 MVT LegalVT = getTLI()->getTypeLegalizationCost(DL, VecTy).second;
3663 unsigned VecTySize = DL.getTypeStoreSize(VecTy);
3664 unsigned LegalVTSize = LegalVT.getStoreSize();
3665 unsigned NumOfMemOps = (VecTySize + LegalVTSize - 1) / LegalVTSize;
3666
3667 // Get the cost of one memory operation.
3668 Type *SingleMemOpTy = VectorType::get(VecTy->getVectorElementType(),
3669 LegalVT.getVectorNumElements());
3670 unsigned MemOpCost = getMemoryOpCost(Opcode, SingleMemOpTy,
3671 MaybeAlign(Alignment), AddressSpace);
3672
3673 unsigned VF = VecTy->getVectorNumElements() / Factor;
3674 MVT VT = MVT::getVectorVT(MVT::getVT(VecTy->getScalarType()), VF);
3675
3676 if (Opcode == Instruction::Load) {
3677 // The tables (AVX512InterleavedLoadTbl and AVX512InterleavedStoreTbl)
3678 // contain the cost of the optimized shuffle sequence that the
3679 // X86InterleavedAccess pass will generate.
3680 // The cost of loads and stores are computed separately from the table.
3681
3682 // X86InterleavedAccess support only the following interleaved-access group.
3683 static const CostTblEntry AVX512InterleavedLoadTbl[] = {
3684 {3, MVT::v16i8, 12}, //(load 48i8 and) deinterleave into 3 x 16i8
3685 {3, MVT::v32i8, 14}, //(load 96i8 and) deinterleave into 3 x 32i8
3686 {3, MVT::v64i8, 22}, //(load 96i8 and) deinterleave into 3 x 32i8
3687 };
3688
3689 if (const auto *Entry =
3690 CostTableLookup(AVX512InterleavedLoadTbl, Factor, VT))
3691 return NumOfMemOps * MemOpCost + Entry->Cost;
3692 //If an entry does not exist, fallback to the default implementation.
3693
3694 // Kind of shuffle depends on number of loaded values.
3695 // If we load the entire data in one register, we can use a 1-src shuffle.
3696 // Otherwise, we'll merge 2 sources in each operation.
3697 TTI::ShuffleKind ShuffleKind =
3698 (NumOfMemOps > 1) ? TTI::SK_PermuteTwoSrc : TTI::SK_PermuteSingleSrc;
3699
3700 unsigned ShuffleCost =
3701 getShuffleCost(ShuffleKind, SingleMemOpTy, 0, nullptr);
3702
3703 unsigned NumOfLoadsInInterleaveGrp =
3704 Indices.size() ? Indices.size() : Factor;
3705 Type *ResultTy = VectorType::get(VecTy->getVectorElementType(),
3706 VecTy->getVectorNumElements() / Factor);
3707 unsigned NumOfResults =
3708 getTLI()->getTypeLegalizationCost(DL, ResultTy).first *
3709 NumOfLoadsInInterleaveGrp;
3710
3711 // About a half of the loads may be folded in shuffles when we have only
3712 // one result. If we have more than one result, we do not fold loads at all.
3713 unsigned NumOfUnfoldedLoads =
3714 NumOfResults > 1 ? NumOfMemOps : NumOfMemOps / 2;
3715
3716 // Get a number of shuffle operations per result.
3717 unsigned NumOfShufflesPerResult =
3718 std::max((unsigned)1, (unsigned)(NumOfMemOps - 1));
3719
3720 // The SK_MergeTwoSrc shuffle clobbers one of src operands.
3721 // When we have more than one destination, we need additional instructions
3722 // to keep sources.
3723 unsigned NumOfMoves = 0;
3724 if (NumOfResults > 1 && ShuffleKind == TTI::SK_PermuteTwoSrc)
3725 NumOfMoves = NumOfResults * NumOfShufflesPerResult / 2;
3726
3727 int Cost = NumOfResults * NumOfShufflesPerResult * ShuffleCost +
3728 NumOfUnfoldedLoads * MemOpCost + NumOfMoves;
3729
3730 return Cost;
3731 }
3732
3733 // Store.
3734 assert(Opcode == Instruction::Store &&((Opcode == Instruction::Store && "Expected Store Instruction at this point"
) ? static_cast<void> (0) : __assert_fail ("Opcode == Instruction::Store && \"Expected Store Instruction at this point\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 3735, __PRETTY_FUNCTION__))
3735 "Expected Store Instruction at this point")((Opcode == Instruction::Store && "Expected Store Instruction at this point"
) ? static_cast<void> (0) : __assert_fail ("Opcode == Instruction::Store && \"Expected Store Instruction at this point\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/X86/X86TargetTransformInfo.cpp"
, 3735, __PRETTY_FUNCTION__))
;
3736 // X86InterleavedAccess support only the following interleaved-access group.
3737 static const CostTblEntry AVX512InterleavedStoreTbl[] = {
3738 {3, MVT::v16i8, 12}, // interleave 3 x 16i8 into 48i8 (and store)
3739 {3, MVT::v32i8, 14}, // interleave 3 x 32i8 into 96i8 (and store)
3740 {3, MVT::v64i8, 26}, // interleave 3 x 64i8 into 96i8 (and store)
3741
3742 {4, MVT::v8i8, 10}, // interleave 4 x 8i8 into 32i8 (and store)
3743 {4, MVT::v16i8, 11}, // interleave 4 x 16i8 into 64i8 (and store)
3744 {4, MVT::v32i8, 14}, // interleave 4 x 32i8 into 128i8 (and store)
3745 {4, MVT::v64i8, 24} // interleave 4 x 32i8 into 256i8 (and store)
3746 };
3747
3748 if (const auto *Entry =
3749 CostTableLookup(AVX512InterleavedStoreTbl, Factor, VT))
3750 return NumOfMemOps * MemOpCost + Entry->Cost;
3751 //If an entry does not exist, fallback to the default implementation.
3752
3753 // There is no strided stores meanwhile. And store can't be folded in
3754 // shuffle.
3755 unsigned NumOfSources = Factor; // The number of values to be merged.
3756 unsigned ShuffleCost =
3757 getShuffleCost(TTI::SK_PermuteTwoSrc, SingleMemOpTy, 0, nullptr);
3758 unsigned NumOfShufflesPerStore = NumOfSources - 1;
3759
3760 // The SK_MergeTwoSrc shuffle clobbers one of src operands.
3761 // We need additional instructions to keep sources.
3762 unsigned NumOfMoves = NumOfMemOps * NumOfShufflesPerStore / 2;
3763 int Cost = NumOfMemOps * (MemOpCost + NumOfShufflesPerStore * ShuffleCost) +
3764 NumOfMoves;
3765 return Cost;
3766}
3767
3768int X86TTIImpl::getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
3769 unsigned Factor,
3770 ArrayRef<unsigned> Indices,
3771 unsigned Alignment,
3772 unsigned AddressSpace,
3773 bool UseMaskForCond,
3774 bool UseMaskForGaps) {
3775 auto isSupportedOnAVX512 = [](Type *VecTy, bool HasBW) {
3776 Type *EltTy = VecTy->getVectorElementType();
3777 if (EltTy->isFloatTy() || EltTy->isDoubleTy() || EltTy->isIntegerTy(64) ||
3778 EltTy->isIntegerTy(32) || EltTy->isPointerTy())
3779 return true;
3780 if (EltTy->isIntegerTy(16) || EltTy->isIntegerTy(8))
3781 return HasBW;
3782 return false;
3783 };
3784 if (ST->hasAVX512() && isSupportedOnAVX512(VecTy, ST->hasBWI()))
3785 return getInterleavedMemoryOpCostAVX512(Opcode, VecTy, Factor, Indices,
3786 Alignment, AddressSpace,
3787 UseMaskForCond, UseMaskForGaps);
3788 if (ST->hasAVX2())
3789 return getInterleavedMemoryOpCostAVX2(Opcode, VecTy, Factor, Indices,
3790 Alignment, AddressSpace,
3791 UseMaskForCond, UseMaskForGaps);
3792
3793 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
3794 Alignment, AddressSpace,
3795 UseMaskForCond, UseMaskForGaps);
3796}

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h

1//===- TargetTransformInfoImpl.h --------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8/// \file
9/// This file provides helpers for the implementation of
10/// a TargetTransformInfo-conforming class.
11///
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ANALYSIS_TARGETTRANSFORMINFOIMPL_H
15#define LLVM_ANALYSIS_TARGETTRANSFORMINFOIMPL_H
16
17#include "llvm/Analysis/ScalarEvolutionExpressions.h"
18#include "llvm/Analysis/TargetTransformInfo.h"
19#include "llvm/Analysis/VectorUtils.h"
20#include "llvm/IR/CallSite.h"
21#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/Function.h"
23#include "llvm/IR/GetElementPtrTypeIterator.h"
24#include "llvm/IR/Operator.h"
25#include "llvm/IR/Type.h"
26
27namespace llvm {
28
29/// Base class for use as a mix-in that aids implementing
30/// a TargetTransformInfo-compatible class.
31class TargetTransformInfoImplBase {
32protected:
33 typedef TargetTransformInfo TTI;
34
35 const DataLayout &DL;
36
37 explicit TargetTransformInfoImplBase(const DataLayout &DL) : DL(DL) {}
38
39public:
40 // Provide value semantics. MSVC requires that we spell all of these out.
41 TargetTransformInfoImplBase(const TargetTransformInfoImplBase &Arg)
42 : DL(Arg.DL) {}
43 TargetTransformInfoImplBase(TargetTransformInfoImplBase &&Arg) : DL(Arg.DL) {}
44
45 const DataLayout &getDataLayout() const { return DL; }
46
47 unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) {
48 switch (Opcode) {
49 default:
50 // By default, just classify everything as 'basic'.
51 return TTI::TCC_Basic;
52
53 case Instruction::GetElementPtr:
54 llvm_unreachable("Use getGEPCost for GEP operations!")::llvm::llvm_unreachable_internal("Use getGEPCost for GEP operations!"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h"
, 54)
;
55
56 case Instruction::BitCast:
57 assert(OpTy && "Cast instructions must provide the operand type")((OpTy && "Cast instructions must provide the operand type"
) ? static_cast<void> (0) : __assert_fail ("OpTy && \"Cast instructions must provide the operand type\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h"
, 57, __PRETTY_FUNCTION__))
;
58 if (Ty == OpTy || (Ty->isPointerTy() && OpTy->isPointerTy()))
59 // Identity and pointer-to-pointer casts are free.
60 return TTI::TCC_Free;
61
62 // Otherwise, the default basic cost is used.
63 return TTI::TCC_Basic;
64
65 case Instruction::FDiv:
66 case Instruction::FRem:
67 case Instruction::SDiv:
68 case Instruction::SRem:
69 case Instruction::UDiv:
70 case Instruction::URem:
71 return TTI::TCC_Expensive;
72
73 case Instruction::IntToPtr: {
74 // An inttoptr cast is free so long as the input is a legal integer type
75 // which doesn't contain values outside the range of a pointer.
76 unsigned OpSize = OpTy->getScalarSizeInBits();
77 if (DL.isLegalInteger(OpSize) &&
78 OpSize <= DL.getPointerTypeSizeInBits(Ty))
79 return TTI::TCC_Free;
80
81 // Otherwise it's not a no-op.
82 return TTI::TCC_Basic;
83 }
84 case Instruction::PtrToInt: {
85 // A ptrtoint cast is free so long as the result is large enough to store
86 // the pointer, and a legal integer type.
87 unsigned DestSize = Ty->getScalarSizeInBits();
88 if (DL.isLegalInteger(DestSize) &&
89 DestSize >= DL.getPointerTypeSizeInBits(OpTy))
90 return TTI::TCC_Free;
91
92 // Otherwise it's not a no-op.
93 return TTI::TCC_Basic;
94 }
95 case Instruction::Trunc:
96 // trunc to a native type is free (assuming the target has compare and
97 // shift-right of the same width).
98 if (DL.isLegalInteger(DL.getTypeSizeInBits(Ty)))
99 return TTI::TCC_Free;
100
101 return TTI::TCC_Basic;
102 }
103 }
104
105 int getGEPCost(Type *PointeeType, const Value *Ptr,
106 ArrayRef<const Value *> Operands) {
107 // In the basic model, we just assume that all-constant GEPs will be folded
108 // into their uses via addressing modes.
109 for (unsigned Idx = 0, Size = Operands.size(); Idx != Size; ++Idx)
110 if (!isa<Constant>(Operands[Idx]))
111 return TTI::TCC_Basic;
112
113 return TTI::TCC_Free;
114 }
115
116 unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
117 unsigned &JTSize,
118 ProfileSummaryInfo *PSI,
119 BlockFrequencyInfo *BFI) {
120 (void)PSI;
121 (void)BFI;
122 JTSize = 0;
123 return SI.getNumCases();
124 }
125
126 int getExtCost(const Instruction *I, const Value *Src) {
127 return TTI::TCC_Basic;
128 }
129
130 unsigned getCallCost(FunctionType *FTy, int NumArgs, const User *U) {
131 assert(FTy && "FunctionType must be provided to this routine.")((FTy && "FunctionType must be provided to this routine."
) ? static_cast<void> (0) : __assert_fail ("FTy && \"FunctionType must be provided to this routine.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h"
, 131, __PRETTY_FUNCTION__))
;
132
133 // The target-independent implementation just measures the size of the
134 // function by approximating that each argument will take on average one
135 // instruction to prepare.
136
137 if (NumArgs < 0)
138 // Set the argument number to the number of explicit arguments in the
139 // function.
140 NumArgs = FTy->getNumParams();
141
142 return TTI::TCC_Basic * (NumArgs + 1);
143 }
144
145 unsigned getInliningThresholdMultiplier() { return 1; }
146
147 int getInlinerVectorBonusPercent() { return 150; }
148
149 unsigned getMemcpyCost(const Instruction *I) {
150 return TTI::TCC_Expensive;
151 }
152
153 bool hasBranchDivergence() { return false; }
154
155 bool isSourceOfDivergence(const Value *V) { return false; }
156
157 bool isAlwaysUniform(const Value *V) { return false; }
158
159 unsigned getFlatAddressSpace () {
160 return -1;
161 }
162
163 bool collectFlatAddressOperands(SmallVectorImpl<int> &OpIndexes,
164 Intrinsic::ID IID) const {
165 return false;
166 }
167
168 bool rewriteIntrinsicWithAddressSpace(IntrinsicInst *II,
169 Value *OldV, Value *NewV) const {
170 return false;
171 }
172
173 bool isLoweredToCall(const Function *F) {
174 assert(F && "A concrete function must be provided to this routine.")((F && "A concrete function must be provided to this routine."
) ? static_cast<void> (0) : __assert_fail ("F && \"A concrete function must be provided to this routine.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h"
, 174, __PRETTY_FUNCTION__))
;
175
176 // FIXME: These should almost certainly not be handled here, and instead
177 // handled with the help of TLI or the target itself. This was largely
178 // ported from existing analysis heuristics here so that such refactorings
179 // can take place in the future.
180
181 if (F->isIntrinsic())
182 return false;
183
184 if (F->hasLocalLinkage() || !F->hasName())
185 return true;
186
187 StringRef Name = F->getName();
188
189 // These will all likely lower to a single selection DAG node.
190 if (Name == "copysign" || Name == "copysignf" || Name == "copysignl" ||
191 Name == "fabs" || Name == "fabsf" || Name == "fabsl" || Name == "sin" ||
192 Name == "fmin" || Name == "fminf" || Name == "fminl" ||
193 Name == "fmax" || Name == "fmaxf" || Name == "fmaxl" ||
194 Name == "sinf" || Name == "sinl" || Name == "cos" || Name == "cosf" ||
195 Name == "cosl" || Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl")
196 return false;
197
198 // These are all likely to be optimized into something smaller.
199 if (Name == "pow" || Name == "powf" || Name == "powl" || Name == "exp2" ||
200 Name == "exp2l" || Name == "exp2f" || Name == "floor" ||
201 Name == "floorf" || Name == "ceil" || Name == "round" ||
202 Name == "ffs" || Name == "ffsl" || Name == "abs" || Name == "labs" ||
203 Name == "llabs")
204 return false;
205
206 return true;
207 }
208
209 bool isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
210 AssumptionCache &AC,
211 TargetLibraryInfo *LibInfo,
212 HardwareLoopInfo &HWLoopInfo) {
213 return false;
214 }
215
216 bool preferPredicateOverEpilogue(Loop *L, LoopInfo *LI, ScalarEvolution &SE,
217 AssumptionCache &AC, TargetLibraryInfo *TLI,
218 DominatorTree *DT,
219 const LoopAccessInfo *LAI) const {
220 return false;
221 }
222
223 void getUnrollingPreferences(Loop *, ScalarEvolution &,
224 TTI::UnrollingPreferences &) {}
225
226 bool isLegalAddImmediate(int64_t Imm) { return false; }
227
228 bool isLegalICmpImmediate(int64_t Imm) { return false; }
229
230 bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
231 bool HasBaseReg, int64_t Scale,
232 unsigned AddrSpace, Instruction *I = nullptr) {
233 // Guess that only reg and reg+reg addressing is allowed. This heuristic is
234 // taken from the implementation of LSR.
235 return !BaseGV && BaseOffset == 0 && (Scale == 0 || Scale == 1);
236 }
237
238 bool isLSRCostLess(TTI::LSRCost &C1, TTI::LSRCost &C2) {
239 return std::tie(C1.NumRegs, C1.AddRecCost, C1.NumIVMuls, C1.NumBaseAdds,
240 C1.ScaleCost, C1.ImmCost, C1.SetupCost) <
241 std::tie(C2.NumRegs, C2.AddRecCost, C2.NumIVMuls, C2.NumBaseAdds,
242 C2.ScaleCost, C2.ImmCost, C2.SetupCost);
243 }
244
245 bool canMacroFuseCmp() { return false; }
246
247 bool canSaveCmp(Loop *L, BranchInst **BI, ScalarEvolution *SE, LoopInfo *LI,
248 DominatorTree *DT, AssumptionCache *AC,
249 TargetLibraryInfo *LibInfo) {
250 return false;
251 }
252
253 bool shouldFavorPostInc() const { return false; }
254
255 bool shouldFavorBackedgeIndex(const Loop *L) const { return false; }
256
257 bool isLegalMaskedStore(Type *DataType, MaybeAlign Alignment) { return false; }
258
259 bool isLegalMaskedLoad(Type *DataType, MaybeAlign Alignment) { return false; }
260
261 bool isLegalNTStore(Type *DataType, Align Alignment) {
262 // By default, assume nontemporal memory stores are available for stores
263 // that are aligned and have a size that is a power of 2.
264 unsigned DataSize = DL.getTypeStoreSize(DataType);
265 return Alignment >= DataSize && isPowerOf2_32(DataSize);
266 }
267
268 bool isLegalNTLoad(Type *DataType, Align Alignment) {
269 // By default, assume nontemporal memory loads are available for loads that
270 // are aligned and have a size that is a power of 2.
271 unsigned DataSize = DL.getTypeStoreSize(DataType);
272 return Alignment >= DataSize && isPowerOf2_32(DataSize);
273 }
274
275 bool isLegalMaskedScatter(Type *DataType) { return false; }
276
277 bool isLegalMaskedGather(Type *DataType) { return false; }
278
279 bool isLegalMaskedCompressStore(Type *DataType) { return false; }
280
281 bool isLegalMaskedExpandLoad(Type *DataType) { return false; }
282
283 bool hasDivRemOp(Type *DataType, bool IsSigned) { return false; }
284
285 bool hasVolatileVariant(Instruction *I, unsigned AddrSpace) { return false; }
286
287 bool prefersVectorizedAddressing() { return true; }
288
289 int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
290 bool HasBaseReg, int64_t Scale, unsigned AddrSpace) {
291 // Guess that all legal addressing mode are free.
292 if (isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg,
293 Scale, AddrSpace))
294 return 0;
295 return -1;
296 }
297
298 bool LSRWithInstrQueries() { return false; }
299
300 bool isTruncateFree(Type *Ty1, Type *Ty2) { return false; }
301
302 bool isProfitableToHoist(Instruction *I) { return true; }
303
304 bool useAA() { return false; }
305
306 bool isTypeLegal(Type *Ty) { return false; }
307
308 bool shouldBuildLookupTables() { return true; }
309 bool shouldBuildLookupTablesForConstant(Constant *C) { return true; }
310
311 bool useColdCCForColdCall(Function &F) { return false; }
312
313 unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) {
314 return 0;
315 }
316
317 unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
318 unsigned VF) { return 0; }
319
320 bool supportsEfficientVectorElementLoadStore() { return false; }
321
322 bool enableAggressiveInterleaving(bool LoopHasReductions) { return false; }
323
324 TTI::MemCmpExpansionOptions enableMemCmpExpansion(bool OptSize,
325 bool IsZeroCmp) const {
326 return {};
327 }
328
329 bool enableInterleavedAccessVectorization() { return false; }
330
331 bool enableMaskedInterleavedAccessVectorization() { return false; }
332
333 bool isFPVectorizationPotentiallyUnsafe() { return false; }
334
335 bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
336 unsigned BitWidth,
337 unsigned AddressSpace,
338 unsigned Alignment,
339 bool *Fast) { return false; }
340
341 TTI::PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) {
342 return TTI::PSK_Software;
343 }
344
345 bool haveFastSqrt(Type *Ty) { return false; }
346
347 bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) { return true; }
348
349 unsigned getFPOpCost(Type *Ty) { return TargetTransformInfo::TCC_Basic; }
350
351 int getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
352 Type *Ty) {
353 return 0;
354 }
355
356 unsigned getIntImmCost(const APInt &Imm, Type *Ty) { return TTI::TCC_Basic; }
357
358 unsigned getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
359 Type *Ty) {
360 return TTI::TCC_Free;
361 }
362
363 unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
364 Type *Ty) {
365 return TTI::TCC_Free;
366 }
367
368 unsigned getNumberOfRegisters(unsigned ClassID) const { return 8; }
369
370 unsigned getRegisterClassForType(bool Vector, Type *Ty = nullptr) const {
371 return Vector ? 1 : 0;
372 };
373
374 const char* getRegisterClassName(unsigned ClassID) const {
375 switch (ClassID) {
376 default:
377 return "Generic::Unknown Register Class";
378 case 0: return "Generic::ScalarRC";
379 case 1: return "Generic::VectorRC";
380 }
381 }
382
383 unsigned getRegisterBitWidth(bool Vector) const { return 32; }
384
385 unsigned getMinVectorRegisterBitWidth() { return 128; }
386
387 bool shouldMaximizeVectorBandwidth(bool OptSize) const { return false; }
388
389 unsigned getMinimumVF(unsigned ElemWidth) const { return 0; }
390
391 bool
392 shouldConsiderAddressTypePromotion(const Instruction &I,
393 bool &AllowPromotionWithoutCommonHeader) {
394 AllowPromotionWithoutCommonHeader = false;
395 return false;
396 }
397
398 unsigned getCacheLineSize() const { return 0; }
399
400 llvm::Optional<unsigned> getCacheSize(TargetTransformInfo::CacheLevel Level) const {
401 switch (Level) {
402 case TargetTransformInfo::CacheLevel::L1D:
403 LLVM_FALLTHROUGH[[gnu::fallthrough]];
404 case TargetTransformInfo::CacheLevel::L2D:
405 return llvm::Optional<unsigned>();
406 }
407 llvm_unreachable("Unknown TargetTransformInfo::CacheLevel")::llvm::llvm_unreachable_internal("Unknown TargetTransformInfo::CacheLevel"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h"
, 407)
;
408 }
409
410 llvm::Optional<unsigned> getCacheAssociativity(
411 TargetTransformInfo::CacheLevel Level) const {
412 switch (Level) {
413 case TargetTransformInfo::CacheLevel::L1D:
414 LLVM_FALLTHROUGH[[gnu::fallthrough]];
415 case TargetTransformInfo::CacheLevel::L2D:
416 return llvm::Optional<unsigned>();
417 }
418
419 llvm_unreachable("Unknown TargetTransformInfo::CacheLevel")::llvm::llvm_unreachable_internal("Unknown TargetTransformInfo::CacheLevel"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h"
, 419)
;
420 }
421
422 unsigned getPrefetchDistance() const { return 0; }
423 unsigned getMinPrefetchStride() const { return 1; }
424 unsigned getMaxPrefetchIterationsAhead() const { return UINT_MAX(2147483647 *2U +1U); }
425
426 unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
427
428 unsigned getArithmeticInstrCost(unsigned Opcode, Type *Ty,
429 TTI::OperandValueKind Opd1Info,
430 TTI::OperandValueKind Opd2Info,
431 TTI::OperandValueProperties Opd1PropInfo,
432 TTI::OperandValueProperties Opd2PropInfo,
433 ArrayRef<const Value *> Args) {
434 return 1;
435 }
436
437 unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Ty, int Index,
438 Type *SubTp) {
439 return 1;
440 }
441
442 unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
443 const Instruction *I) { return 1; }
444
445 unsigned getExtractWithExtendCost(unsigned Opcode, Type *Dst,
446 VectorType *VecTy, unsigned Index) {
447 return 1;
448 }
449
450 unsigned getCFInstrCost(unsigned Opcode) { return 1; }
451
452 unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
453 const Instruction *I) {
454 return 1;
455 }
456
457 unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
458 return 1;
459 }
460
461 unsigned getMemoryOpCost(unsigned Opcode, Type *Src, MaybeAlign Alignment,
462 unsigned AddressSpace, const Instruction *I) {
463 return 1;
464 }
465
466 unsigned getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
467 unsigned AddressSpace) {
468 return 1;
469 }
470
471 unsigned getGatherScatterOpCost(unsigned Opcode, Type *DataTy, Value *Ptr,
472 bool VariableMask,
473 unsigned Alignment) {
474 return 1;
475 }
476
477 unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
478 unsigned Factor,
479 ArrayRef<unsigned> Indices,
480 unsigned Alignment, unsigned AddressSpace,
481 bool UseMaskForCond = false,
482 bool UseMaskForGaps = false) {
483 return 1;
484 }
485
486 unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
487 ArrayRef<Type *> Tys, FastMathFlags FMF,
488 unsigned ScalarizationCostPassed) {
489 return 1;
490 }
491 unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
492 ArrayRef<Value *> Args, FastMathFlags FMF, unsigned VF) {
493 return 1;
494 }
495
496 unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) {
497 return 1;
498 }
499
500 unsigned getNumberOfParts(Type *Tp) { return 0; }
501
502 unsigned getAddressComputationCost(Type *Tp, ScalarEvolution *,
503 const SCEV *) {
504 return 0;
505 }
506
507 unsigned getArithmeticReductionCost(unsigned, Type *, bool) { return 1; }
508
509 unsigned getMinMaxReductionCost(Type *, Type *, bool, bool) { return 1; }
510
511 unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) { return 0; }
512
513 bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) {
514 return false;
515 }
516
517 unsigned getAtomicMemIntrinsicMaxElementSize() const {
518 // Note for overrides: You must ensure for all element unordered-atomic
519 // memory intrinsics that all power-of-2 element sizes up to, and
520 // including, the return value of this method have a corresponding
521 // runtime lib call. These runtime lib call definitions can be found
522 // in RuntimeLibcalls.h
523 return 0;
524 }
525
526 Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
527 Type *ExpectedType) {
528 return nullptr;
529 }
530
531 Type *getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length,
532 unsigned SrcAlign, unsigned DestAlign) const {
533 return Type::getInt8Ty(Context);
534 }
535
536 void getMemcpyLoopResidualLoweringType(SmallVectorImpl<Type *> &OpsOut,
537 LLVMContext &Context,
538 unsigned RemainingBytes,
539 unsigned SrcAlign,
540 unsigned DestAlign) const {
541 for (unsigned i = 0; i != RemainingBytes; ++i)
542 OpsOut.push_back(Type::getInt8Ty(Context));
543 }
544
545 bool areInlineCompatible(const Function *Caller,
546 const Function *Callee) const {
547 return (Caller->getFnAttribute("target-cpu") ==
548 Callee->getFnAttribute("target-cpu")) &&
549 (Caller->getFnAttribute("target-features") ==
550 Callee->getFnAttribute("target-features"));
551 }
552
553 bool areFunctionArgsABICompatible(const Function *Caller, const Function *Callee,
554 SmallPtrSetImpl<Argument *> &Args) const {
555 return (Caller->getFnAttribute("target-cpu") ==
556 Callee->getFnAttribute("target-cpu")) &&
557 (Caller->getFnAttribute("target-features") ==
558 Callee->getFnAttribute("target-features"));
559 }
560
561 bool isIndexedLoadLegal(TTI::MemIndexedMode Mode, Type *Ty,
562 const DataLayout &DL) const {
563 return false;
564 }
565
566 bool isIndexedStoreLegal(TTI::MemIndexedMode Mode, Type *Ty,
567 const DataLayout &DL) const {
568 return false;
569 }
570
571 unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const { return 128; }
572
573 bool isLegalToVectorizeLoad(LoadInst *LI) const { return true; }
574
575 bool isLegalToVectorizeStore(StoreInst *SI) const { return true; }
576
577 bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
578 unsigned Alignment,
579 unsigned AddrSpace) const {
580 return true;
581 }
582
583 bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
584 unsigned Alignment,
585 unsigned AddrSpace) const {
586 return true;
587 }
588
589 unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
590 unsigned ChainSizeInBytes,
591 VectorType *VecTy) const {
592 return VF;
593 }
594
595 unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
596 unsigned ChainSizeInBytes,
597 VectorType *VecTy) const {
598 return VF;
599 }
600
601 bool useReductionIntrinsic(unsigned Opcode, Type *Ty,
602 TTI::ReductionFlags Flags) const {
603 return false;
604 }
605
606 bool shouldExpandReduction(const IntrinsicInst *II) const {
607 return true;
608 }
609
610 unsigned getGISelRematGlobalCost() const {
611 return 1;
612 }
613
614protected:
615 // Obtain the minimum required size to hold the value (without the sign)
616 // In case of a vector it returns the min required size for one element.
617 unsigned minRequiredElementSize(const Value* Val, bool &isSigned) {
618 if (isa<ConstantDataVector>(Val) || isa<ConstantVector>(Val)) {
619 const auto* VectorValue = cast<Constant>(Val);
620
621 // In case of a vector need to pick the max between the min
622 // required size for each element
623 auto *VT = cast<VectorType>(Val->getType());
624
625 // Assume unsigned elements
626 isSigned = false;
627
628 // The max required size is the total vector width divided by num
629 // of elements in the vector
630 unsigned MaxRequiredSize = VT->getBitWidth() / VT->getNumElements();
631
632 unsigned MinRequiredSize = 0;
633 for(unsigned i = 0, e = VT->getNumElements(); i < e; ++i) {
634 if (auto* IntElement =
635 dyn_cast<ConstantInt>(VectorValue->getAggregateElement(i))) {
636 bool signedElement = IntElement->getValue().isNegative();
637 // Get the element min required size.
638 unsigned ElementMinRequiredSize =
639 IntElement->getValue().getMinSignedBits() - 1;
640 // In case one element is signed then all the vector is signed.
641 isSigned |= signedElement;
642 // Save the max required bit size between all the elements.
643 MinRequiredSize = std::max(MinRequiredSize, ElementMinRequiredSize);
644 }
645 else {
646 // not an int constant element
647 return MaxRequiredSize;
648 }
649 }
650 return MinRequiredSize;
651 }
652
653 if (const auto* CI = dyn_cast<ConstantInt>(Val)) {
654 isSigned = CI->getValue().isNegative();
655 return CI->getValue().getMinSignedBits() - 1;
656 }
657
658 if (const auto* Cast = dyn_cast<SExtInst>(Val)) {
659 isSigned = true;
660 return Cast->getSrcTy()->getScalarSizeInBits() - 1;
661 }
662
663 if (const auto* Cast = dyn_cast<ZExtInst>(Val)) {
664 isSigned = false;
665 return Cast->getSrcTy()->getScalarSizeInBits();
666 }
667
668 isSigned = false;
669 return Val->getType()->getScalarSizeInBits();
670 }
671
672 bool isStridedAccess(const SCEV *Ptr) {
673 return Ptr && isa<SCEVAddRecExpr>(Ptr);
674 }
675
676 const SCEVConstant *getConstantStrideStep(ScalarEvolution *SE,
677 const SCEV *Ptr) {
678 if (!isStridedAccess(Ptr))
679 return nullptr;
680 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ptr);
681 return dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(*SE));
682 }
683
684 bool isConstantStridedAccessLessThan(ScalarEvolution *SE, const SCEV *Ptr,
685 int64_t MergeDistance) {
686 const SCEVConstant *Step = getConstantStrideStep(SE, Ptr);
687 if (!Step)
688 return false;
689 APInt StrideVal = Step->getAPInt();
690 if (StrideVal.getBitWidth() > 64)
691 return false;
692 // FIXME: Need to take absolute value for negative stride case.
693 return StrideVal.getSExtValue() < MergeDistance;
694 }
695};
696
697/// CRTP base class for use as a mix-in that aids implementing
698/// a TargetTransformInfo-compatible class.
699template <typename T>
700class TargetTransformInfoImplCRTPBase : public TargetTransformInfoImplBase {
701private:
702 typedef TargetTransformInfoImplBase BaseT;
703
704protected:
705 explicit TargetTransformInfoImplCRTPBase(const DataLayout &DL) : BaseT(DL) {}
706
707public:
708 using BaseT::getCallCost;
709
710 unsigned getCallCost(const Function *F, int NumArgs, const User *U) {
711 assert(F && "A concrete function must be provided to this routine.")((F && "A concrete function must be provided to this routine."
) ? static_cast<void> (0) : __assert_fail ("F && \"A concrete function must be provided to this routine.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h"
, 711, __PRETTY_FUNCTION__))
;
712
713 if (NumArgs < 0)
714 // Set the argument number to the number of explicit arguments in the
715 // function.
716 NumArgs = F->arg_size();
717
718 if (Intrinsic::ID IID = F->getIntrinsicID()) {
719 FunctionType *FTy = F->getFunctionType();
720 SmallVector<Type *, 8> ParamTys(FTy->param_begin(), FTy->param_end());
721 return static_cast<T *>(this)
722 ->getIntrinsicCost(IID, FTy->getReturnType(), ParamTys, U);
723 }
724
725 if (!static_cast<T *>(this)->isLoweredToCall(F))
726 return TTI::TCC_Basic; // Give a basic cost if it will be lowered
727 // directly.
728
729 return static_cast<T *>(this)->getCallCost(F->getFunctionType(), NumArgs, U);
730 }
731
732 unsigned getCallCost(const Function *F, ArrayRef<const Value *> Arguments,
733 const User *U) {
734 // Simply delegate to generic handling of the call.
735 // FIXME: We should use instsimplify or something else to catch calls which
736 // will constant fold with these arguments.
737 return static_cast<T *>(this)->getCallCost(F, Arguments.size(), U);
738 }
739
740 using BaseT::getGEPCost;
741
742 int getGEPCost(Type *PointeeType, const Value *Ptr,
743 ArrayRef<const Value *> Operands) {
744 assert(PointeeType && Ptr && "can't get GEPCost of nullptr")((PointeeType && Ptr && "can't get GEPCost of nullptr"
) ? static_cast<void> (0) : __assert_fail ("PointeeType && Ptr && \"can't get GEPCost of nullptr\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h"
, 744, __PRETTY_FUNCTION__))
;
745 // TODO: will remove this when pointers have an opaque type.
746 assert(Ptr->getType()->getScalarType()->getPointerElementType() ==((Ptr->getType()->getScalarType()->getPointerElementType
() == PointeeType && "explicit pointee type doesn't match operand's pointee type"
) ? static_cast<void> (0) : __assert_fail ("Ptr->getType()->getScalarType()->getPointerElementType() == PointeeType && \"explicit pointee type doesn't match operand's pointee type\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h"
, 748, __PRETTY_FUNCTION__))
747 PointeeType &&((Ptr->getType()->getScalarType()->getPointerElementType
() == PointeeType && "explicit pointee type doesn't match operand's pointee type"
) ? static_cast<void> (0) : __assert_fail ("Ptr->getType()->getScalarType()->getPointerElementType() == PointeeType && \"explicit pointee type doesn't match operand's pointee type\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h"
, 748, __PRETTY_FUNCTION__))
748 "explicit pointee type doesn't match operand's pointee type")((Ptr->getType()->getScalarType()->getPointerElementType
() == PointeeType && "explicit pointee type doesn't match operand's pointee type"
) ? static_cast<void> (0) : __assert_fail ("Ptr->getType()->getScalarType()->getPointerElementType() == PointeeType && \"explicit pointee type doesn't match operand's pointee type\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h"
, 748, __PRETTY_FUNCTION__))
;
749 auto *BaseGV = dyn_cast<GlobalValue>(Ptr->stripPointerCasts());
750 bool HasBaseReg = (BaseGV == nullptr);
751
752 auto PtrSizeBits = DL.getPointerTypeSizeInBits(Ptr->getType());
753 APInt BaseOffset(PtrSizeBits, 0);
754 int64_t Scale = 0;
755
756 auto GTI = gep_type_begin(PointeeType, Operands);
757 Type *TargetType = nullptr;
758
759 // Handle the case where the GEP instruction has a single operand,
760 // the basis, therefore TargetType is a nullptr.
761 if (Operands.empty())
762 return !BaseGV ? TTI::TCC_Free : TTI::TCC_Basic;
763
764 for (auto I = Operands.begin(); I != Operands.end(); ++I, ++GTI) {
765 TargetType = GTI.getIndexedType();
766 // We assume that the cost of Scalar GEP with constant index and the
767 // cost of Vector GEP with splat constant index are the same.
768 const ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I);
769 if (!ConstIdx)
770 if (auto Splat = getSplatValue(*I))
771 ConstIdx = dyn_cast<ConstantInt>(Splat);
772 if (StructType *STy = GTI.getStructTypeOrNull()) {
773 // For structures the index is always splat or scalar constant
774 assert(ConstIdx && "Unexpected GEP index")((ConstIdx && "Unexpected GEP index") ? static_cast<
void> (0) : __assert_fail ("ConstIdx && \"Unexpected GEP index\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h"
, 774, __PRETTY_FUNCTION__))
;
775 uint64_t Field = ConstIdx->getZExtValue();
776 BaseOffset += DL.getStructLayout(STy)->getElementOffset(Field);
777 } else {
778 int64_t ElementSize = DL.getTypeAllocSize(GTI.getIndexedType());
779 if (ConstIdx) {
780 BaseOffset +=
781 ConstIdx->getValue().sextOrTrunc(PtrSizeBits) * ElementSize;
782 } else {
783 // Needs scale register.
784 if (Scale != 0)
785 // No addressing mode takes two scale registers.
786 return TTI::TCC_Basic;
787 Scale = ElementSize;
788 }
789 }
790 }
791
792 if (static_cast<T *>(this)->isLegalAddressingMode(
793 TargetType, const_cast<GlobalValue *>(BaseGV),
794 BaseOffset.sextOrTrunc(64).getSExtValue(), HasBaseReg, Scale,
795 Ptr->getType()->getPointerAddressSpace()))
796 return TTI::TCC_Free;
797 return TTI::TCC_Basic;
798 }
799
800 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
801 ArrayRef<Type *> ParamTys, const User *U) {
802 switch (IID) {
803 default:
804 // Intrinsics rarely (if ever) have normal argument setup constraints.
805 // Model them as having a basic instruction cost.
806 return TTI::TCC_Basic;
807
808 // TODO: other libc intrinsics.
809 case Intrinsic::memcpy:
810 return static_cast<T *>(this)->getMemcpyCost(dyn_cast<Instruction>(U));
811
812 case Intrinsic::annotation:
813 case Intrinsic::assume:
814 case Intrinsic::sideeffect:
815 case Intrinsic::dbg_declare:
816 case Intrinsic::dbg_value:
817 case Intrinsic::dbg_label:
818 case Intrinsic::invariant_start:
819 case Intrinsic::invariant_end:
820 case Intrinsic::launder_invariant_group:
821 case Intrinsic::strip_invariant_group:
822 case Intrinsic::is_constant:
823 case Intrinsic::lifetime_start:
824 case Intrinsic::lifetime_end:
825 case Intrinsic::objectsize:
826 case Intrinsic::ptr_annotation:
827 case Intrinsic::var_annotation:
828 case Intrinsic::experimental_gc_result:
829 case Intrinsic::experimental_gc_relocate:
830 case Intrinsic::coro_alloc:
831 case Intrinsic::coro_begin:
832 case Intrinsic::coro_free:
833 case Intrinsic::coro_end:
834 case Intrinsic::coro_frame:
835 case Intrinsic::coro_size:
836 case Intrinsic::coro_suspend:
837 case Intrinsic::coro_param:
838 case Intrinsic::coro_subfn_addr:
839 // These intrinsics don't actually represent code after lowering.
840 return TTI::TCC_Free;
841 }
842 }
843
844 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
845 ArrayRef<const Value *> Arguments, const User *U) {
846 // Delegate to the generic intrinsic handling code. This mostly provides an
847 // opportunity for targets to (for example) special case the cost of
848 // certain intrinsics based on constants used as arguments.
849 SmallVector<Type *, 8> ParamTys;
850 ParamTys.reserve(Arguments.size());
851 for (unsigned Idx = 0, Size = Arguments.size(); Idx != Size; ++Idx)
852 ParamTys.push_back(Arguments[Idx]->getType());
853 return static_cast<T *>(this)->getIntrinsicCost(IID, RetTy, ParamTys, U);
854 }
855
856 unsigned getUserCost(const User *U, ArrayRef<const Value *> Operands) {
857 if (isa<PHINode>(U))
4
Assuming 'U' is not a 'PHINode'
5
Taking false branch
858 return TTI::TCC_Free; // Model all PHI nodes as free.
859
860 if (isa<ExtractValueInst>(U))
6
Assuming 'U' is not a 'ExtractValueInst'
7
Taking false branch
861 return TTI::TCC_Free; // Model all ExtractValue nodes as free.
862
863 // Static alloca doesn't generate target instructions.
864 if (auto *A
8.1
'A' is null
8.1
'A' is null
8.1
'A' is null
8.1
'A' is null
8.1
'A' is null
8.1
'A' is null
8.1
'A' is null
= dyn_cast<AllocaInst>(U))
8
Assuming 'U' is not a 'AllocaInst'
9
Taking false branch
865 if (A->isStaticAlloca())
866 return TTI::TCC_Free;
867
868 if (const GEPOperator *GEP
10.1
'GEP' is null
10.1
'GEP' is null
10.1
'GEP' is null
10.1
'GEP' is null
10.1
'GEP' is null
10.1
'GEP' is null
10.1
'GEP' is null
= dyn_cast<GEPOperator>(U)) {
10
Assuming 'U' is not a 'GEPOperator'
11
Taking false branch
869 return static_cast<T *>(this)->getGEPCost(GEP->getSourceElementType(),
870 GEP->getPointerOperand(),
871 Operands.drop_front());
872 }
873
874 if (auto CS = ImmutableCallSite(U)) {
12
Calling 'CallSiteBase::operator bool'
26
Returning from 'CallSiteBase::operator bool'
27
Taking false branch
875 const Function *F = CS.getCalledFunction();
876 if (!F) {
877 // Just use the called value type.
878 Type *FTy = CS.getCalledValue()->getType()->getPointerElementType();
879 return static_cast<T *>(this)
880 ->getCallCost(cast<FunctionType>(FTy), CS.arg_size(), U);
881 }
882
883 SmallVector<const Value *, 8> Arguments(CS.arg_begin(), CS.arg_end());
884 return static_cast<T *>(this)->getCallCost(F, Arguments, U);
885 }
886
887 if (isa<SExtInst>(U) || isa<ZExtInst>(U) || isa<FPExtInst>(U))
28
Assuming 'U' is not a 'SExtInst'
29
Assuming 'U' is not a 'ZExtInst'
30
Assuming 'U' is not a 'FPExtInst'
31
Taking false branch
888 // The old behaviour of generally treating extensions of icmp to be free
889 // has been removed. A target that needs it should override getUserCost().
890 return static_cast<T *>(this)->getExtCost(cast<Instruction>(U),
891 Operands.back());
892
893 return static_cast<T *>(this)->getOperationCost(
40
Calling 'BasicTTIImplBase::getOperationCost'
894 Operator::getOpcode(U), U->getType(),
32
Calling 'Operator::getOpcode'
36
Returning from 'Operator::getOpcode'
895 U->getNumOperands() == 1 ? U->getOperand(0)->getType() : nullptr);
37
Assuming the condition is false
38
'?' condition is false
39
Passing null pointer value via 3rd parameter 'OpTy'
896 }
897
898 int getInstructionLatency(const Instruction *I) {
899 SmallVector<const Value *, 4> Operands(I->value_op_begin(),
900 I->value_op_end());
901 if (getUserCost(I, Operands) == TTI::TCC_Free)
902 return 0;
903
904 if (isa<LoadInst>(I))
905 return 4;
906
907 Type *DstTy = I->getType();
908
909 // Usually an intrinsic is a simple instruction.
910 // A real function call is much slower.
911 if (auto *CI = dyn_cast<CallInst>(I)) {
912 const Function *F = CI->getCalledFunction();
913 if (!F || static_cast<T *>(this)->isLoweredToCall(F))
914 return 40;
915 // Some intrinsics return a value and a flag, we use the value type
916 // to decide its latency.
917 if (StructType* StructTy = dyn_cast<StructType>(DstTy))
918 DstTy = StructTy->getElementType(0);
919 // Fall through to simple instructions.
920 }
921
922 if (VectorType *VectorTy = dyn_cast<VectorType>(DstTy))
923 DstTy = VectorTy->getElementType();
924 if (DstTy->isFloatingPointTy())
925 return 3;
926
927 return 1;
928 }
929};
930}
931
932#endif

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h

1//===- CallSite.h - Abstract Call & Invoke instrs ---------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the CallSite class, which is a handy wrapper for code that
10// wants to treat Call, Invoke and CallBr instructions in a generic way. When
11// in non-mutation context (e.g. an analysis) ImmutableCallSite should be used.
12// Finally, when some degree of customization is necessary between these two
13// extremes, CallSiteBase<> can be supplied with fine-tuned parameters.
14//
15// NOTE: These classes are supposed to have "value semantics". So they should be
16// passed by value, not by reference; they should not be "new"ed or "delete"d.
17// They are efficiently copyable, assignable and constructable, with cost
18// equivalent to copying a pointer (notice that they have only a single data
19// member). The internal representation carries a flag which indicates which of
20// the three variants is enclosed. This allows for cheaper checks when various
21// accessors of CallSite are employed.
22//
23//===----------------------------------------------------------------------===//
24
25#ifndef LLVM_IR_CALLSITE_H
26#define LLVM_IR_CALLSITE_H
27
28#include "llvm/ADT/Optional.h"
29#include "llvm/ADT/PointerIntPair.h"
30#include "llvm/ADT/iterator_range.h"
31#include "llvm/IR/Attributes.h"
32#include "llvm/IR/CallingConv.h"
33#include "llvm/IR/Function.h"
34#include "llvm/IR/InstrTypes.h"
35#include "llvm/IR/Instruction.h"
36#include "llvm/IR/Instructions.h"
37#include "llvm/IR/Use.h"
38#include "llvm/IR/User.h"
39#include "llvm/IR/Value.h"
40#include "llvm/Support/Casting.h"
41#include <cassert>
42#include <cstdint>
43#include <iterator>
44
45namespace llvm {
46
47namespace Intrinsic {
48enum ID : unsigned;
49}
50
51template <typename FunTy = const Function, typename BBTy = const BasicBlock,
52 typename ValTy = const Value, typename UserTy = const User,
53 typename UseTy = const Use, typename InstrTy = const Instruction,
54 typename CallTy = const CallInst,
55 typename InvokeTy = const InvokeInst,
56 typename CallBrTy = const CallBrInst,
57 typename IterTy = User::const_op_iterator>
58class CallSiteBase {
59protected:
60 PointerIntPair<InstrTy *, 2, int> I;
61
62 CallSiteBase() = default;
63 CallSiteBase(CallTy *CI) : I(CI, 1) { assert(CI)((CI) ? static_cast<void> (0) : __assert_fail ("CI", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h"
, 63, __PRETTY_FUNCTION__))
; }
64 CallSiteBase(InvokeTy *II) : I(II, 0) { assert(II)((II) ? static_cast<void> (0) : __assert_fail ("II", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h"
, 64, __PRETTY_FUNCTION__))
; }
65 CallSiteBase(CallBrTy *CBI) : I(CBI, 2) { assert(CBI)((CBI) ? static_cast<void> (0) : __assert_fail ("CBI", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h"
, 65, __PRETTY_FUNCTION__))
; }
66 explicit CallSiteBase(ValTy *II) { *this = get(II); }
67
68private:
69 /// This static method is like a constructor. It will create an appropriate
70 /// call site for a Call, Invoke or CallBr instruction, but it can also create
71 /// a null initialized CallSiteBase object for something which is NOT a call
72 /// site.
73 static CallSiteBase get(ValTy *V) {
74 if (InstrTy *II = dyn_cast<InstrTy>(V)) {
75 if (II->getOpcode() == Instruction::Call)
76 return CallSiteBase(static_cast<CallTy*>(II));
77 if (II->getOpcode() == Instruction::Invoke)
78 return CallSiteBase(static_cast<InvokeTy*>(II));
79 if (II->getOpcode() == Instruction::CallBr)
80 return CallSiteBase(static_cast<CallBrTy *>(II));
81 }
82 return CallSiteBase();
83 }
84
85public:
86 /// Return true if a CallInst is enclosed.
87 bool isCall() const { return I.getInt() == 1; }
88
89 /// Return true if a InvokeInst is enclosed. !I.getInt() may also signify a
90 /// NULL instruction pointer, so check that.
91 bool isInvoke() const { return getInstruction() && I.getInt() == 0; }
92
93 /// Return true if a CallBrInst is enclosed.
94 bool isCallBr() const { return I.getInt() == 2; }
95
96 InstrTy *getInstruction() const { return I.getPointer(); }
97 InstrTy *operator->() const { return I.getPointer(); }
98 explicit operator bool() const { return I.getPointer(); }
13
Calling 'PointerIntPair::getPointer'
24
Returning from 'PointerIntPair::getPointer'
25
Returning zero, which participates in a condition later
99
100 /// Get the basic block containing the call site.
101 BBTy* getParent() const { return getInstruction()->getParent(); }
102
103 /// Return the pointer to function that is being called.
104 ValTy *getCalledValue() const {
105 assert(getInstruction() && "Not a call, invoke or callbr instruction!")((getInstruction() && "Not a call, invoke or callbr instruction!"
) ? static_cast<void> (0) : __assert_fail ("getInstruction() && \"Not a call, invoke or callbr instruction!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h"
, 105, __PRETTY_FUNCTION__))
;
106 return *getCallee();
107 }
108
109 /// Return the function being called if this is a direct call, otherwise
110 /// return null (if it's an indirect call).
111 FunTy *getCalledFunction() const {
112 return dyn_cast<FunTy>(getCalledValue());
113 }
114
115 /// Return true if the callsite is an indirect call.
116 bool isIndirectCall() const {
117 const Value *V = getCalledValue();
118 if (!V)
119 return false;
120 if (isa<FunTy>(V) || isa<Constant>(V))
121 return false;
122 if (const CallBase *CB = dyn_cast<CallBase>(getInstruction()))
123 if (CB->isInlineAsm())
124 return false;
125 return true;
126 }
127
128 /// Set the callee to the specified value. Unlike the function of the same
129 /// name on CallBase, does not modify the type!
130 void setCalledFunction(Value *V) {
131 assert(getInstruction() && "Not a call, callbr, or invoke instruction!")((getInstruction() && "Not a call, callbr, or invoke instruction!"
) ? static_cast<void> (0) : __assert_fail ("getInstruction() && \"Not a call, callbr, or invoke instruction!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h"
, 131, __PRETTY_FUNCTION__))
;
132 assert(cast<PointerType>(V->getType())->getElementType() ==((cast<PointerType>(V->getType())->getElementType
() == cast<CallBase>(getInstruction())->getFunctionType
() && "New callee type does not match FunctionType on call"
) ? static_cast<void> (0) : __assert_fail ("cast<PointerType>(V->getType())->getElementType() == cast<CallBase>(getInstruction())->getFunctionType() && \"New callee type does not match FunctionType on call\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h"
, 134, __PRETTY_FUNCTION__))
133 cast<CallBase>(getInstruction())->getFunctionType() &&((cast<PointerType>(V->getType())->getElementType
() == cast<CallBase>(getInstruction())->getFunctionType
() && "New callee type does not match FunctionType on call"
) ? static_cast<void> (0) : __assert_fail ("cast<PointerType>(V->getType())->getElementType() == cast<CallBase>(getInstruction())->getFunctionType() && \"New callee type does not match FunctionType on call\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h"
, 134, __PRETTY_FUNCTION__))
134 "New callee type does not match FunctionType on call")((cast<PointerType>(V->getType())->getElementType
() == cast<CallBase>(getInstruction())->getFunctionType
() && "New callee type does not match FunctionType on call"
) ? static_cast<void> (0) : __assert_fail ("cast<PointerType>(V->getType())->getElementType() == cast<CallBase>(getInstruction())->getFunctionType() && \"New callee type does not match FunctionType on call\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h"
, 134, __PRETTY_FUNCTION__))
;
135 *getCallee() = V;
136 }
137
138 /// Return the intrinsic ID of the intrinsic called by this CallSite,
139 /// or Intrinsic::not_intrinsic if the called function is not an
140 /// intrinsic, or if this CallSite is an indirect call.
141 Intrinsic::ID getIntrinsicID() const {
142 if (auto *F = getCalledFunction())
143 return F->getIntrinsicID();
144 // Don't use Intrinsic::not_intrinsic, as it will require pulling
145 // Intrinsics.h into every header that uses CallSite.
146 return static_cast<Intrinsic::ID>(0);
147 }
148
149 /// Determine whether the passed iterator points to the callee operand's Use.
150 bool isCallee(Value::const_user_iterator UI) const {
151 return isCallee(&UI.getUse());
152 }
153
154 /// Determine whether this Use is the callee operand's Use.
155 bool isCallee(const Use *U) const { return getCallee() == U; }
156
157 /// Determine whether the passed iterator points to an argument operand.
158 bool isArgOperand(Value::const_user_iterator UI) const {
159 return isArgOperand(&UI.getUse());
160 }
161
162 /// Determine whether the passed use points to an argument operand.
163 bool isArgOperand(const Use *U) const {
164 assert(getInstruction() == U->getUser())((getInstruction() == U->getUser()) ? static_cast<void>
(0) : __assert_fail ("getInstruction() == U->getUser()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h"
, 164, __PRETTY_FUNCTION__))
;
165 return arg_begin() <= U && U < arg_end();
166 }
167
168 /// Determine whether the passed iterator points to a bundle operand.
169 bool isBundleOperand(Value::const_user_iterator UI) const {
170 return isBundleOperand(&UI.getUse());
171 }
172
173 /// Determine whether the passed use points to a bundle operand.
174 bool isBundleOperand(const Use *U) const {
175 assert(getInstruction() == U->getUser())((getInstruction() == U->getUser()) ? static_cast<void>
(0) : __assert_fail ("getInstruction() == U->getUser()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h"
, 175, __PRETTY_FUNCTION__))
;
176 if (!hasOperandBundles())
177 return false;
178 unsigned OperandNo = U - (*this)->op_begin();
179 return getBundleOperandsStartIndex() <= OperandNo &&
180 OperandNo < getBundleOperandsEndIndex();
181 }
182
183 /// Determine whether the passed iterator points to a data operand.
184 bool isDataOperand(Value::const_user_iterator UI) const {
185 return isDataOperand(&UI.getUse());
186 }
187
188 /// Determine whether the passed use points to a data operand.
189 bool isDataOperand(const Use *U) const {
190 return data_operands_begin() <= U && U < data_operands_end();
191 }
192
193 ValTy *getArgument(unsigned ArgNo) const {
194 assert(arg_begin() + ArgNo < arg_end() && "Argument # out of range!")((arg_begin() + ArgNo < arg_end() && "Argument # out of range!"
) ? static_cast<void> (0) : __assert_fail ("arg_begin() + ArgNo < arg_end() && \"Argument # out of range!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h"
, 194, __PRETTY_FUNCTION__))
;
195 return *(arg_begin() + ArgNo);
196 }
197
198 void setArgument(unsigned ArgNo, Value* newVal) {
199 assert(getInstruction() && "Not a call, invoke or callbr instruction!")((getInstruction() && "Not a call, invoke or callbr instruction!"
) ? static_cast<void> (0) : __assert_fail ("getInstruction() && \"Not a call, invoke or callbr instruction!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h"
, 199, __PRETTY_FUNCTION__))
;
200 assert(arg_begin() + ArgNo < arg_end() && "Argument # out of range!")((arg_begin() + ArgNo < arg_end() && "Argument # out of range!"
) ? static_cast<void> (0) : __assert_fail ("arg_begin() + ArgNo < arg_end() && \"Argument # out of range!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h"
, 200, __PRETTY_FUNCTION__))
;
201 getInstruction()->setOperand(ArgNo, newVal);
202 }
203
204 /// Given a value use iterator, returns the argument that corresponds to it.
205 /// Iterator must actually correspond to an argument.
206 unsigned getArgumentNo(Value::const_user_iterator I) const {
207 return getArgumentNo(&I.getUse());
208 }
209
210 /// Given a use for an argument, get the argument number that corresponds to
211 /// it.
212 unsigned getArgumentNo(const Use *U) const {
213 assert(getInstruction() && "Not a call, invoke or callbr instruction!")((getInstruction() && "Not a call, invoke or callbr instruction!"
) ? static_cast<void> (0) : __assert_fail ("getInstruction() && \"Not a call, invoke or callbr instruction!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h"
, 213, __PRETTY_FUNCTION__))
;
214 assert(isArgOperand(U) && "Argument # out of range!")((isArgOperand(U) && "Argument # out of range!") ? static_cast
<void> (0) : __assert_fail ("isArgOperand(U) && \"Argument # out of range!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h"
, 214, __PRETTY_FUNCTION__))
;
215 return U - arg_begin();
216 }
217
218 /// The type of iterator to use when looping over actual arguments at this
219 /// call site.
220 using arg_iterator = IterTy;
221
222 iterator_range<IterTy> args() const {
223 return make_range(arg_begin(), arg_end());
224 }
225 bool arg_empty() const { return arg_end() == arg_begin(); }
226 unsigned arg_size() const { return unsigned(arg_end() - arg_begin()); }
227
228 /// Given a value use iterator, return the data operand corresponding to it.
229 /// Iterator must actually correspond to a data operand.
230 unsigned getDataOperandNo(Value::const_user_iterator UI) const {
231 return getDataOperandNo(&UI.getUse());
232 }
233
234 /// Given a use for a data operand, get the data operand number that
235 /// corresponds to it.
236 unsigned getDataOperandNo(const Use *U) const {
237 assert(getInstruction() && "Not a call, invoke or callbr instruction!")((getInstruction() && "Not a call, invoke or callbr instruction!"
) ? static_cast<void> (0) : __assert_fail ("getInstruction() && \"Not a call, invoke or callbr instruction!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h"
, 237, __PRETTY_FUNCTION__))
;
238 assert(isDataOperand(U) && "Data operand # out of range!")((isDataOperand(U) && "Data operand # out of range!")
? static_cast<void> (0) : __assert_fail ("isDataOperand(U) && \"Data operand # out of range!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h"
, 238, __PRETTY_FUNCTION__))
;
239 return U - data_operands_begin();
240 }
241
242 /// Type of iterator to use when looping over data operands at this call site
243 /// (see below).
244 using data_operand_iterator = IterTy;
245
246 /// data_operands_begin/data_operands_end - Return iterators iterating over
247 /// the call / invoke / callbr argument list and bundle operands. For invokes,
248 /// this is the set of instruction operands except the invoke target and the
249 /// two successor blocks; for calls this is the set of instruction operands
250 /// except the call target; for callbrs the number of labels to skip must be
251 /// determined first.
252
253 IterTy data_operands_begin() const {
254 assert(getInstruction() && "Not a call or invoke instruction!")((getInstruction() && "Not a call or invoke instruction!"
) ? static_cast<void> (0) : __assert_fail ("getInstruction() && \"Not a call or invoke instruction!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h"
, 254, __PRETTY_FUNCTION__))
;
255 return cast<CallBase>(getInstruction())->data_operands_begin();
256 }
257 IterTy data_operands_end() const {
258 assert(getInstruction() && "Not a call or invoke instruction!")((getInstruction() && "Not a call or invoke instruction!"
) ? static_cast<void> (0) : __assert_fail ("getInstruction() && \"Not a call or invoke instruction!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h"
, 258, __PRETTY_FUNCTION__))
;
259 return cast<CallBase>(getInstruction())->data_operands_end();
260 }
261 iterator_range<IterTy> data_ops() const {
262 return make_range(data_operands_begin(), data_operands_end());
263 }
264 bool data_operands_empty() const {
265 return data_operands_end() == data_operands_begin();
266 }
267 unsigned data_operands_size() const {
268 return std::distance(data_operands_begin(), data_operands_end());
269 }
270
271 /// Return the type of the instruction that generated this call site.
272 Type *getType() const { return (*this)->getType(); }
273
274 /// Return the caller function for this call site.
275 FunTy *getCaller() const { return (*this)->getParent()->getParent(); }
276
277 /// Tests if this call site must be tail call optimized. Only a CallInst can
278 /// be tail call optimized.
279 bool isMustTailCall() const {
280 return isCall() && cast<CallInst>(getInstruction())->isMustTailCall();
281 }
282
283 /// Tests if this call site is marked as a tail call.
284 bool isTailCall() const {
285 return isCall() && cast<CallInst>(getInstruction())->isTailCall();
286 }
287
288#define CALLSITE_DELEGATE_GETTER(METHOD) \
289 InstrTy *II = getInstruction(); \
290 return isCall() ? cast<CallInst>(II)->METHOD \
291 : isCallBr() ? cast<CallBrInst>(II)->METHOD \
292 : cast<InvokeInst>(II)->METHOD
293
294#define CALLSITE_DELEGATE_SETTER(METHOD) \
295 InstrTy *II = getInstruction(); \
296 if (isCall()) \
297 cast<CallInst>(II)->METHOD; \
298 else if (isCallBr()) \
299 cast<CallBrInst>(II)->METHOD; \
300 else \
301 cast<InvokeInst>(II)->METHOD
302
303 unsigned getNumArgOperands() const {
304 CALLSITE_DELEGATE_GETTER(getNumArgOperands());
305 }
306
307 ValTy *getArgOperand(unsigned i) const {
308 CALLSITE_DELEGATE_GETTER(getArgOperand(i));
309 }
310
311 ValTy *getReturnedArgOperand() const {
312 CALLSITE_DELEGATE_GETTER(getReturnedArgOperand());
313 }
314
315 bool isInlineAsm() const {
316 return cast<CallBase>(getInstruction())->isInlineAsm();
317 }
318
319 /// Get the calling convention of the call.
320 CallingConv::ID getCallingConv() const {
321 CALLSITE_DELEGATE_GETTER(getCallingConv());
322 }
323 /// Set the calling convention of the call.
324 void setCallingConv(CallingConv::ID CC) {
325 CALLSITE_DELEGATE_SETTER(setCallingConv(CC));
326 }
327
328 FunctionType *getFunctionType() const {
329 CALLSITE_DELEGATE_GETTER(getFunctionType());
330 }
331
332 void mutateFunctionType(FunctionType *Ty) const {
333 CALLSITE_DELEGATE_SETTER(mutateFunctionType(Ty));
334 }
335
336 /// Get the parameter attributes of the call.
337 AttributeList getAttributes() const {
338 CALLSITE_DELEGATE_GETTER(getAttributes());
339 }
340 /// Set the parameter attributes of the call.
341 void setAttributes(AttributeList PAL) {
342 CALLSITE_DELEGATE_SETTER(setAttributes(PAL));
343 }
344
345 void addAttribute(unsigned i, Attribute::AttrKind Kind) {
346 CALLSITE_DELEGATE_SETTER(addAttribute(i, Kind));
347 }
348
349 void addAttribute(unsigned i, Attribute Attr) {
350 CALLSITE_DELEGATE_SETTER(addAttribute(i, Attr));
351 }
352
353 void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
354 CALLSITE_DELEGATE_SETTER(addParamAttr(ArgNo, Kind));
355 }
356
357 void removeAttribute(unsigned i, Attribute::AttrKind Kind) {
358 CALLSITE_DELEGATE_SETTER(removeAttribute(i, Kind));
359 }
360
361 void removeAttribute(unsigned i, StringRef Kind) {
362 CALLSITE_DELEGATE_SETTER(removeAttribute(i, Kind));
363 }
364
365 void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
366 CALLSITE_DELEGATE_SETTER(removeParamAttr(ArgNo, Kind));
367 }
368
369 /// Return true if this function has the given attribute.
370 bool hasFnAttr(Attribute::AttrKind Kind) const {
371 CALLSITE_DELEGATE_GETTER(hasFnAttr(Kind));
372 }
373
374 /// Return true if this function has the given attribute.
375 bool hasFnAttr(StringRef Kind) const {
376 CALLSITE_DELEGATE_GETTER(hasFnAttr(Kind));
377 }
378
379 /// Return true if this return value has the given attribute.
380 bool hasRetAttr(Attribute::AttrKind Kind) const {
381 CALLSITE_DELEGATE_GETTER(hasRetAttr(Kind));
382 }
383
384 /// Return true if the call or the callee has the given attribute.
385 bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
386 CALLSITE_DELEGATE_GETTER(paramHasAttr(ArgNo, Kind));
387 }
388
389 Attribute getAttribute(unsigned i, Attribute::AttrKind Kind) const {
390 CALLSITE_DELEGATE_GETTER(getAttribute(i, Kind));
391 }
392
393 Attribute getAttribute(unsigned i, StringRef Kind) const {
394 CALLSITE_DELEGATE_GETTER(getAttribute(i, Kind));
395 }
396
397 /// Return true if the data operand at index \p i directly or indirectly has
398 /// the attribute \p A.
399 ///
400 /// Normal call, invoke or callbr arguments have per operand attributes, as
401 /// specified in the attribute set attached to this instruction, while operand
402 /// bundle operands may have some attributes implied by the type of its
403 /// containing operand bundle.
404 bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind Kind) const {
405 CALLSITE_DELEGATE_GETTER(dataOperandHasImpliedAttr(i, Kind));
406 }
407
408 /// Extract the alignment of the return value.
409 unsigned getRetAlignment() const {
410 CALLSITE_DELEGATE_GETTER(getRetAlignment());
411 }
412
413 /// Extract the alignment for a call or parameter (0=unknown).
414 unsigned getParamAlignment(unsigned ArgNo) const {
415 CALLSITE_DELEGATE_GETTER(getParamAlignment(ArgNo));
416 }
417
418 /// Extract the byval type for a call or parameter (nullptr=unknown).
419 Type *getParamByValType(unsigned ArgNo) const {
420 CALLSITE_DELEGATE_GETTER(getParamByValType(ArgNo));
421 }
422
423 /// Extract the number of dereferenceable bytes for a call or parameter
424 /// (0=unknown).
425 uint64_t getDereferenceableBytes(unsigned i) const {
426 CALLSITE_DELEGATE_GETTER(getDereferenceableBytes(i));
427 }
428
429 /// Extract the number of dereferenceable_or_null bytes for a call or
430 /// parameter (0=unknown).
431 uint64_t getDereferenceableOrNullBytes(unsigned i) const {
432 CALLSITE_DELEGATE_GETTER(getDereferenceableOrNullBytes(i));
433 }
434
435 /// Determine if the return value is marked with NoAlias attribute.
436 bool returnDoesNotAlias() const {
437 CALLSITE_DELEGATE_GETTER(returnDoesNotAlias());
438 }
439
440 /// Return true if the call should not be treated as a call to a builtin.
441 bool isNoBuiltin() const {
442 CALLSITE_DELEGATE_GETTER(isNoBuiltin());
443 }
444
445 /// Return true if the call requires strict floating point semantics.
446 bool isStrictFP() const {
447 CALLSITE_DELEGATE_GETTER(isStrictFP());
448 }
449
450 /// Return true if the call should not be inlined.
451 bool isNoInline() const {
452 CALLSITE_DELEGATE_GETTER(isNoInline());
453 }
454 void setIsNoInline(bool Value = true) {
455 CALLSITE_DELEGATE_SETTER(setIsNoInline(Value));
456 }
457
458 /// Determine if the call does not access memory.
459 bool doesNotAccessMemory() const {
460 CALLSITE_DELEGATE_GETTER(doesNotAccessMemory());
461 }
462 void setDoesNotAccessMemory() {
463 CALLSITE_DELEGATE_SETTER(setDoesNotAccessMemory());
464 }
465
466 /// Determine if the call does not access or only reads memory.
467 bool onlyReadsMemory() const {
468 CALLSITE_DELEGATE_GETTER(onlyReadsMemory());
469 }
470 void setOnlyReadsMemory() {
471 CALLSITE_DELEGATE_SETTER(setOnlyReadsMemory());
472 }
473
474 /// Determine if the call does not access or only writes memory.
475 bool doesNotReadMemory() const {
476 CALLSITE_DELEGATE_GETTER(doesNotReadMemory());
477 }
478 void setDoesNotReadMemory() {
479 CALLSITE_DELEGATE_SETTER(setDoesNotReadMemory());
480 }
481
482 /// Determine if the call can access memmory only using pointers based
483 /// on its arguments.
484 bool onlyAccessesArgMemory() const {
485 CALLSITE_DELEGATE_GETTER(onlyAccessesArgMemory());
486 }
487 void setOnlyAccessesArgMemory() {
488 CALLSITE_DELEGATE_SETTER(setOnlyAccessesArgMemory());
489 }
490
491 /// Determine if the function may only access memory that is
492 /// inaccessible from the IR.
493 bool onlyAccessesInaccessibleMemory() const {
494 CALLSITE_DELEGATE_GETTER(onlyAccessesInaccessibleMemory());
495 }
496 void setOnlyAccessesInaccessibleMemory() {
497 CALLSITE_DELEGATE_SETTER(setOnlyAccessesInaccessibleMemory());
498 }
499
500 /// Determine if the function may only access memory that is
501 /// either inaccessible from the IR or pointed to by its arguments.
502 bool onlyAccessesInaccessibleMemOrArgMem() const {
503 CALLSITE_DELEGATE_GETTER(onlyAccessesInaccessibleMemOrArgMem());
504 }
505 void setOnlyAccessesInaccessibleMemOrArgMem() {
506 CALLSITE_DELEGATE_SETTER(setOnlyAccessesInaccessibleMemOrArgMem());
507 }
508
509 /// Determine if the call cannot return.
510 bool doesNotReturn() const {
511 CALLSITE_DELEGATE_GETTER(doesNotReturn());
512 }
513 void setDoesNotReturn() {
514 CALLSITE_DELEGATE_SETTER(setDoesNotReturn());
515 }
516
517 /// Determine if the call cannot unwind.
518 bool doesNotThrow() const {
519 CALLSITE_DELEGATE_GETTER(doesNotThrow());
520 }
521 void setDoesNotThrow() {
522 CALLSITE_DELEGATE_SETTER(setDoesNotThrow());
523 }
524
525 /// Determine if the call can be duplicated.
526 bool cannotDuplicate() const {
527 CALLSITE_DELEGATE_GETTER(cannotDuplicate());
528 }
529 void setCannotDuplicate() {
530 CALLSITE_DELEGATE_SETTER(setCannotDuplicate());
531 }
532
533 /// Determine if the call is convergent.
534 bool isConvergent() const {
535 CALLSITE_DELEGATE_GETTER(isConvergent());
536 }
537 void setConvergent() {
538 CALLSITE_DELEGATE_SETTER(setConvergent());
539 }
540 void setNotConvergent() {
541 CALLSITE_DELEGATE_SETTER(setNotConvergent());
542 }
543
544 unsigned getNumOperandBundles() const {
545 CALLSITE_DELEGATE_GETTER(getNumOperandBundles());
546 }
547
548 bool hasOperandBundles() const {
549 CALLSITE_DELEGATE_GETTER(hasOperandBundles());
550 }
551
552 unsigned getBundleOperandsStartIndex() const {
553 CALLSITE_DELEGATE_GETTER(getBundleOperandsStartIndex());
554 }
555
556 unsigned getBundleOperandsEndIndex() const {
557 CALLSITE_DELEGATE_GETTER(getBundleOperandsEndIndex());
558 }
559
560 unsigned getNumTotalBundleOperands() const {
561 CALLSITE_DELEGATE_GETTER(getNumTotalBundleOperands());
562 }
563
564 OperandBundleUse getOperandBundleAt(unsigned Index) const {
565 CALLSITE_DELEGATE_GETTER(getOperandBundleAt(Index));
566 }
567
568 Optional<OperandBundleUse> getOperandBundle(StringRef Name) const {
569 CALLSITE_DELEGATE_GETTER(getOperandBundle(Name));
570 }
571
572 Optional<OperandBundleUse> getOperandBundle(uint32_t ID) const {
573 CALLSITE_DELEGATE_GETTER(getOperandBundle(ID));
574 }
575
576 unsigned countOperandBundlesOfType(uint32_t ID) const {
577 CALLSITE_DELEGATE_GETTER(countOperandBundlesOfType(ID));
578 }
579
580 bool isBundleOperand(unsigned Idx) const {
581 CALLSITE_DELEGATE_GETTER(isBundleOperand(Idx));
582 }
583
584 IterTy arg_begin() const {
585 CALLSITE_DELEGATE_GETTER(arg_begin());
586 }
587
588 IterTy arg_end() const {
589 CALLSITE_DELEGATE_GETTER(arg_end());
590 }
591
592#undef CALLSITE_DELEGATE_GETTER
593#undef CALLSITE_DELEGATE_SETTER
594
595 void getOperandBundlesAsDefs(SmallVectorImpl<OperandBundleDef> &Defs) const {
596 // Since this is actually a getter that "looks like" a setter, don't use the
597 // above macros to avoid confusion.
598 cast<CallBase>(getInstruction())->getOperandBundlesAsDefs(Defs);
599 }
600
601 /// Determine whether this data operand is not captured.
602 bool doesNotCapture(unsigned OpNo) const {
603 return dataOperandHasImpliedAttr(OpNo + 1, Attribute::NoCapture);
604 }
605
606 /// Determine whether this argument is passed by value.
607 bool isByValArgument(unsigned ArgNo) const {
608 return paramHasAttr(ArgNo, Attribute::ByVal);
609 }
610
611 /// Determine whether this argument is passed in an alloca.
612 bool isInAllocaArgument(unsigned ArgNo) const {
613 return paramHasAttr(ArgNo, Attribute::InAlloca);
614 }
615
616 /// Determine whether this argument is passed by value or in an alloca.
617 bool isByValOrInAllocaArgument(unsigned ArgNo) const {
618 return paramHasAttr(ArgNo, Attribute::ByVal) ||
619 paramHasAttr(ArgNo, Attribute::InAlloca);
620 }
621
622 /// Determine if there are is an inalloca argument. Only the last argument can
623 /// have the inalloca attribute.
624 bool hasInAllocaArgument() const {
625 return !arg_empty() && paramHasAttr(arg_size() - 1, Attribute::InAlloca);
626 }
627
628 bool doesNotAccessMemory(unsigned OpNo) const {
629 return dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadNone);
630 }
631
632 bool onlyReadsMemory(unsigned OpNo) const {
633 return dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadOnly) ||
634 dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadNone);
635 }
636
637 bool doesNotReadMemory(unsigned OpNo) const {
638 return dataOperandHasImpliedAttr(OpNo + 1, Attribute::WriteOnly) ||
639 dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadNone);
640 }
641
642 /// Return true if the return value is known to be not null.
643 /// This may be because it has the nonnull attribute, or because at least
644 /// one byte is dereferenceable and the pointer is in addrspace(0).
645 bool isReturnNonNull() const {
646 if (hasRetAttr(Attribute::NonNull))
647 return true;
648 else if (getDereferenceableBytes(AttributeList::ReturnIndex) > 0 &&
649 !NullPointerIsDefined(getCaller(),
650 getType()->getPointerAddressSpace()))
651 return true;
652
653 return false;
654 }
655
656 /// Returns true if this CallSite passes the given Value* as an argument to
657 /// the called function.
658 bool hasArgument(const Value *Arg) const {
659 for (arg_iterator AI = this->arg_begin(), E = this->arg_end(); AI != E;
660 ++AI)
661 if (AI->get() == Arg)
662 return true;
663 return false;
664 }
665
666private:
667 IterTy getCallee() const {
668 return cast<CallBase>(getInstruction())->op_end() - 1;
669 }
670};
671
672class CallSite : public CallSiteBase<Function, BasicBlock, Value, User, Use,
673 Instruction, CallInst, InvokeInst,
674 CallBrInst, User::op_iterator> {
675public:
676 CallSite() = default;
677 CallSite(CallSiteBase B) : CallSiteBase(B) {}
678 CallSite(CallInst *CI) : CallSiteBase(CI) {}
679 CallSite(InvokeInst *II) : CallSiteBase(II) {}
680 CallSite(CallBrInst *CBI) : CallSiteBase(CBI) {}
681 explicit CallSite(Instruction *II) : CallSiteBase(II) {}
682 explicit CallSite(Value *V) : CallSiteBase(V) {}
683
684 bool operator==(const CallSite &CS) const { return I == CS.I; }
685 bool operator!=(const CallSite &CS) const { return I != CS.I; }
686 bool operator<(const CallSite &CS) const {
687 return getInstruction() < CS.getInstruction();
688 }
689
690private:
691 friend struct DenseMapInfo<CallSite>;
692
693 User::op_iterator getCallee() const;
694};
695
696/// AbstractCallSite
697///
698/// An abstract call site is a wrapper that allows to treat direct,
699/// indirect, and callback calls the same. If an abstract call site
700/// represents a direct or indirect call site it behaves like a stripped
701/// down version of a normal call site object. The abstract call site can
702/// also represent a callback call, thus the fact that the initially
703/// called function (=broker) may invoke a third one (=callback callee).
704/// In this case, the abstract call site hides the middle man, hence the
705/// broker function. The result is a representation of the callback call,
706/// inside the broker, but in the context of the original call to the broker.
707///
708/// There are up to three functions involved when we talk about callback call
709/// sites. The caller (1), which invokes the broker function. The broker
710/// function (2), that will invoke the callee zero or more times. And finally
711/// the callee (3), which is the target of the callback call.
712///
713/// The abstract call site will handle the mapping from parameters to arguments
714/// depending on the semantic of the broker function. However, it is important
715/// to note that the mapping is often partial. Thus, some arguments of the
716/// call/invoke instruction are mapped to parameters of the callee while others
717/// are not.
718class AbstractCallSite {
719public:
720
721 /// The encoding of a callback with regards to the underlying instruction.
722 struct CallbackInfo {
723
724 /// For direct/indirect calls the parameter encoding is empty. If it is not,
725 /// the abstract call site represents a callback. In that case, the first
726 /// element of the encoding vector represents which argument of the call
727 /// site CS is the callback callee. The remaining elements map parameters
728 /// (identified by their position) to the arguments that will be passed
729 /// through (also identified by position but in the call site instruction).
730 ///
731 /// NOTE that we use LLVM argument numbers (starting at 0) and not
732 /// clang/source argument numbers (starting at 1). The -1 entries represent
733 /// unknown values that are passed to the callee.
734 using ParameterEncodingTy = SmallVector<int, 0>;
735 ParameterEncodingTy ParameterEncoding;
736
737 };
738
739private:
740
741 /// The underlying call site:
742 /// caller -> callee, if this is a direct or indirect call site
743 /// caller -> broker function, if this is a callback call site
744 CallSite CS;
745
746 /// The encoding of a callback with regards to the underlying instruction.
747 CallbackInfo CI;
748
749public:
750 /// Sole constructor for abstract call sites (ACS).
751 ///
752 /// An abstract call site can only be constructed through a llvm::Use because
753 /// each operand (=use) of an instruction could potentially be a different
754 /// abstract call site. Furthermore, even if the value of the llvm::Use is the
755 /// same, and the user is as well, the abstract call sites might not be.
756 ///
757 /// If a use is not associated with an abstract call site the constructed ACS
758 /// will evaluate to false if converted to a boolean.
759 ///
760 /// If the use is the callee use of a call or invoke instruction, the
761 /// constructed abstract call site will behave as a llvm::CallSite would.
762 ///
763 /// If the use is not a callee use of a call or invoke instruction, the
764 /// callback metadata is used to determine the argument <-> parameter mapping
765 /// as well as the callee of the abstract call site.
766 AbstractCallSite(const Use *U);
767
768 /// Conversion operator to conveniently check for a valid/initialized ACS.
769 explicit operator bool() const { return (bool)CS; }
770
771 /// Return the underlying instruction.
772 Instruction *getInstruction() const { return CS.getInstruction(); }
773
774 /// Return the call site abstraction for the underlying instruction.
775 CallSite getCallSite() const { return CS; }
776
777 /// Return true if this ACS represents a direct call.
778 bool isDirectCall() const {
779 return !isCallbackCall() && !CS.isIndirectCall();
780 }
781
782 /// Return true if this ACS represents an indirect call.
783 bool isIndirectCall() const {
784 return !isCallbackCall() && CS.isIndirectCall();
785 }
786
787 /// Return true if this ACS represents a callback call.
788 bool isCallbackCall() const {
789 // For a callback call site the callee is ALWAYS stored first in the
790 // transitive values vector. Thus, a non-empty vector indicates a callback.
791 return !CI.ParameterEncoding.empty();
792 }
793
794 /// Return true if @p UI is the use that defines the callee of this ACS.
795 bool isCallee(Value::const_user_iterator UI) const {
796 return isCallee(&UI.getUse());
797 }
798
799 /// Return true if @p U is the use that defines the callee of this ACS.
800 bool isCallee(const Use *U) const {
801 if (isDirectCall())
802 return CS.isCallee(U);
803
804 assert(!CI.ParameterEncoding.empty() &&((!CI.ParameterEncoding.empty() && "Callback without parameter encoding!"
) ? static_cast<void> (0) : __assert_fail ("!CI.ParameterEncoding.empty() && \"Callback without parameter encoding!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h"
, 805, __PRETTY_FUNCTION__))
805 "Callback without parameter encoding!")((!CI.ParameterEncoding.empty() && "Callback without parameter encoding!"
) ? static_cast<void> (0) : __assert_fail ("!CI.ParameterEncoding.empty() && \"Callback without parameter encoding!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h"
, 805, __PRETTY_FUNCTION__))
;
806
807 return (int)CS.getArgumentNo(U) == CI.ParameterEncoding[0];
808 }
809
810 /// Return the number of parameters of the callee.
811 unsigned getNumArgOperands() const {
812 if (isDirectCall())
813 return CS.getNumArgOperands();
814 // Subtract 1 for the callee encoding.
815 return CI.ParameterEncoding.size() - 1;
816 }
817
818 /// Return the operand index of the underlying instruction associated with @p
819 /// Arg.
820 int getCallArgOperandNo(Argument &Arg) const {
821 return getCallArgOperandNo(Arg.getArgNo());
822 }
823
824 /// Return the operand index of the underlying instruction associated with
825 /// the function parameter number @p ArgNo or -1 if there is none.
826 int getCallArgOperandNo(unsigned ArgNo) const {
827 if (isDirectCall())
828 return ArgNo;
829 // Add 1 for the callee encoding.
830 return CI.ParameterEncoding[ArgNo + 1];
831 }
832
833 /// Return the operand of the underlying instruction associated with @p Arg.
834 Value *getCallArgOperand(Argument &Arg) const {
835 return getCallArgOperand(Arg.getArgNo());
836 }
837
838 /// Return the operand of the underlying instruction associated with the
839 /// function parameter number @p ArgNo or nullptr if there is none.
840 Value *getCallArgOperand(unsigned ArgNo) const {
841 if (isDirectCall())
842 return CS.getArgOperand(ArgNo);
843 // Add 1 for the callee encoding.
844 return CI.ParameterEncoding[ArgNo + 1] >= 0
845 ? CS.getArgOperand(CI.ParameterEncoding[ArgNo + 1])
846 : nullptr;
847 }
848
849 /// Return the operand index of the underlying instruction associated with the
850 /// callee of this ACS. Only valid for callback calls!
851 int getCallArgOperandNoForCallee() const {
852 assert(isCallbackCall())((isCallbackCall()) ? static_cast<void> (0) : __assert_fail
("isCallbackCall()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h"
, 852, __PRETTY_FUNCTION__))
;
853 assert(CI.ParameterEncoding.size() && CI.ParameterEncoding[0] >= 0)((CI.ParameterEncoding.size() && CI.ParameterEncoding
[0] >= 0) ? static_cast<void> (0) : __assert_fail ("CI.ParameterEncoding.size() && CI.ParameterEncoding[0] >= 0"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h"
, 853, __PRETTY_FUNCTION__))
;
854 return CI.ParameterEncoding[0];
855 }
856
857 /// Return the use of the callee value in the underlying instruction. Only
858 /// valid for callback calls!
859 const Use &getCalleeUseForCallback() const {
860 int CalleeArgIdx = getCallArgOperandNoForCallee();
861 assert(CalleeArgIdx >= 0 &&((CalleeArgIdx >= 0 && unsigned(CalleeArgIdx) <
getInstruction()->getNumOperands()) ? static_cast<void
> (0) : __assert_fail ("CalleeArgIdx >= 0 && unsigned(CalleeArgIdx) < getInstruction()->getNumOperands()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h"
, 862, __PRETTY_FUNCTION__))
862 unsigned(CalleeArgIdx) < getInstruction()->getNumOperands())((CalleeArgIdx >= 0 && unsigned(CalleeArgIdx) <
getInstruction()->getNumOperands()) ? static_cast<void
> (0) : __assert_fail ("CalleeArgIdx >= 0 && unsigned(CalleeArgIdx) < getInstruction()->getNumOperands()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/CallSite.h"
, 862, __PRETTY_FUNCTION__))
;
863 return getInstruction()->getOperandUse(CalleeArgIdx);
864 }
865
866 /// Return the pointer to function that is being called.
867 Value *getCalledValue() const {
868 if (isDirectCall())
869 return CS.getCalledValue();
870 return CS.getArgOperand(getCallArgOperandNoForCallee());
871 }
872
873 /// Return the function being called if this is a direct call, otherwise
874 /// return null (if it's an indirect call).
875 Function *getCalledFunction() const {
876 Value *V = getCalledValue();
877 return V ? dyn_cast<Function>(V->stripPointerCasts()) : nullptr;
878 }
879};
880
881template <> struct DenseMapInfo<CallSite> {
882 using BaseInfo = DenseMapInfo<decltype(CallSite::I)>;
883
884 static CallSite getEmptyKey() {
885 CallSite CS;
886 CS.I = BaseInfo::getEmptyKey();
887 return CS;
888 }
889
890 static CallSite getTombstoneKey() {
891 CallSite CS;
892 CS.I = BaseInfo::getTombstoneKey();
893 return CS;
894 }
895
896 static unsigned getHashValue(const CallSite &CS) {
897 return BaseInfo::getHashValue(CS.I);
898 }
899
900 static bool isEqual(const CallSite &LHS, const CallSite &RHS) {
901 return LHS == RHS;
902 }
903};
904
905/// Establish a view to a call site for examination.
906class ImmutableCallSite : public CallSiteBase<> {
907public:
908 ImmutableCallSite() = default;
909 ImmutableCallSite(const CallInst *CI) : CallSiteBase(CI) {}
910 ImmutableCallSite(const InvokeInst *II) : CallSiteBase(II) {}
911 ImmutableCallSite(const CallBrInst *CBI) : CallSiteBase(CBI) {}
912 explicit ImmutableCallSite(const Instruction *II) : CallSiteBase(II) {}
913 explicit ImmutableCallSite(const Value *V) : CallSiteBase(V) {}
914 ImmutableCallSite(CallSite CS) : CallSiteBase(CS.getInstruction()) {}
915};
916
917} // end namespace llvm
918
919#endif // LLVM_IR_CALLSITE_H

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/ADT/PointerIntPair.h

1//===- llvm/ADT/PointerIntPair.h - Pair for pointer and int -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the PointerIntPair class.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_ADT_POINTERINTPAIR_H
14#define LLVM_ADT_POINTERINTPAIR_H
15
16#include "llvm/Support/Compiler.h"
17#include "llvm/Support/PointerLikeTypeTraits.h"
18#include "llvm/Support/type_traits.h"
19#include <cassert>
20#include <cstdint>
21#include <limits>
22
23namespace llvm {
24
25template <typename T> struct DenseMapInfo;
26template <typename PointerT, unsigned IntBits, typename PtrTraits>
27struct PointerIntPairInfo;
28
29/// PointerIntPair - This class implements a pair of a pointer and small
30/// integer. It is designed to represent this in the space required by one
31/// pointer by bitmangling the integer into the low part of the pointer. This
32/// can only be done for small integers: typically up to 3 bits, but it depends
33/// on the number of bits available according to PointerLikeTypeTraits for the
34/// type.
35///
36/// Note that PointerIntPair always puts the IntVal part in the highest bits
37/// possible. For example, PointerIntPair<void*, 1, bool> will put the bit for
38/// the bool into bit #2, not bit #0, which allows the low two bits to be used
39/// for something else. For example, this allows:
40/// PointerIntPair<PointerIntPair<void*, 1, bool>, 1, bool>
41/// ... and the two bools will land in different bits.
42template <typename PointerTy, unsigned IntBits, typename IntType = unsigned,
43 typename PtrTraits = PointerLikeTypeTraits<PointerTy>,
44 typename Info = PointerIntPairInfo<PointerTy, IntBits, PtrTraits>>
45class PointerIntPair {
46 // Used by MSVC visualizer and generally helpful for debugging/visualizing.
47 using InfoTy = Info;
48 intptr_t Value = 0;
49
50public:
51 constexpr PointerIntPair() = default;
52
53 PointerIntPair(PointerTy PtrVal, IntType IntVal) {
54 setPointerAndInt(PtrVal, IntVal);
55 }
56
57 explicit PointerIntPair(PointerTy PtrVal) { initWithPointer(PtrVal); }
58
59 PointerTy getPointer() const { return Info::getPointer(Value); }
14
Calling 'PointerIntPairInfo::getPointer'
22
Returning from 'PointerIntPairInfo::getPointer'
23
Returning null pointer, which participates in a condition later
60
61 IntType getInt() const { return (IntType)Info::getInt(Value); }
62
63 void setPointer(PointerTy PtrVal) LLVM_LVALUE_FUNCTION& {
64 Value = Info::updatePointer(Value, PtrVal);
65 }
66
67 void setInt(IntType IntVal) LLVM_LVALUE_FUNCTION& {
68 Value = Info::updateInt(Value, static_cast<intptr_t>(IntVal));
69 }
70
71 void initWithPointer(PointerTy PtrVal) LLVM_LVALUE_FUNCTION& {
72 Value = Info::updatePointer(0, PtrVal);
73 }
74
75 void setPointerAndInt(PointerTy PtrVal, IntType IntVal) LLVM_LVALUE_FUNCTION& {
76 Value = Info::updateInt(Info::updatePointer(0, PtrVal),
77 static_cast<intptr_t>(IntVal));
78 }
79
80 PointerTy const *getAddrOfPointer() const {
81 return const_cast<PointerIntPair *>(this)->getAddrOfPointer();
82 }
83
84 PointerTy *getAddrOfPointer() {
85 assert(Value == reinterpret_cast<intptr_t>(getPointer()) &&((Value == reinterpret_cast<intptr_t>(getPointer()) &&
"Can only return the address if IntBits is cleared and " "PtrTraits doesn't change the pointer"
) ? static_cast<void> (0) : __assert_fail ("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/ADT/PointerIntPair.h"
, 87, __PRETTY_FUNCTION__))
86 "Can only return the address if IntBits is cleared and "((Value == reinterpret_cast<intptr_t>(getPointer()) &&
"Can only return the address if IntBits is cleared and " "PtrTraits doesn't change the pointer"
) ? static_cast<void> (0) : __assert_fail ("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/ADT/PointerIntPair.h"
, 87, __PRETTY_FUNCTION__))
87 "PtrTraits doesn't change the pointer")((Value == reinterpret_cast<intptr_t>(getPointer()) &&
"Can only return the address if IntBits is cleared and " "PtrTraits doesn't change the pointer"
) ? static_cast<void> (0) : __assert_fail ("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/ADT/PointerIntPair.h"
, 87, __PRETTY_FUNCTION__))
;
88 return reinterpret_cast<PointerTy *>(&Value);
89 }
90
91 void *getOpaqueValue() const { return reinterpret_cast<void *>(Value); }
92
93 void setFromOpaqueValue(void *Val) LLVM_LVALUE_FUNCTION& {
94 Value = reinterpret_cast<intptr_t>(Val);
95 }
96
97 static PointerIntPair getFromOpaqueValue(void *V) {
98 PointerIntPair P;
99 P.setFromOpaqueValue(V);
100 return P;
101 }
102
103 // Allow PointerIntPairs to be created from const void * if and only if the
104 // pointer type could be created from a const void *.
105 static PointerIntPair getFromOpaqueValue(const void *V) {
106 (void)PtrTraits::getFromVoidPointer(V);
107 return getFromOpaqueValue(const_cast<void *>(V));
108 }
109
110 bool operator==(const PointerIntPair &RHS) const {
111 return Value == RHS.Value;
112 }
113
114 bool operator!=(const PointerIntPair &RHS) const {
115 return Value != RHS.Value;
116 }
117
118 bool operator<(const PointerIntPair &RHS) const { return Value < RHS.Value; }
119 bool operator>(const PointerIntPair &RHS) const { return Value > RHS.Value; }
120
121 bool operator<=(const PointerIntPair &RHS) const {
122 return Value <= RHS.Value;
123 }
124
125 bool operator>=(const PointerIntPair &RHS) const {
126 return Value >= RHS.Value;
127 }
128};
129
130// Specialize is_trivially_copyable to avoid limitation of llvm::is_trivially_copyable
131// when compiled with gcc 4.9.
132template <typename PointerTy, unsigned IntBits, typename IntType,
133 typename PtrTraits,
134 typename Info>
135struct is_trivially_copyable<PointerIntPair<PointerTy, IntBits, IntType, PtrTraits, Info>> : std::true_type {
136#ifdef HAVE_STD_IS_TRIVIALLY_COPYABLE
137 static_assert(std::is_trivially_copyable<PointerIntPair<PointerTy, IntBits, IntType, PtrTraits, Info>>::value,
138 "inconsistent behavior between llvm:: and std:: implementation of is_trivially_copyable");
139#endif
140};
141
142
143template <typename PointerT, unsigned IntBits, typename PtrTraits>
144struct PointerIntPairInfo {
145 static_assert(PtrTraits::NumLowBitsAvailable <
146 std::numeric_limits<uintptr_t>::digits,
147 "cannot use a pointer type that has all bits free");
148 static_assert(IntBits <= PtrTraits::NumLowBitsAvailable,
149 "PointerIntPair with integer size too large for pointer");
150 enum : uintptr_t {
151 /// PointerBitMask - The bits that come from the pointer.
152 PointerBitMask =
153 ~(uintptr_t)(((intptr_t)1 << PtrTraits::NumLowBitsAvailable) - 1),
154
155 /// IntShift - The number of low bits that we reserve for other uses, and
156 /// keep zero.
157 IntShift = (uintptr_t)PtrTraits::NumLowBitsAvailable - IntBits,
158
159 /// IntMask - This is the unshifted mask for valid bits of the int type.
160 IntMask = (uintptr_t)(((intptr_t)1 << IntBits) - 1),
161
162 // ShiftedIntMask - This is the bits for the integer shifted in place.
163 ShiftedIntMask = (uintptr_t)(IntMask << IntShift)
164 };
165
166 static PointerT getPointer(intptr_t Value) {
167 return PtrTraits::getFromVoidPointer(
15
Calling 'PointerLikeTypeTraits::getFromVoidPointer'
20
Returning from 'PointerLikeTypeTraits::getFromVoidPointer'
21
Returning null pointer, which participates in a condition later
168 reinterpret_cast<void *>(Value & PointerBitMask));
169 }
170
171 static intptr_t getInt(intptr_t Value) {
172 return (Value >> IntShift) & IntMask;
173 }
174
175 static intptr_t updatePointer(intptr_t OrigValue, PointerT Ptr) {
176 intptr_t PtrWord =
177 reinterpret_cast<intptr_t>(PtrTraits::getAsVoidPointer(Ptr));
178 assert((PtrWord & ~PointerBitMask) == 0 &&(((PtrWord & ~PointerBitMask) == 0 && "Pointer is not sufficiently aligned"
) ? static_cast<void> (0) : __assert_fail ("(PtrWord & ~PointerBitMask) == 0 && \"Pointer is not sufficiently aligned\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/ADT/PointerIntPair.h"
, 179, __PRETTY_FUNCTION__))
179 "Pointer is not sufficiently aligned")(((PtrWord & ~PointerBitMask) == 0 && "Pointer is not sufficiently aligned"
) ? static_cast<void> (0) : __assert_fail ("(PtrWord & ~PointerBitMask) == 0 && \"Pointer is not sufficiently aligned\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/ADT/PointerIntPair.h"
, 179, __PRETTY_FUNCTION__))
;
180 // Preserve all low bits, just update the pointer.
181 return PtrWord | (OrigValue & ~PointerBitMask);
182 }
183
184 static intptr_t updateInt(intptr_t OrigValue, intptr_t Int) {
185 intptr_t IntWord = static_cast<intptr_t>(Int);
186 assert((IntWord & ~IntMask) == 0 && "Integer too large for field")(((IntWord & ~IntMask) == 0 && "Integer too large for field"
) ? static_cast<void> (0) : __assert_fail ("(IntWord & ~IntMask) == 0 && \"Integer too large for field\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/ADT/PointerIntPair.h"
, 186, __PRETTY_FUNCTION__))
;
187
188 // Preserve all bits other than the ones we are updating.
189 return (OrigValue & ~ShiftedIntMask) | IntWord << IntShift;
190 }
191};
192
193// Provide specialization of DenseMapInfo for PointerIntPair.
194template <typename PointerTy, unsigned IntBits, typename IntType>
195struct DenseMapInfo<PointerIntPair<PointerTy, IntBits, IntType>> {
196 using Ty = PointerIntPair<PointerTy, IntBits, IntType>;
197
198 static Ty getEmptyKey() {
199 uintptr_t Val = static_cast<uintptr_t>(-1);
200 Val <<= PointerLikeTypeTraits<Ty>::NumLowBitsAvailable;
201 return Ty::getFromOpaqueValue(reinterpret_cast<void *>(Val));
202 }
203
204 static Ty getTombstoneKey() {
205