Bug Summary

File:include/llvm/Analysis/TargetTransformInfoImpl.h
Warning:line 715, column 52
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 ARMTargetTransformInfo.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 -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-8/lib/clang/8.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/lib/Target/ARM -I /build/llvm-toolchain-snapshot-8~svn345461/lib/Target/ARM -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn345461/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/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.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++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/lib/Target/ARM -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-10-27-211344-32123-1 -x c++ /build/llvm-toolchain-snapshot-8~svn345461/lib/Target/ARM/ARMTargetTransformInfo.cpp -faddrsig

/build/llvm-toolchain-snapshot-8~svn345461/lib/Target/ARM/ARMTargetTransformInfo.cpp

1//===- ARMTargetTransformInfo.cpp - ARM specific TTI ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "ARMTargetTransformInfo.h"
11#include "ARMSubtarget.h"
12#include "MCTargetDesc/ARMAddressingModes.h"
13#include "llvm/ADT/APInt.h"
14#include "llvm/ADT/SmallVector.h"
15#include "llvm/Analysis/LoopInfo.h"
16#include "llvm/CodeGen/CostTable.h"
17#include "llvm/CodeGen/ISDOpcodes.h"
18#include "llvm/CodeGen/ValueTypes.h"
19#include "llvm/IR/BasicBlock.h"
20#include "llvm/IR/CallSite.h"
21#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/DerivedTypes.h"
23#include "llvm/IR/Instruction.h"
24#include "llvm/IR/Instructions.h"
25#include "llvm/IR/Type.h"
26#include "llvm/MC/SubtargetFeature.h"
27#include "llvm/Support/Casting.h"
28#include "llvm/Support/MachineValueType.h"
29#include "llvm/Target/TargetMachine.h"
30#include <algorithm>
31#include <cassert>
32#include <cstdint>
33#include <utility>
34
35using namespace llvm;
36
37#define DEBUG_TYPE"armtti" "armtti"
38
39bool ARMTTIImpl::areInlineCompatible(const Function *Caller,
40 const Function *Callee) const {
41 const TargetMachine &TM = getTLI()->getTargetMachine();
42 const FeatureBitset &CallerBits =
43 TM.getSubtargetImpl(*Caller)->getFeatureBits();
44 const FeatureBitset &CalleeBits =
45 TM.getSubtargetImpl(*Callee)->getFeatureBits();
46
47 // To inline a callee, all features not in the whitelist must match exactly.
48 bool MatchExact = (CallerBits & ~InlineFeatureWhitelist) ==
49 (CalleeBits & ~InlineFeatureWhitelist);
50 // For features in the whitelist, the callee's features must be a subset of
51 // the callers'.
52 bool MatchSubset = ((CallerBits & CalleeBits) & InlineFeatureWhitelist) ==
53 (CalleeBits & InlineFeatureWhitelist);
54 return MatchExact && MatchSubset;
55}
56
57int ARMTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty) {
58 assert(Ty->isIntegerTy())((Ty->isIntegerTy()) ? static_cast<void> (0) : __assert_fail
("Ty->isIntegerTy()", "/build/llvm-toolchain-snapshot-8~svn345461/lib/Target/ARM/ARMTargetTransformInfo.cpp"
, 58, __PRETTY_FUNCTION__))
;
59
60 unsigned Bits = Ty->getPrimitiveSizeInBits();
61 if (Bits == 0 || Imm.getActiveBits() >= 64)
62 return 4;
63
64 int64_t SImmVal = Imm.getSExtValue();
65 uint64_t ZImmVal = Imm.getZExtValue();
66 if (!ST->isThumb()) {
67 if ((SImmVal >= 0 && SImmVal < 65536) ||
68 (ARM_AM::getSOImmVal(ZImmVal) != -1) ||
69 (ARM_AM::getSOImmVal(~ZImmVal) != -1))
70 return 1;
71 return ST->hasV6T2Ops() ? 2 : 3;
72 }
73 if (ST->isThumb2()) {
74 if ((SImmVal >= 0 && SImmVal < 65536) ||
75 (ARM_AM::getT2SOImmVal(ZImmVal) != -1) ||
76 (ARM_AM::getT2SOImmVal(~ZImmVal) != -1))
77 return 1;
78 return ST->hasV6T2Ops() ? 2 : 3;
79 }
80 // Thumb1, any i8 imm cost 1.
81 if (Bits == 8 || (SImmVal >= 0 && SImmVal < 256))
82 return 1;
83 if ((~SImmVal < 256) || ARM_AM::isThumbImmShiftedVal(ZImmVal))
84 return 2;
85 // Load from constantpool.
86 return 3;
87}
88
89// Constants smaller than 256 fit in the immediate field of
90// Thumb1 instructions so we return a zero cost and 1 otherwise.
91int ARMTTIImpl::getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx,
92 const APInt &Imm, Type *Ty) {
93 if (Imm.isNonNegative() && Imm.getLimitedValue() < 256)
94 return 0;
95
96 return 1;
97}
98
99int ARMTTIImpl::getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
100 Type *Ty) {
101 // Division by a constant can be turned into multiplication, but only if we
102 // know it's constant. So it's not so much that the immediate is cheap (it's
103 // not), but that the alternative is worse.
104 // FIXME: this is probably unneeded with GlobalISel.
105 if ((Opcode == Instruction::SDiv || Opcode == Instruction::UDiv ||
106 Opcode == Instruction::SRem || Opcode == Instruction::URem) &&
107 Idx == 1)
108 return 0;
109
110 if (Opcode == Instruction::And)
111 // Conversion to BIC is free, and means we can use ~Imm instead.
112 return std::min(getIntImmCost(Imm, Ty), getIntImmCost(~Imm, Ty));
113
114 if (Opcode == Instruction::Add)
115 // Conversion to SUB is free, and means we can use -Imm instead.
116 return std::min(getIntImmCost(Imm, Ty), getIntImmCost(-Imm, Ty));
117
118 if (Opcode == Instruction::ICmp && Imm.isNegative() &&
119 Ty->getIntegerBitWidth() == 32) {
120 int64_t NegImm = -Imm.getSExtValue();
121 if (ST->isThumb2() && NegImm < 1<<12)
122 // icmp X, #-C -> cmn X, #C
123 return 0;
124 if (ST->isThumb() && NegImm < 1<<8)
125 // icmp X, #-C -> adds X, #C
126 return 0;
127 }
128
129 // xor a, -1 can always be folded to MVN
130 if (Opcode == Instruction::Xor && Imm.isAllOnesValue())
131 return 0;
132
133 return getIntImmCost(Imm, Ty);
134}
135
136int ARMTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
137 const Instruction *I) {
138 int ISD = TLI->InstructionOpcodeToISD(Opcode);
139 assert(ISD && "Invalid opcode")((ISD && "Invalid opcode") ? static_cast<void> (
0) : __assert_fail ("ISD && \"Invalid opcode\"", "/build/llvm-toolchain-snapshot-8~svn345461/lib/Target/ARM/ARMTargetTransformInfo.cpp"
, 139, __PRETTY_FUNCTION__))
;
140
141 // Single to/from double precision conversions.
142 static const CostTblEntry NEONFltDblTbl[] = {
143 // Vector fptrunc/fpext conversions.
144 { ISD::FP_ROUND, MVT::v2f64, 2 },
145 { ISD::FP_EXTEND, MVT::v2f32, 2 },
146 { ISD::FP_EXTEND, MVT::v4f32, 4 }
147 };
148
149 if (Src->isVectorTy() && ST->hasNEON() && (ISD == ISD::FP_ROUND ||
150 ISD == ISD::FP_EXTEND)) {
151 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
152 if (const auto *Entry = CostTableLookup(NEONFltDblTbl, ISD, LT.second))
153 return LT.first * Entry->Cost;
154 }
155
156 EVT SrcTy = TLI->getValueType(DL, Src);
157 EVT DstTy = TLI->getValueType(DL, Dst);
158
159 if (!SrcTy.isSimple() || !DstTy.isSimple())
160 return BaseT::getCastInstrCost(Opcode, Dst, Src);
161
162 // Some arithmetic, load and store operations have specific instructions
163 // to cast up/down their types automatically at no extra cost.
164 // TODO: Get these tables to know at least what the related operations are.
165 static const TypeConversionCostTblEntry NEONVectorConversionTbl[] = {
166 { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 0 },
167 { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 0 },
168 { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i32, 1 },
169 { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i32, 1 },
170 { ISD::TRUNCATE, MVT::v4i32, MVT::v4i64, 0 },
171 { ISD::TRUNCATE, MVT::v4i16, MVT::v4i32, 1 },
172
173 // The number of vmovl instructions for the extension.
174 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
175 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
176 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i8, 3 },
177 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i8, 3 },
178 { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i8, 7 },
179 { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i8, 7 },
180 { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i16, 6 },
181 { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i16, 6 },
182 { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
183 { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
184
185 // Operations that we legalize using splitting.
186 { ISD::TRUNCATE, MVT::v16i8, MVT::v16i32, 6 },
187 { ISD::TRUNCATE, MVT::v8i8, MVT::v8i32, 3 },
188
189 // Vector float <-> i32 conversions.
190 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
191 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
192
193 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i8, 3 },
194 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i8, 3 },
195 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i16, 2 },
196 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i16, 2 },
197 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 },
198 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 },
199 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i1, 3 },
200 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i1, 3 },
201 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i8, 3 },
202 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i8, 3 },
203 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 },
204 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 },
205 { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 },
206 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 },
207 { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i32, 2 },
208 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i32, 2 },
209 { ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i16, 8 },
210 { ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i16, 8 },
211 { ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i32, 4 },
212 { ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i32, 4 },
213
214 { ISD::FP_TO_SINT, MVT::v4i32, MVT::v4f32, 1 },
215 { ISD::FP_TO_UINT, MVT::v4i32, MVT::v4f32, 1 },
216 { ISD::FP_TO_SINT, MVT::v4i8, MVT::v4f32, 3 },
217 { ISD::FP_TO_UINT, MVT::v4i8, MVT::v4f32, 3 },
218 { ISD::FP_TO_SINT, MVT::v4i16, MVT::v4f32, 2 },
219 { ISD::FP_TO_UINT, MVT::v4i16, MVT::v4f32, 2 },
220
221 // Vector double <-> i32 conversions.
222 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
223 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
224
225 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i8, 4 },
226 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i8, 4 },
227 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i16, 3 },
228 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i16, 3 },
229 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
230 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
231
232 { ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f64, 2 },
233 { ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f64, 2 },
234 { ISD::FP_TO_SINT, MVT::v8i16, MVT::v8f32, 4 },
235 { ISD::FP_TO_UINT, MVT::v8i16, MVT::v8f32, 4 },
236 { ISD::FP_TO_SINT, MVT::v16i16, MVT::v16f32, 8 },
237 { ISD::FP_TO_UINT, MVT::v16i16, MVT::v16f32, 8 }
238 };
239
240 if (SrcTy.isVector() && ST->hasNEON()) {
241 if (const auto *Entry = ConvertCostTableLookup(NEONVectorConversionTbl, ISD,
242 DstTy.getSimpleVT(),
243 SrcTy.getSimpleVT()))
244 return Entry->Cost;
245 }
246
247 // Scalar float to integer conversions.
248 static const TypeConversionCostTblEntry NEONFloatConversionTbl[] = {
249 { ISD::FP_TO_SINT, MVT::i1, MVT::f32, 2 },
250 { ISD::FP_TO_UINT, MVT::i1, MVT::f32, 2 },
251 { ISD::FP_TO_SINT, MVT::i1, MVT::f64, 2 },
252 { ISD::FP_TO_UINT, MVT::i1, MVT::f64, 2 },
253 { ISD::FP_TO_SINT, MVT::i8, MVT::f32, 2 },
254 { ISD::FP_TO_UINT, MVT::i8, MVT::f32, 2 },
255 { ISD::FP_TO_SINT, MVT::i8, MVT::f64, 2 },
256 { ISD::FP_TO_UINT, MVT::i8, MVT::f64, 2 },
257 { ISD::FP_TO_SINT, MVT::i16, MVT::f32, 2 },
258 { ISD::FP_TO_UINT, MVT::i16, MVT::f32, 2 },
259 { ISD::FP_TO_SINT, MVT::i16, MVT::f64, 2 },
260 { ISD::FP_TO_UINT, MVT::i16, MVT::f64, 2 },
261 { ISD::FP_TO_SINT, MVT::i32, MVT::f32, 2 },
262 { ISD::FP_TO_UINT, MVT::i32, MVT::f32, 2 },
263 { ISD::FP_TO_SINT, MVT::i32, MVT::f64, 2 },
264 { ISD::FP_TO_UINT, MVT::i32, MVT::f64, 2 },
265 { ISD::FP_TO_SINT, MVT::i64, MVT::f32, 10 },
266 { ISD::FP_TO_UINT, MVT::i64, MVT::f32, 10 },
267 { ISD::FP_TO_SINT, MVT::i64, MVT::f64, 10 },
268 { ISD::FP_TO_UINT, MVT::i64, MVT::f64, 10 }
269 };
270 if (SrcTy.isFloatingPoint() && ST->hasNEON()) {
271 if (const auto *Entry = ConvertCostTableLookup(NEONFloatConversionTbl, ISD,
272 DstTy.getSimpleVT(),
273 SrcTy.getSimpleVT()))
274 return Entry->Cost;
275 }
276
277 // Scalar integer to float conversions.
278 static const TypeConversionCostTblEntry NEONIntegerConversionTbl[] = {
279 { ISD::SINT_TO_FP, MVT::f32, MVT::i1, 2 },
280 { ISD::UINT_TO_FP, MVT::f32, MVT::i1, 2 },
281 { ISD::SINT_TO_FP, MVT::f64, MVT::i1, 2 },
282 { ISD::UINT_TO_FP, MVT::f64, MVT::i1, 2 },
283 { ISD::SINT_TO_FP, MVT::f32, MVT::i8, 2 },
284 { ISD::UINT_TO_FP, MVT::f32, MVT::i8, 2 },
285 { ISD::SINT_TO_FP, MVT::f64, MVT::i8, 2 },
286 { ISD::UINT_TO_FP, MVT::f64, MVT::i8, 2 },
287 { ISD::SINT_TO_FP, MVT::f32, MVT::i16, 2 },
288 { ISD::UINT_TO_FP, MVT::f32, MVT::i16, 2 },
289 { ISD::SINT_TO_FP, MVT::f64, MVT::i16, 2 },
290 { ISD::UINT_TO_FP, MVT::f64, MVT::i16, 2 },
291 { ISD::SINT_TO_FP, MVT::f32, MVT::i32, 2 },
292 { ISD::UINT_TO_FP, MVT::f32, MVT::i32, 2 },
293 { ISD::SINT_TO_FP, MVT::f64, MVT::i32, 2 },
294 { ISD::UINT_TO_FP, MVT::f64, MVT::i32, 2 },
295 { ISD::SINT_TO_FP, MVT::f32, MVT::i64, 10 },
296 { ISD::UINT_TO_FP, MVT::f32, MVT::i64, 10 },
297 { ISD::SINT_TO_FP, MVT::f64, MVT::i64, 10 },
298 { ISD::UINT_TO_FP, MVT::f64, MVT::i64, 10 }
299 };
300
301 if (SrcTy.isInteger() && ST->hasNEON()) {
302 if (const auto *Entry = ConvertCostTableLookup(NEONIntegerConversionTbl,
303 ISD, DstTy.getSimpleVT(),
304 SrcTy.getSimpleVT()))
305 return Entry->Cost;
306 }
307
308 // Scalar integer conversion costs.
309 static const TypeConversionCostTblEntry ARMIntegerConversionTbl[] = {
310 // i16 -> i64 requires two dependent operations.
311 { ISD::SIGN_EXTEND, MVT::i64, MVT::i16, 2 },
312
313 // Truncates on i64 are assumed to be free.
314 { ISD::TRUNCATE, MVT::i32, MVT::i64, 0 },
315 { ISD::TRUNCATE, MVT::i16, MVT::i64, 0 },
316 { ISD::TRUNCATE, MVT::i8, MVT::i64, 0 },
317 { ISD::TRUNCATE, MVT::i1, MVT::i64, 0 }
318 };
319
320 if (SrcTy.isInteger()) {
321 if (const auto *Entry = ConvertCostTableLookup(ARMIntegerConversionTbl, ISD,
322 DstTy.getSimpleVT(),
323 SrcTy.getSimpleVT()))
324 return Entry->Cost;
325 }
326
327 return BaseT::getCastInstrCost(Opcode, Dst, Src);
328}
329
330int ARMTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy,
331 unsigned Index) {
332 // Penalize inserting into an D-subregister. We end up with a three times
333 // lower estimated throughput on swift.
334 if (ST->hasSlowLoadDSubregister() && Opcode == Instruction::InsertElement &&
335 ValTy->isVectorTy() && ValTy->getScalarSizeInBits() <= 32)
336 return 3;
337
338 if ((Opcode == Instruction::InsertElement ||
339 Opcode == Instruction::ExtractElement)) {
340 // Cross-class copies are expensive on many microarchitectures,
341 // so assume they are expensive by default.
342 if (ValTy->getVectorElementType()->isIntegerTy())
343 return 3;
344
345 // Even if it's not a cross class copy, this likely leads to mixing
346 // of NEON and VFP code and should be therefore penalized.
347 if (ValTy->isVectorTy() &&
348 ValTy->getScalarSizeInBits() <= 32)
349 return std::max(BaseT::getVectorInstrCost(Opcode, ValTy, Index), 2U);
350 }
351
352 return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
353}
354
355int ARMTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
356 const Instruction *I) {
357 int ISD = TLI->InstructionOpcodeToISD(Opcode);
358 // On NEON a vector select gets lowered to vbsl.
359 if (ST->hasNEON() && ValTy->isVectorTy() && ISD == ISD::SELECT) {
360 // Lowering of some vector selects is currently far from perfect.
361 static const TypeConversionCostTblEntry NEONVectorSelectTbl[] = {
362 { ISD::SELECT, MVT::v4i1, MVT::v4i64, 4*4 + 1*2 + 1 },
363 { ISD::SELECT, MVT::v8i1, MVT::v8i64, 50 },
364 { ISD::SELECT, MVT::v16i1, MVT::v16i64, 100 }
365 };
366
367 EVT SelCondTy = TLI->getValueType(DL, CondTy);
368 EVT SelValTy = TLI->getValueType(DL, ValTy);
369 if (SelCondTy.isSimple() && SelValTy.isSimple()) {
370 if (const auto *Entry = ConvertCostTableLookup(NEONVectorSelectTbl, ISD,
371 SelCondTy.getSimpleVT(),
372 SelValTy.getSimpleVT()))
373 return Entry->Cost;
374 }
375
376 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
377 return LT.first;
378 }
379
380 return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, I);
381}
382
383int ARMTTIImpl::getAddressComputationCost(Type *Ty, ScalarEvolution *SE,
384 const SCEV *Ptr) {
385 // Address computations in vectorized code with non-consecutive addresses will
386 // likely result in more instructions compared to scalar code where the
387 // computation can more often be merged into the index mode. The resulting
388 // extra micro-ops can significantly decrease throughput.
389 unsigned NumVectorInstToHideOverhead = 10;
390 int MaxMergeDistance = 64;
391
392 if (Ty->isVectorTy() && SE &&
393 !BaseT::isConstantStridedAccessLessThan(SE, Ptr, MaxMergeDistance + 1))
394 return NumVectorInstToHideOverhead;
395
396 // In many cases the address computation is not merged into the instruction
397 // addressing mode.
398 return 1;
399}
400
401int ARMTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
402 Type *SubTp) {
403 if (Kind == TTI::SK_Broadcast) {
404 static const CostTblEntry NEONDupTbl[] = {
405 // VDUP handles these cases.
406 {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
407 {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
408 {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
409 {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
410 {ISD::VECTOR_SHUFFLE, MVT::v4i16, 1},
411 {ISD::VECTOR_SHUFFLE, MVT::v8i8, 1},
412
413 {ISD::VECTOR_SHUFFLE, MVT::v4i32, 1},
414 {ISD::VECTOR_SHUFFLE, MVT::v4f32, 1},
415 {ISD::VECTOR_SHUFFLE, MVT::v8i16, 1},
416 {ISD::VECTOR_SHUFFLE, MVT::v16i8, 1}};
417
418 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
419
420 if (const auto *Entry = CostTableLookup(NEONDupTbl, ISD::VECTOR_SHUFFLE,
421 LT.second))
422 return LT.first * Entry->Cost;
423
424 return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
425 }
426 if (Kind == TTI::SK_Reverse) {
427 static const CostTblEntry NEONShuffleTbl[] = {
428 // Reverse shuffle cost one instruction if we are shuffling within a
429 // double word (vrev) or two if we shuffle a quad word (vrev, vext).
430 {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
431 {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
432 {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
433 {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
434 {ISD::VECTOR_SHUFFLE, MVT::v4i16, 1},
435 {ISD::VECTOR_SHUFFLE, MVT::v8i8, 1},
436
437 {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2},
438 {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2},
439 {ISD::VECTOR_SHUFFLE, MVT::v8i16, 2},
440 {ISD::VECTOR_SHUFFLE, MVT::v16i8, 2}};
441
442 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
443
444 if (const auto *Entry = CostTableLookup(NEONShuffleTbl, ISD::VECTOR_SHUFFLE,
445 LT.second))
446 return LT.first * Entry->Cost;
447
448 return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
449 }
450 if (Kind == TTI::SK_Select) {
451 static const CostTblEntry NEONSelShuffleTbl[] = {
452 // Select shuffle cost table for ARM. Cost is the number of instructions
453 // required to create the shuffled vector.
454
455 {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
456 {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
457 {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
458 {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
459
460 {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2},
461 {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2},
462 {ISD::VECTOR_SHUFFLE, MVT::v4i16, 2},
463
464 {ISD::VECTOR_SHUFFLE, MVT::v8i16, 16},
465
466 {ISD::VECTOR_SHUFFLE, MVT::v16i8, 32}};
467
468 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
469 if (const auto *Entry = CostTableLookup(NEONSelShuffleTbl,
470 ISD::VECTOR_SHUFFLE, LT.second))
471 return LT.first * Entry->Cost;
472 return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
473 }
474 return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
475}
476
477int ARMTTIImpl::getArithmeticInstrCost(
478 unsigned Opcode, Type *Ty, TTI::OperandValueKind Op1Info,
479 TTI::OperandValueKind Op2Info, TTI::OperandValueProperties Opd1PropInfo,
480 TTI::OperandValueProperties Opd2PropInfo,
481 ArrayRef<const Value *> Args) {
482 int ISDOpcode = TLI->InstructionOpcodeToISD(Opcode);
483 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
484
485 const unsigned FunctionCallDivCost = 20;
486 const unsigned ReciprocalDivCost = 10;
487 static const CostTblEntry CostTbl[] = {
488 // Division.
489 // These costs are somewhat random. Choose a cost of 20 to indicate that
490 // vectorizing devision (added function call) is going to be very expensive.
491 // Double registers types.
492 { ISD::SDIV, MVT::v1i64, 1 * FunctionCallDivCost},
493 { ISD::UDIV, MVT::v1i64, 1 * FunctionCallDivCost},
494 { ISD::SREM, MVT::v1i64, 1 * FunctionCallDivCost},
495 { ISD::UREM, MVT::v1i64, 1 * FunctionCallDivCost},
496 { ISD::SDIV, MVT::v2i32, 2 * FunctionCallDivCost},
497 { ISD::UDIV, MVT::v2i32, 2 * FunctionCallDivCost},
498 { ISD::SREM, MVT::v2i32, 2 * FunctionCallDivCost},
499 { ISD::UREM, MVT::v2i32, 2 * FunctionCallDivCost},
500 { ISD::SDIV, MVT::v4i16, ReciprocalDivCost},
501 { ISD::UDIV, MVT::v4i16, ReciprocalDivCost},
502 { ISD::SREM, MVT::v4i16, 4 * FunctionCallDivCost},
503 { ISD::UREM, MVT::v4i16, 4 * FunctionCallDivCost},
504 { ISD::SDIV, MVT::v8i8, ReciprocalDivCost},
505 { ISD::UDIV, MVT::v8i8, ReciprocalDivCost},
506 { ISD::SREM, MVT::v8i8, 8 * FunctionCallDivCost},
507 { ISD::UREM, MVT::v8i8, 8 * FunctionCallDivCost},
508 // Quad register types.
509 { ISD::SDIV, MVT::v2i64, 2 * FunctionCallDivCost},
510 { ISD::UDIV, MVT::v2i64, 2 * FunctionCallDivCost},
511 { ISD::SREM, MVT::v2i64, 2 * FunctionCallDivCost},
512 { ISD::UREM, MVT::v2i64, 2 * FunctionCallDivCost},
513 { ISD::SDIV, MVT::v4i32, 4 * FunctionCallDivCost},
514 { ISD::UDIV, MVT::v4i32, 4 * FunctionCallDivCost},
515 { ISD::SREM, MVT::v4i32, 4 * FunctionCallDivCost},
516 { ISD::UREM, MVT::v4i32, 4 * FunctionCallDivCost},
517 { ISD::SDIV, MVT::v8i16, 8 * FunctionCallDivCost},
518 { ISD::UDIV, MVT::v8i16, 8 * FunctionCallDivCost},
519 { ISD::SREM, MVT::v8i16, 8 * FunctionCallDivCost},
520 { ISD::UREM, MVT::v8i16, 8 * FunctionCallDivCost},
521 { ISD::SDIV, MVT::v16i8, 16 * FunctionCallDivCost},
522 { ISD::UDIV, MVT::v16i8, 16 * FunctionCallDivCost},
523 { ISD::SREM, MVT::v16i8, 16 * FunctionCallDivCost},
524 { ISD::UREM, MVT::v16i8, 16 * FunctionCallDivCost},
525 // Multiplication.
526 };
527
528 if (ST->hasNEON())
529 if (const auto *Entry = CostTableLookup(CostTbl, ISDOpcode, LT.second))
530 return LT.first * Entry->Cost;
531
532 int Cost = BaseT::getArithmeticInstrCost(Opcode, Ty, Op1Info, Op2Info,
533 Opd1PropInfo, Opd2PropInfo);
534
535 // This is somewhat of a hack. The problem that we are facing is that SROA
536 // creates a sequence of shift, and, or instructions to construct values.
537 // These sequences are recognized by the ISel and have zero-cost. Not so for
538 // the vectorized code. Because we have support for v2i64 but not i64 those
539 // sequences look particularly beneficial to vectorize.
540 // To work around this we increase the cost of v2i64 operations to make them
541 // seem less beneficial.
542 if (LT.second == MVT::v2i64 &&
543 Op2Info == TargetTransformInfo::OK_UniformConstantValue)
544 Cost += 4;
545
546 return Cost;
547}
548
549int ARMTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
550 unsigned AddressSpace, const Instruction *I) {
551 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
552
553 if (Src->isVectorTy() && Alignment != 16 &&
554 Src->getVectorElementType()->isDoubleTy()) {
555 // Unaligned loads/stores are extremely inefficient.
556 // We need 4 uops for vst.1/vld.1 vs 1uop for vldr/vstr.
557 return LT.first * 4;
558 }
559 return LT.first;
560}
561
562int ARMTTIImpl::getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
563 unsigned Factor,
564 ArrayRef<unsigned> Indices,
565 unsigned Alignment,
566 unsigned AddressSpace,
567 bool IsMasked) {
568 assert(Factor >= 2 && "Invalid interleave factor")((Factor >= 2 && "Invalid interleave factor") ? static_cast
<void> (0) : __assert_fail ("Factor >= 2 && \"Invalid interleave factor\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Target/ARM/ARMTargetTransformInfo.cpp"
, 568, __PRETTY_FUNCTION__))
;
569 assert(isa<VectorType>(VecTy) && "Expect a vector type")((isa<VectorType>(VecTy) && "Expect a vector type"
) ? static_cast<void> (0) : __assert_fail ("isa<VectorType>(VecTy) && \"Expect a vector type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Target/ARM/ARMTargetTransformInfo.cpp"
, 569, __PRETTY_FUNCTION__))
;
570
571 // vldN/vstN doesn't support vector types of i64/f64 element.
572 bool EltIs64Bits = DL.getTypeSizeInBits(VecTy->getScalarType()) == 64;
573
574 if (Factor <= TLI->getMaxSupportedInterleaveFactor() && !EltIs64Bits &&
575 !IsMasked) {
576 unsigned NumElts = VecTy->getVectorNumElements();
577 auto *SubVecTy = VectorType::get(VecTy->getScalarType(), NumElts / Factor);
578
579 // vldN/vstN only support legal vector types of size 64 or 128 in bits.
580 // Accesses having vector types that are a multiple of 128 bits can be
581 // matched to more than one vldN/vstN instruction.
582 if (NumElts % Factor == 0 &&
583 TLI->isLegalInterleavedAccessType(SubVecTy, DL))
584 return Factor * TLI->getNumInterleavedAccesses(SubVecTy, DL);
585 }
586
587 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
588 Alignment, AddressSpace, IsMasked);
589}
590
591void ARMTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
592 TTI::UnrollingPreferences &UP) {
593 // Only currently enable these preferences for M-Class cores.
594 if (!ST->isMClass())
1
Taking false branch
595 return BasicTTIImplBase::getUnrollingPreferences(L, SE, UP);
596
597 // Disable loop unrolling for Oz and Os.
598 UP.OptSizeThreshold = 0;
599 UP.PartialOptSizeThreshold = 0;
600 if (L->getHeader()->getParent()->optForSize())
2
Assuming the condition is false
3
Taking false branch
601 return;
602
603 // Only enable on Thumb-2 targets.
604 if (!ST->isThumb2())
4
Assuming the condition is false
5
Taking false branch
605 return;
606
607 SmallVector<BasicBlock*, 4> ExitingBlocks;
608 L->getExitingBlocks(ExitingBlocks);
609 LLVM_DEBUG(dbgs() << "Loop has:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("armtti")) { dbgs() << "Loop has:\n" << "Blocks: "
<< L->getNumBlocks() << "\n" << "Exit blocks: "
<< ExitingBlocks.size() << "\n"; } } while (false
)
610 << "Blocks: " << L->getNumBlocks() << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("armtti")) { dbgs() << "Loop has:\n" << "Blocks: "
<< L->getNumBlocks() << "\n" << "Exit blocks: "
<< ExitingBlocks.size() << "\n"; } } while (false
)
611 << "Exit blocks: " << ExitingBlocks.size() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("armtti")) { dbgs() << "Loop has:\n" << "Blocks: "
<< L->getNumBlocks() << "\n" << "Exit blocks: "
<< ExitingBlocks.size() << "\n"; } } while (false
)
;
612
613 // Only allow another exit other than the latch. This acts as an early exit
614 // as it mirrors the profitability calculation of the runtime unroller.
615 if (ExitingBlocks.size() > 2)
6
Assuming the condition is false
7
Taking false branch
616 return;
617
618 // Limit the CFG of the loop body for targets with a branch predictor.
619 // Allowing 4 blocks permits if-then-else diamonds in the body.
620 if (ST->hasBranchPredictor() && L->getNumBlocks() > 4)
8
Assuming the condition is false
621 return;
622
623 // Scan the loop: don't unroll loops with calls as this could prevent
624 // inlining.
625 unsigned Cost = 0;
626 for (auto *BB : L->getBlocks()) {
9
Assuming '__begin1' is not equal to '__end1'
627 for (auto &I : *BB) {
628 if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
10
Taking false branch
629 ImmutableCallSite CS(&I);
630 if (const Function *F = CS.getCalledFunction()) {
631 if (!isLoweredToCall(F))
632 continue;
633 }
634 return;
635 }
636 SmallVector<const Value*, 4> Operands(I.value_op_begin(),
637 I.value_op_end());
638 Cost += getUserCost(&I, Operands);
11
Calling 'TargetTransformInfoImplCRTPBase::getUserCost'
639 }
640 }
641
642 LLVM_DEBUG(dbgs() << "Cost of loop: " << Cost << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("armtti")) { dbgs() << "Cost of loop: " << Cost <<
"\n"; } } while (false)
;
643
644 UP.Partial = true;
645 UP.Runtime = true;
646 UP.UnrollRemainder = true;
647 UP.DefaultUnrollRuntimeCount = 4;
648 UP.UnrollAndJam = true;
649 UP.UnrollAndJamInnerLoopThreshold = 60;
650
651 // Force unrolling small loops can be very useful because of the branch
652 // taken cost of the backedge.
653 if (Cost < 12)
654 UP.Force = true;
655}

/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Analysis/TargetTransformInfoImpl.h

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

/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/BasicTTIImpl.h

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