Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name 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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/lib/Target/ARM -I /build/llvm-toolchain-snapshot-10~svn374877/lib/Target/ARM -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn374877/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/lib/Target/ARM -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn374877=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-10-15-233810-7101-1 -x c++ /build/llvm-toolchain-snapshot-10~svn374877/lib/Target/ARM/ARMTargetTransformInfo.cpp

/build/llvm-toolchain-snapshot-10~svn374877/lib/Target/ARM/ARMTargetTransformInfo.cpp

1//===- ARMTargetTransformInfo.cpp - ARM specific TTI ----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "ARMTargetTransformInfo.h"
10#include "ARMSubtarget.h"
11#include "MCTargetDesc/ARMAddressingModes.h"
12#include "llvm/ADT/APInt.h"
13#include "llvm/ADT/SmallVector.h"
14#include "llvm/Analysis/LoopInfo.h"
15#include "llvm/CodeGen/CostTable.h"
16#include "llvm/CodeGen/ISDOpcodes.h"
17#include "llvm/CodeGen/ValueTypes.h"
18#include "llvm/IR/BasicBlock.h"
19#include "llvm/IR/CallSite.h"
20#include "llvm/IR/DataLayout.h"
21#include "llvm/IR/DerivedTypes.h"
22#include "llvm/IR/Instruction.h"
23#include "llvm/IR/Instructions.h"
24#include "llvm/IR/IntrinsicInst.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
39static cl::opt<bool> EnableMaskedLoadStores(
40 "enable-arm-maskedldst", cl::Hidden, cl::init(false),
41 cl::desc("Enable the generation of masked loads and stores"));
42
43static cl::opt<bool> DisableLowOverheadLoops(
44 "disable-arm-loloops", cl::Hidden, cl::init(false),
45 cl::desc("Disable the generation of low-overhead loops"));
46
47bool ARMTTIImpl::areInlineCompatible(const Function *Caller,
48 const Function *Callee) const {
49 const TargetMachine &TM = getTLI()->getTargetMachine();
50 const FeatureBitset &CallerBits =
51 TM.getSubtargetImpl(*Caller)->getFeatureBits();
52 const FeatureBitset &CalleeBits =
53 TM.getSubtargetImpl(*Callee)->getFeatureBits();
54
55 // To inline a callee, all features not in the whitelist must match exactly.
56 bool MatchExact = (CallerBits & ~InlineFeatureWhitelist) ==
57 (CalleeBits & ~InlineFeatureWhitelist);
58 // For features in the whitelist, the callee's features must be a subset of
59 // the callers'.
60 bool MatchSubset = ((CallerBits & CalleeBits) & InlineFeatureWhitelist) ==
61 (CalleeBits & InlineFeatureWhitelist);
62 return MatchExact && MatchSubset;
63}
64
65int ARMTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty) {
66 assert(Ty->isIntegerTy())((Ty->isIntegerTy()) ? static_cast<void> (0) : __assert_fail
("Ty->isIntegerTy()", "/build/llvm-toolchain-snapshot-10~svn374877/lib/Target/ARM/ARMTargetTransformInfo.cpp"
, 66, __PRETTY_FUNCTION__))
;
67
68 unsigned Bits = Ty->getPrimitiveSizeInBits();
69 if (Bits == 0 || Imm.getActiveBits() >= 64)
70 return 4;
71
72 int64_t SImmVal = Imm.getSExtValue();
73 uint64_t ZImmVal = Imm.getZExtValue();
74 if (!ST->isThumb()) {
75 if ((SImmVal >= 0 && SImmVal < 65536) ||
76 (ARM_AM::getSOImmVal(ZImmVal) != -1) ||
77 (ARM_AM::getSOImmVal(~ZImmVal) != -1))
78 return 1;
79 return ST->hasV6T2Ops() ? 2 : 3;
80 }
81 if (ST->isThumb2()) {
82 if ((SImmVal >= 0 && SImmVal < 65536) ||
83 (ARM_AM::getT2SOImmVal(ZImmVal) != -1) ||
84 (ARM_AM::getT2SOImmVal(~ZImmVal) != -1))
85 return 1;
86 return ST->hasV6T2Ops() ? 2 : 3;
87 }
88 // Thumb1, any i8 imm cost 1.
89 if (Bits == 8 || (SImmVal >= 0 && SImmVal < 256))
90 return 1;
91 if ((~SImmVal < 256) || ARM_AM::isThumbImmShiftedVal(ZImmVal))
92 return 2;
93 // Load from constantpool.
94 return 3;
95}
96
97// Constants smaller than 256 fit in the immediate field of
98// Thumb1 instructions so we return a zero cost and 1 otherwise.
99int ARMTTIImpl::getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx,
100 const APInt &Imm, Type *Ty) {
101 if (Imm.isNonNegative() && Imm.getLimitedValue() < 256)
102 return 0;
103
104 return 1;
105}
106
107int ARMTTIImpl::getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
108 Type *Ty) {
109 // Division by a constant can be turned into multiplication, but only if we
110 // know it's constant. So it's not so much that the immediate is cheap (it's
111 // not), but that the alternative is worse.
112 // FIXME: this is probably unneeded with GlobalISel.
113 if ((Opcode == Instruction::SDiv || Opcode == Instruction::UDiv ||
114 Opcode == Instruction::SRem || Opcode == Instruction::URem) &&
115 Idx == 1)
116 return 0;
117
118 if (Opcode == Instruction::And) {
119 // UXTB/UXTH
120 if (Imm == 255 || Imm == 65535)
121 return 0;
122 // Conversion to BIC is free, and means we can use ~Imm instead.
123 return std::min(getIntImmCost(Imm, Ty), getIntImmCost(~Imm, Ty));
124 }
125
126 if (Opcode == Instruction::Add)
127 // Conversion to SUB is free, and means we can use -Imm instead.
128 return std::min(getIntImmCost(Imm, Ty), getIntImmCost(-Imm, Ty));
129
130 if (Opcode == Instruction::ICmp && Imm.isNegative() &&
131 Ty->getIntegerBitWidth() == 32) {
132 int64_t NegImm = -Imm.getSExtValue();
133 if (ST->isThumb2() && NegImm < 1<<12)
134 // icmp X, #-C -> cmn X, #C
135 return 0;
136 if (ST->isThumb() && NegImm < 1<<8)
137 // icmp X, #-C -> adds X, #C
138 return 0;
139 }
140
141 // xor a, -1 can always be folded to MVN
142 if (Opcode == Instruction::Xor && Imm.isAllOnesValue())
143 return 0;
144
145 return getIntImmCost(Imm, Ty);
146}
147
148int ARMTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
149 const Instruction *I) {
150 int ISD = TLI->InstructionOpcodeToISD(Opcode);
151 assert(ISD && "Invalid opcode")((ISD && "Invalid opcode") ? static_cast<void> (
0) : __assert_fail ("ISD && \"Invalid opcode\"", "/build/llvm-toolchain-snapshot-10~svn374877/lib/Target/ARM/ARMTargetTransformInfo.cpp"
, 151, __PRETTY_FUNCTION__))
;
152
153 // Single to/from double precision conversions.
154 static const CostTblEntry NEONFltDblTbl[] = {
155 // Vector fptrunc/fpext conversions.
156 { ISD::FP_ROUND, MVT::v2f64, 2 },
157 { ISD::FP_EXTEND, MVT::v2f32, 2 },
158 { ISD::FP_EXTEND, MVT::v4f32, 4 }
159 };
160
161 if (Src->isVectorTy() && ST->hasNEON() && (ISD == ISD::FP_ROUND ||
162 ISD == ISD::FP_EXTEND)) {
163 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
164 if (const auto *Entry = CostTableLookup(NEONFltDblTbl, ISD, LT.second))
165 return LT.first * Entry->Cost;
166 }
167
168 EVT SrcTy = TLI->getValueType(DL, Src);
169 EVT DstTy = TLI->getValueType(DL, Dst);
170
171 if (!SrcTy.isSimple() || !DstTy.isSimple())
172 return BaseT::getCastInstrCost(Opcode, Dst, Src);
173
174 // The extend of a load is free
175 if (I && isa<LoadInst>(I->getOperand(0))) {
176 static const TypeConversionCostTblEntry LoadConversionTbl[] = {
177 {ISD::SIGN_EXTEND, MVT::i32, MVT::i16, 0},
178 {ISD::ZERO_EXTEND, MVT::i32, MVT::i16, 0},
179 {ISD::SIGN_EXTEND, MVT::i32, MVT::i8, 0},
180 {ISD::ZERO_EXTEND, MVT::i32, MVT::i8, 0},
181 {ISD::SIGN_EXTEND, MVT::i16, MVT::i8, 0},
182 {ISD::ZERO_EXTEND, MVT::i16, MVT::i8, 0},
183 {ISD::SIGN_EXTEND, MVT::i64, MVT::i32, 1},
184 {ISD::ZERO_EXTEND, MVT::i64, MVT::i32, 1},
185 {ISD::SIGN_EXTEND, MVT::i64, MVT::i16, 1},
186 {ISD::ZERO_EXTEND, MVT::i64, MVT::i16, 1},
187 {ISD::SIGN_EXTEND, MVT::i64, MVT::i8, 1},
188 {ISD::ZERO_EXTEND, MVT::i64, MVT::i8, 1},
189 };
190 if (const auto *Entry = ConvertCostTableLookup(
191 LoadConversionTbl, ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
192 return Entry->Cost;
193
194 static const TypeConversionCostTblEntry MVELoadConversionTbl[] = {
195 {ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 0},
196 {ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 0},
197 {ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 0},
198 {ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 0},
199 {ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 0},
200 {ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 0},
201 };
202 if (SrcTy.isVector() && ST->hasMVEIntegerOps()) {
203 if (const auto *Entry =
204 ConvertCostTableLookup(MVELoadConversionTbl, ISD,
205 DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
206 return Entry->Cost;
207 }
208 }
209
210 // Some arithmetic, load and store operations have specific instructions
211 // to cast up/down their types automatically at no extra cost.
212 // TODO: Get these tables to know at least what the related operations are.
213 static const TypeConversionCostTblEntry NEONVectorConversionTbl[] = {
214 { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 0 },
215 { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 0 },
216 { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i32, 1 },
217 { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i32, 1 },
218 { ISD::TRUNCATE, MVT::v4i32, MVT::v4i64, 0 },
219 { ISD::TRUNCATE, MVT::v4i16, MVT::v4i32, 1 },
220
221 // The number of vmovl instructions for the extension.
222 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
223 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
224 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i8, 3 },
225 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i8, 3 },
226 { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i8, 7 },
227 { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i8, 7 },
228 { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i16, 6 },
229 { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i16, 6 },
230 { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
231 { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
232
233 // Operations that we legalize using splitting.
234 { ISD::TRUNCATE, MVT::v16i8, MVT::v16i32, 6 },
235 { ISD::TRUNCATE, MVT::v8i8, MVT::v8i32, 3 },
236
237 // Vector float <-> i32 conversions.
238 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
239 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
240
241 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i8, 3 },
242 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i8, 3 },
243 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i16, 2 },
244 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i16, 2 },
245 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 },
246 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 },
247 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i1, 3 },
248 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i1, 3 },
249 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i8, 3 },
250 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i8, 3 },
251 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 },
252 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 },
253 { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 },
254 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 },
255 { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i32, 2 },
256 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i32, 2 },
257 { ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i16, 8 },
258 { ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i16, 8 },
259 { ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i32, 4 },
260 { ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i32, 4 },
261
262 { ISD::FP_TO_SINT, MVT::v4i32, MVT::v4f32, 1 },
263 { ISD::FP_TO_UINT, MVT::v4i32, MVT::v4f32, 1 },
264 { ISD::FP_TO_SINT, MVT::v4i8, MVT::v4f32, 3 },
265 { ISD::FP_TO_UINT, MVT::v4i8, MVT::v4f32, 3 },
266 { ISD::FP_TO_SINT, MVT::v4i16, MVT::v4f32, 2 },
267 { ISD::FP_TO_UINT, MVT::v4i16, MVT::v4f32, 2 },
268
269 // Vector double <-> i32 conversions.
270 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
271 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
272
273 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i8, 4 },
274 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i8, 4 },
275 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i16, 3 },
276 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i16, 3 },
277 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
278 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
279
280 { ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f64, 2 },
281 { ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f64, 2 },
282 { ISD::FP_TO_SINT, MVT::v8i16, MVT::v8f32, 4 },
283 { ISD::FP_TO_UINT, MVT::v8i16, MVT::v8f32, 4 },
284 { ISD::FP_TO_SINT, MVT::v16i16, MVT::v16f32, 8 },
285 { ISD::FP_TO_UINT, MVT::v16i16, MVT::v16f32, 8 }
286 };
287
288 if (SrcTy.isVector() && ST->hasNEON()) {
289 if (const auto *Entry = ConvertCostTableLookup(NEONVectorConversionTbl, ISD,
290 DstTy.getSimpleVT(),
291 SrcTy.getSimpleVT()))
292 return Entry->Cost;
293 }
294
295 // Scalar float to integer conversions.
296 static const TypeConversionCostTblEntry NEONFloatConversionTbl[] = {
297 { ISD::FP_TO_SINT, MVT::i1, MVT::f32, 2 },
298 { ISD::FP_TO_UINT, MVT::i1, MVT::f32, 2 },
299 { ISD::FP_TO_SINT, MVT::i1, MVT::f64, 2 },
300 { ISD::FP_TO_UINT, MVT::i1, MVT::f64, 2 },
301 { ISD::FP_TO_SINT, MVT::i8, MVT::f32, 2 },
302 { ISD::FP_TO_UINT, MVT::i8, MVT::f32, 2 },
303 { ISD::FP_TO_SINT, MVT::i8, MVT::f64, 2 },
304 { ISD::FP_TO_UINT, MVT::i8, MVT::f64, 2 },
305 { ISD::FP_TO_SINT, MVT::i16, MVT::f32, 2 },
306 { ISD::FP_TO_UINT, MVT::i16, MVT::f32, 2 },
307 { ISD::FP_TO_SINT, MVT::i16, MVT::f64, 2 },
308 { ISD::FP_TO_UINT, MVT::i16, MVT::f64, 2 },
309 { ISD::FP_TO_SINT, MVT::i32, MVT::f32, 2 },
310 { ISD::FP_TO_UINT, MVT::i32, MVT::f32, 2 },
311 { ISD::FP_TO_SINT, MVT::i32, MVT::f64, 2 },
312 { ISD::FP_TO_UINT, MVT::i32, MVT::f64, 2 },
313 { ISD::FP_TO_SINT, MVT::i64, MVT::f32, 10 },
314 { ISD::FP_TO_UINT, MVT::i64, MVT::f32, 10 },
315 { ISD::FP_TO_SINT, MVT::i64, MVT::f64, 10 },
316 { ISD::FP_TO_UINT, MVT::i64, MVT::f64, 10 }
317 };
318 if (SrcTy.isFloatingPoint() && ST->hasNEON()) {
319 if (const auto *Entry = ConvertCostTableLookup(NEONFloatConversionTbl, ISD,
320 DstTy.getSimpleVT(),
321 SrcTy.getSimpleVT()))
322 return Entry->Cost;
323 }
324
325 // Scalar integer to float conversions.
326 static const TypeConversionCostTblEntry NEONIntegerConversionTbl[] = {
327 { ISD::SINT_TO_FP, MVT::f32, MVT::i1, 2 },
328 { ISD::UINT_TO_FP, MVT::f32, MVT::i1, 2 },
329 { ISD::SINT_TO_FP, MVT::f64, MVT::i1, 2 },
330 { ISD::UINT_TO_FP, MVT::f64, MVT::i1, 2 },
331 { ISD::SINT_TO_FP, MVT::f32, MVT::i8, 2 },
332 { ISD::UINT_TO_FP, MVT::f32, MVT::i8, 2 },
333 { ISD::SINT_TO_FP, MVT::f64, MVT::i8, 2 },
334 { ISD::UINT_TO_FP, MVT::f64, MVT::i8, 2 },
335 { ISD::SINT_TO_FP, MVT::f32, MVT::i16, 2 },
336 { ISD::UINT_TO_FP, MVT::f32, MVT::i16, 2 },
337 { ISD::SINT_TO_FP, MVT::f64, MVT::i16, 2 },
338 { ISD::UINT_TO_FP, MVT::f64, MVT::i16, 2 },
339 { ISD::SINT_TO_FP, MVT::f32, MVT::i32, 2 },
340 { ISD::UINT_TO_FP, MVT::f32, MVT::i32, 2 },
341 { ISD::SINT_TO_FP, MVT::f64, MVT::i32, 2 },
342 { ISD::UINT_TO_FP, MVT::f64, MVT::i32, 2 },
343 { ISD::SINT_TO_FP, MVT::f32, MVT::i64, 10 },
344 { ISD::UINT_TO_FP, MVT::f32, MVT::i64, 10 },
345 { ISD::SINT_TO_FP, MVT::f64, MVT::i64, 10 },
346 { ISD::UINT_TO_FP, MVT::f64, MVT::i64, 10 }
347 };
348
349 if (SrcTy.isInteger() && ST->hasNEON()) {
350 if (const auto *Entry = ConvertCostTableLookup(NEONIntegerConversionTbl,
351 ISD, DstTy.getSimpleVT(),
352 SrcTy.getSimpleVT()))
353 return Entry->Cost;
354 }
355
356 // MVE extend costs, taken from codegen tests. i8->i16 or i16->i32 is one
357 // instruction, i8->i32 is two. i64 zexts are an VAND with a constant, sext
358 // are linearised so take more.
359 static const TypeConversionCostTblEntry MVEVectorConversionTbl[] = {
360 { ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
361 { ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
362 { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 2 },
363 { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 2 },
364 { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i8, 10 },
365 { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i8, 2 },
366 { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
367 { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
368 { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i16, 10 },
369 { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i16, 2 },
370 { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i32, 8 },
371 { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i32, 2 },
372 };
373
374 if (SrcTy.isVector() && ST->hasMVEIntegerOps()) {
375 if (const auto *Entry = ConvertCostTableLookup(MVEVectorConversionTbl,
376 ISD, DstTy.getSimpleVT(),
377 SrcTy.getSimpleVT()))
378 return Entry->Cost * ST->getMVEVectorCostFactor();
379 }
380
381 // Scalar integer conversion costs.
382 static const TypeConversionCostTblEntry ARMIntegerConversionTbl[] = {
383 // i16 -> i64 requires two dependent operations.
384 { ISD::SIGN_EXTEND, MVT::i64, MVT::i16, 2 },
385
386 // Truncates on i64 are assumed to be free.
387 { ISD::TRUNCATE, MVT::i32, MVT::i64, 0 },
388 { ISD::TRUNCATE, MVT::i16, MVT::i64, 0 },
389 { ISD::TRUNCATE, MVT::i8, MVT::i64, 0 },
390 { ISD::TRUNCATE, MVT::i1, MVT::i64, 0 }
391 };
392
393 if (SrcTy.isInteger()) {
394 if (const auto *Entry = ConvertCostTableLookup(ARMIntegerConversionTbl, ISD,
395 DstTy.getSimpleVT(),
396 SrcTy.getSimpleVT()))
397 return Entry->Cost;
398 }
399
400 int BaseCost = ST->hasMVEIntegerOps() && Src->isVectorTy()
401 ? ST->getMVEVectorCostFactor()
402 : 1;
403 return BaseCost * BaseT::getCastInstrCost(Opcode, Dst, Src);
404}
405
406int ARMTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy,
407 unsigned Index) {
408 // Penalize inserting into an D-subregister. We end up with a three times
409 // lower estimated throughput on swift.
410 if (ST->hasSlowLoadDSubregister() && Opcode == Instruction::InsertElement &&
411 ValTy->isVectorTy() && ValTy->getScalarSizeInBits() <= 32)
412 return 3;
413
414 if (ST->hasNEON() && (Opcode == Instruction::InsertElement ||
415 Opcode == Instruction::ExtractElement)) {
416 // Cross-class copies are expensive on many microarchitectures,
417 // so assume they are expensive by default.
418 if (ValTy->getVectorElementType()->isIntegerTy())
419 return 3;
420
421 // Even if it's not a cross class copy, this likely leads to mixing
422 // of NEON and VFP code and should be therefore penalized.
423 if (ValTy->isVectorTy() &&
424 ValTy->getScalarSizeInBits() <= 32)
425 return std::max(BaseT::getVectorInstrCost(Opcode, ValTy, Index), 2U);
426 }
427
428 if (ST->hasMVEIntegerOps() && (Opcode == Instruction::InsertElement ||
429 Opcode == Instruction::ExtractElement)) {
430 // We say MVE moves costs at least the MVEVectorCostFactor, even though
431 // they are scalar instructions. This helps prevent mixing scalar and
432 // vector, to prevent vectorising where we end up just scalarising the
433 // result anyway.
434 return std::max(BaseT::getVectorInstrCost(Opcode, ValTy, Index),
435 ST->getMVEVectorCostFactor()) *
436 ValTy->getVectorNumElements() / 2;
437 }
438
439 return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
440}
441
442int ARMTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
443 const Instruction *I) {
444 int ISD = TLI->InstructionOpcodeToISD(Opcode);
445 // On NEON a vector select gets lowered to vbsl.
446 if (ST->hasNEON() && ValTy->isVectorTy() && ISD == ISD::SELECT) {
447 // Lowering of some vector selects is currently far from perfect.
448 static const TypeConversionCostTblEntry NEONVectorSelectTbl[] = {
449 { ISD::SELECT, MVT::v4i1, MVT::v4i64, 4*4 + 1*2 + 1 },
450 { ISD::SELECT, MVT::v8i1, MVT::v8i64, 50 },
451 { ISD::SELECT, MVT::v16i1, MVT::v16i64, 100 }
452 };
453
454 EVT SelCondTy = TLI->getValueType(DL, CondTy);
455 EVT SelValTy = TLI->getValueType(DL, ValTy);
456 if (SelCondTy.isSimple() && SelValTy.isSimple()) {
457 if (const auto *Entry = ConvertCostTableLookup(NEONVectorSelectTbl, ISD,
458 SelCondTy.getSimpleVT(),
459 SelValTy.getSimpleVT()))
460 return Entry->Cost;
461 }
462
463 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
464 return LT.first;
465 }
466
467 int BaseCost = ST->hasMVEIntegerOps() && ValTy->isVectorTy()
468 ? ST->getMVEVectorCostFactor()
469 : 1;
470 return BaseCost * BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, I);
471}
472
473int ARMTTIImpl::getAddressComputationCost(Type *Ty, ScalarEvolution *SE,
474 const SCEV *Ptr) {
475 // Address computations in vectorized code with non-consecutive addresses will
476 // likely result in more instructions compared to scalar code where the
477 // computation can more often be merged into the index mode. The resulting
478 // extra micro-ops can significantly decrease throughput.
479 unsigned NumVectorInstToHideOverhead = 10;
480 int MaxMergeDistance = 64;
481
482 if (ST->hasNEON()) {
483 if (Ty->isVectorTy() && SE &&
484 !BaseT::isConstantStridedAccessLessThan(SE, Ptr, MaxMergeDistance + 1))
485 return NumVectorInstToHideOverhead;
486
487 // In many cases the address computation is not merged into the instruction
488 // addressing mode.
489 return 1;
490 }
491 return BaseT::getAddressComputationCost(Ty, SE, Ptr);
492}
493
494bool ARMTTIImpl::isLegalMaskedLoad(Type *DataTy, MaybeAlign Alignment) {
495 if (!EnableMaskedLoadStores || !ST->hasMVEIntegerOps())
496 return false;
497
498 if (DataTy->isVectorTy()) {
499 // We don't yet support narrowing or widening masked loads/stores. Expand
500 // them for the moment.
501 unsigned VecWidth = DataTy->getPrimitiveSizeInBits();
502 if (VecWidth != 128)
503 return false;
504 }
505
506 unsigned EltWidth = DataTy->getScalarSizeInBits();
507 return EltWidth == 32 || EltWidth == 16 || EltWidth == 8;
508}
509
510int ARMTTIImpl::getMemcpyCost(const Instruction *I) {
511 const MemCpyInst *MI = dyn_cast<MemCpyInst>(I);
512 assert(MI && "MemcpyInst expected")((MI && "MemcpyInst expected") ? static_cast<void>
(0) : __assert_fail ("MI && \"MemcpyInst expected\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Target/ARM/ARMTargetTransformInfo.cpp"
, 512, __PRETTY_FUNCTION__))
;
513 ConstantInt *C = dyn_cast<ConstantInt>(MI->getLength());
514
515 // To model the cost of a library call, we assume 1 for the call, and
516 // 3 for the argument setup.
517 const unsigned LibCallCost = 4;
518
519 // If 'size' is not a constant, a library call will be generated.
520 if (!C)
521 return LibCallCost;
522
523 const unsigned Size = C->getValue().getZExtValue();
524 const unsigned DstAlign = MI->getDestAlignment();
525 const unsigned SrcAlign = MI->getSourceAlignment();
526 const Function *F = I->getParent()->getParent();
527 const unsigned Limit = TLI->getMaxStoresPerMemmove(F->hasMinSize());
528 std::vector<EVT> MemOps;
529
530 // MemOps will be poplulated with a list of data types that needs to be
531 // loaded and stored. That's why we multiply the number of elements by 2 to
532 // get the cost for this memcpy.
533 if (getTLI()->findOptimalMemOpLowering(
534 MemOps, Limit, Size, DstAlign, SrcAlign, false /*IsMemset*/,
535 false /*ZeroMemset*/, false /*MemcpyStrSrc*/, false /*AllowOverlap*/,
536 MI->getDestAddressSpace(), MI->getSourceAddressSpace(),
537 F->getAttributes()))
538 return MemOps.size() * 2;
539
540 // If we can't find an optimal memop lowering, return the default cost
541 return LibCallCost;
542}
543
544int ARMTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
545 Type *SubTp) {
546 if (ST->hasNEON()) {
547 if (Kind == TTI::SK_Broadcast) {
548 static const CostTblEntry NEONDupTbl[] = {
549 // VDUP handles these cases.
550 {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
551 {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
552 {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
553 {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
554 {ISD::VECTOR_SHUFFLE, MVT::v4i16, 1},
555 {ISD::VECTOR_SHUFFLE, MVT::v8i8, 1},
556
557 {ISD::VECTOR_SHUFFLE, MVT::v4i32, 1},
558 {ISD::VECTOR_SHUFFLE, MVT::v4f32, 1},
559 {ISD::VECTOR_SHUFFLE, MVT::v8i16, 1},
560 {ISD::VECTOR_SHUFFLE, MVT::v16i8, 1}};
561
562 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
563
564 if (const auto *Entry =
565 CostTableLookup(NEONDupTbl, ISD::VECTOR_SHUFFLE, LT.second))
566 return LT.first * Entry->Cost;
567 }
568 if (Kind == TTI::SK_Reverse) {
569 static const CostTblEntry NEONShuffleTbl[] = {
570 // Reverse shuffle cost one instruction if we are shuffling within a
571 // double word (vrev) or two if we shuffle a quad word (vrev, vext).
572 {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
573 {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
574 {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
575 {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
576 {ISD::VECTOR_SHUFFLE, MVT::v4i16, 1},
577 {ISD::VECTOR_SHUFFLE, MVT::v8i8, 1},
578
579 {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2},
580 {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2},
581 {ISD::VECTOR_SHUFFLE, MVT::v8i16, 2},
582 {ISD::VECTOR_SHUFFLE, MVT::v16i8, 2}};
583
584 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
585
586 if (const auto *Entry =
587 CostTableLookup(NEONShuffleTbl, ISD::VECTOR_SHUFFLE, LT.second))
588 return LT.first * Entry->Cost;
589 }
590 if (Kind == TTI::SK_Select) {
591 static const CostTblEntry NEONSelShuffleTbl[] = {
592 // Select shuffle cost table for ARM. Cost is the number of
593 // instructions
594 // required to create the shuffled vector.
595
596 {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
597 {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
598 {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
599 {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
600
601 {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2},
602 {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2},
603 {ISD::VECTOR_SHUFFLE, MVT::v4i16, 2},
604
605 {ISD::VECTOR_SHUFFLE, MVT::v8i16, 16},
606
607 {ISD::VECTOR_SHUFFLE, MVT::v16i8, 32}};
608
609 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
610 if (const auto *Entry = CostTableLookup(NEONSelShuffleTbl,
611 ISD::VECTOR_SHUFFLE, LT.second))
612 return LT.first * Entry->Cost;
613 }
614 }
615 if (ST->hasMVEIntegerOps()) {
616 if (Kind == TTI::SK_Broadcast) {
617 static const CostTblEntry MVEDupTbl[] = {
618 // VDUP handles these cases.
619 {ISD::VECTOR_SHUFFLE, MVT::v4i32, 1},
620 {ISD::VECTOR_SHUFFLE, MVT::v8i16, 1},
621 {ISD::VECTOR_SHUFFLE, MVT::v16i8, 1},
622 {ISD::VECTOR_SHUFFLE, MVT::v4f32, 1},
623 {ISD::VECTOR_SHUFFLE, MVT::v8f16, 1}};
624
625 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
626
627 if (const auto *Entry = CostTableLookup(MVEDupTbl, ISD::VECTOR_SHUFFLE,
628 LT.second))
629 return LT.first * Entry->Cost * ST->getMVEVectorCostFactor();
630 }
631 }
632 int BaseCost = ST->hasMVEIntegerOps() && Tp->isVectorTy()
633 ? ST->getMVEVectorCostFactor()
634 : 1;
635 return BaseCost * BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
636}
637
638int ARMTTIImpl::getArithmeticInstrCost(
639 unsigned Opcode, Type *Ty, TTI::OperandValueKind Op1Info,
640 TTI::OperandValueKind Op2Info, TTI::OperandValueProperties Opd1PropInfo,
641 TTI::OperandValueProperties Opd2PropInfo,
642 ArrayRef<const Value *> Args) {
643 int ISDOpcode = TLI->InstructionOpcodeToISD(Opcode);
644 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
645
646 const unsigned FunctionCallDivCost = 20;
647 const unsigned ReciprocalDivCost = 10;
648 static const CostTblEntry CostTbl[] = {
649 // Division.
650 // These costs are somewhat random. Choose a cost of 20 to indicate that
651 // vectorizing devision (added function call) is going to be very expensive.
652 // Double registers types.
653 { ISD::SDIV, MVT::v1i64, 1 * FunctionCallDivCost},
654 { ISD::UDIV, MVT::v1i64, 1 * FunctionCallDivCost},
655 { ISD::SREM, MVT::v1i64, 1 * FunctionCallDivCost},
656 { ISD::UREM, MVT::v1i64, 1 * FunctionCallDivCost},
657 { ISD::SDIV, MVT::v2i32, 2 * FunctionCallDivCost},
658 { ISD::UDIV, MVT::v2i32, 2 * FunctionCallDivCost},
659 { ISD::SREM, MVT::v2i32, 2 * FunctionCallDivCost},
660 { ISD::UREM, MVT::v2i32, 2 * FunctionCallDivCost},
661 { ISD::SDIV, MVT::v4i16, ReciprocalDivCost},
662 { ISD::UDIV, MVT::v4i16, ReciprocalDivCost},
663 { ISD::SREM, MVT::v4i16, 4 * FunctionCallDivCost},
664 { ISD::UREM, MVT::v4i16, 4 * FunctionCallDivCost},
665 { ISD::SDIV, MVT::v8i8, ReciprocalDivCost},
666 { ISD::UDIV, MVT::v8i8, ReciprocalDivCost},
667 { ISD::SREM, MVT::v8i8, 8 * FunctionCallDivCost},
668 { ISD::UREM, MVT::v8i8, 8 * FunctionCallDivCost},
669 // Quad register types.
670 { ISD::SDIV, MVT::v2i64, 2 * FunctionCallDivCost},
671 { ISD::UDIV, MVT::v2i64, 2 * FunctionCallDivCost},
672 { ISD::SREM, MVT::v2i64, 2 * FunctionCallDivCost},
673 { ISD::UREM, MVT::v2i64, 2 * FunctionCallDivCost},
674 { ISD::SDIV, MVT::v4i32, 4 * FunctionCallDivCost},
675 { ISD::UDIV, MVT::v4i32, 4 * FunctionCallDivCost},
676 { ISD::SREM, MVT::v4i32, 4 * FunctionCallDivCost},
677 { ISD::UREM, MVT::v4i32, 4 * FunctionCallDivCost},
678 { ISD::SDIV, MVT::v8i16, 8 * FunctionCallDivCost},
679 { ISD::UDIV, MVT::v8i16, 8 * FunctionCallDivCost},
680 { ISD::SREM, MVT::v8i16, 8 * FunctionCallDivCost},
681 { ISD::UREM, MVT::v8i16, 8 * FunctionCallDivCost},
682 { ISD::SDIV, MVT::v16i8, 16 * FunctionCallDivCost},
683 { ISD::UDIV, MVT::v16i8, 16 * FunctionCallDivCost},
684 { ISD::SREM, MVT::v16i8, 16 * FunctionCallDivCost},
685 { ISD::UREM, MVT::v16i8, 16 * FunctionCallDivCost},
686 // Multiplication.
687 };
688
689 if (ST->hasNEON()) {
690 if (const auto *Entry = CostTableLookup(CostTbl, ISDOpcode, LT.second))
691 return LT.first * Entry->Cost;
692
693 int Cost = BaseT::getArithmeticInstrCost(Opcode, Ty, Op1Info, Op2Info,
694 Opd1PropInfo, Opd2PropInfo);
695
696 // This is somewhat of a hack. The problem that we are facing is that SROA
697 // creates a sequence of shift, and, or instructions to construct values.
698 // These sequences are recognized by the ISel and have zero-cost. Not so for
699 // the vectorized code. Because we have support for v2i64 but not i64 those
700 // sequences look particularly beneficial to vectorize.
701 // To work around this we increase the cost of v2i64 operations to make them
702 // seem less beneficial.
703 if (LT.second == MVT::v2i64 &&
704 Op2Info == TargetTransformInfo::OK_UniformConstantValue)
705 Cost += 4;
706
707 return Cost;
708 }
709
710 int BaseCost = ST->hasMVEIntegerOps() && Ty->isVectorTy()
711 ? ST->getMVEVectorCostFactor()
712 : 1;
713
714 // The rest of this mostly follows what is done in BaseT::getArithmeticInstrCost,
715 // without treating floats as more expensive that scalars or increasing the
716 // costs for custom operations. The results is also multiplied by the
717 // MVEVectorCostFactor where appropriate.
718 if (TLI->isOperationLegalOrCustomOrPromote(ISDOpcode, LT.second))
719 return LT.first * BaseCost;
720
721 // Else this is expand, assume that we need to scalarize this op.
722 if (Ty->isVectorTy()) {
723 unsigned Num = Ty->getVectorNumElements();
724 unsigned Cost = getArithmeticInstrCost(Opcode, Ty->getScalarType());
725 // Return the cost of multiple scalar invocation plus the cost of
726 // inserting and extracting the values.
727 return BaseT::getScalarizationOverhead(Ty, Args) + Num * Cost;
728 }
729
730 return BaseCost;
731}
732
733int ARMTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
734 unsigned AddressSpace, const Instruction *I) {
735 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
736
737 if (ST->hasNEON() && Src->isVectorTy() && Alignment != 16 &&
738 Src->getVectorElementType()->isDoubleTy()) {
739 // Unaligned loads/stores are extremely inefficient.
740 // We need 4 uops for vst.1/vld.1 vs 1uop for vldr/vstr.
741 return LT.first * 4;
742 }
743 int BaseCost = ST->hasMVEIntegerOps() && Src->isVectorTy()
744 ? ST->getMVEVectorCostFactor()
745 : 1;
746 return BaseCost * LT.first;
747}
748
749int ARMTTIImpl::getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
750 unsigned Factor,
751 ArrayRef<unsigned> Indices,
752 unsigned Alignment,
753 unsigned AddressSpace,
754 bool UseMaskForCond,
755 bool UseMaskForGaps) {
756 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-10~svn374877/lib/Target/ARM/ARMTargetTransformInfo.cpp"
, 756, __PRETTY_FUNCTION__))
;
757 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-10~svn374877/lib/Target/ARM/ARMTargetTransformInfo.cpp"
, 757, __PRETTY_FUNCTION__))
;
758
759 // vldN/vstN doesn't support vector types of i64/f64 element.
760 bool EltIs64Bits = DL.getTypeSizeInBits(VecTy->getScalarType()) == 64;
761
762 if (Factor <= TLI->getMaxSupportedInterleaveFactor() && !EltIs64Bits &&
763 !UseMaskForCond && !UseMaskForGaps) {
764 unsigned NumElts = VecTy->getVectorNumElements();
765 auto *SubVecTy = VectorType::get(VecTy->getScalarType(), NumElts / Factor);
766
767 // vldN/vstN only support legal vector types of size 64 or 128 in bits.
768 // Accesses having vector types that are a multiple of 128 bits can be
769 // matched to more than one vldN/vstN instruction.
770 if (NumElts % Factor == 0 &&
771 TLI->isLegalInterleavedAccessType(SubVecTy, DL))
772 return Factor * TLI->getNumInterleavedAccesses(SubVecTy, DL);
773 }
774
775 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
776 Alignment, AddressSpace,
777 UseMaskForCond, UseMaskForGaps);
778}
779
780bool ARMTTIImpl::isLoweredToCall(const Function *F) {
781 if (!F->isIntrinsic())
782 BaseT::isLoweredToCall(F);
783
784 // Assume all Arm-specific intrinsics map to an instruction.
785 if (F->getName().startswith("llvm.arm"))
786 return false;
787
788 switch (F->getIntrinsicID()) {
789 default: break;
790 case Intrinsic::powi:
791 case Intrinsic::sin:
792 case Intrinsic::cos:
793 case Intrinsic::pow:
794 case Intrinsic::log:
795 case Intrinsic::log10:
796 case Intrinsic::log2:
797 case Intrinsic::exp:
798 case Intrinsic::exp2:
799 return true;
800 case Intrinsic::sqrt:
801 case Intrinsic::fabs:
802 case Intrinsic::copysign:
803 case Intrinsic::floor:
804 case Intrinsic::ceil:
805 case Intrinsic::trunc:
806 case Intrinsic::rint:
807 case Intrinsic::nearbyint:
808 case Intrinsic::round:
809 case Intrinsic::canonicalize:
810 case Intrinsic::lround:
811 case Intrinsic::llround:
812 case Intrinsic::lrint:
813 case Intrinsic::llrint:
814 if (F->getReturnType()->isDoubleTy() && !ST->hasFP64())
815 return true;
816 if (F->getReturnType()->isHalfTy() && !ST->hasFullFP16())
817 return true;
818 // Some operations can be handled by vector instructions and assume
819 // unsupported vectors will be expanded into supported scalar ones.
820 // TODO Handle scalar operations properly.
821 return !ST->hasFPARMv8Base() && !ST->hasVFP2Base();
822 case Intrinsic::masked_store:
823 case Intrinsic::masked_load:
824 case Intrinsic::masked_gather:
825 case Intrinsic::masked_scatter:
826 return !ST->hasMVEIntegerOps();
827 case Intrinsic::sadd_with_overflow:
828 case Intrinsic::uadd_with_overflow:
829 case Intrinsic::ssub_with_overflow:
830 case Intrinsic::usub_with_overflow:
831 case Intrinsic::sadd_sat:
832 case Intrinsic::uadd_sat:
833 case Intrinsic::ssub_sat:
834 case Intrinsic::usub_sat:
835 return false;
836 }
837
838 return BaseT::isLoweredToCall(F);
839}
840
841bool ARMTTIImpl::isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
842 AssumptionCache &AC,
843 TargetLibraryInfo *LibInfo,
844 HardwareLoopInfo &HWLoopInfo) {
845 // Low-overhead branches are only supported in the 'low-overhead branch'
846 // extension of v8.1-m.
847 if (!ST->hasLOB() || DisableLowOverheadLoops)
848 return false;
849
850 if (!SE.hasLoopInvariantBackedgeTakenCount(L))
851 return false;
852
853 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
854 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
855 return false;
856
857 const SCEV *TripCountSCEV =
858 SE.getAddExpr(BackedgeTakenCount,
859 SE.getOne(BackedgeTakenCount->getType()));
860
861 // We need to store the trip count in LR, a 32-bit register.
862 if (SE.getUnsignedRangeMax(TripCountSCEV).getBitWidth() > 32)
863 return false;
864
865 // Making a call will trash LR and clear LO_BRANCH_INFO, so there's little
866 // point in generating a hardware loop if that's going to happen.
867 auto MaybeCall = [this](Instruction &I) {
868 const ARMTargetLowering *TLI = getTLI();
869 unsigned ISD = TLI->InstructionOpcodeToISD(I.getOpcode());
870 EVT VT = TLI->getValueType(DL, I.getType(), true);
871 if (TLI->getOperationAction(ISD, VT) == TargetLowering::LibCall)
872 return true;
873
874 // Check if an intrinsic will be lowered to a call and assume that any
875 // other CallInst will generate a bl.
876 if (auto *Call = dyn_cast<CallInst>(&I)) {
877 if (isa<IntrinsicInst>(Call)) {
878 if (const Function *F = Call->getCalledFunction())
879 return isLoweredToCall(F);
880 }
881 return true;
882 }
883
884 // FPv5 provides conversions between integer, double-precision,
885 // single-precision, and half-precision formats.
886 switch (I.getOpcode()) {
887 default:
888 break;
889 case Instruction::FPToSI:
890 case Instruction::FPToUI:
891 case Instruction::SIToFP:
892 case Instruction::UIToFP:
893 case Instruction::FPTrunc:
894 case Instruction::FPExt:
895 return !ST->hasFPARMv8Base();
896 }
897
898 // FIXME: Unfortunately the approach of checking the Operation Action does
899 // not catch all cases of Legalization that use library calls. Our
900 // Legalization step categorizes some transformations into library calls as
901 // Custom, Expand or even Legal when doing type legalization. So for now
902 // we have to special case for instance the SDIV of 64bit integers and the
903 // use of floating point emulation.
904 if (VT.isInteger() && VT.getSizeInBits() >= 64) {
905 switch (ISD) {
906 default:
907 break;
908 case ISD::SDIV:
909 case ISD::UDIV:
910 case ISD::SREM:
911 case ISD::UREM:
912 case ISD::SDIVREM:
913 case ISD::UDIVREM:
914 return true;
915 }
916 }
917
918 // Assume all other non-float operations are supported.
919 if (!VT.isFloatingPoint())
920 return false;
921
922 // We'll need a library call to handle most floats when using soft.
923 if (TLI->useSoftFloat()) {
924 switch (I.getOpcode()) {
925 default:
926 return true;
927 case Instruction::Alloca:
928 case Instruction::Load:
929 case Instruction::Store:
930 case Instruction::Select:
931 case Instruction::PHI:
932 return false;
933 }
934 }
935
936 // We'll need a libcall to perform double precision operations on a single
937 // precision only FPU.
938 if (I.getType()->isDoubleTy() && !ST->hasFP64())
939 return true;
940
941 // Likewise for half precision arithmetic.
942 if (I.getType()->isHalfTy() && !ST->hasFullFP16())
943 return true;
944
945 return false;
946 };
947
948 auto IsHardwareLoopIntrinsic = [](Instruction &I) {
949 if (auto *Call = dyn_cast<IntrinsicInst>(&I)) {
950 switch (Call->getIntrinsicID()) {
951 default:
952 break;
953 case Intrinsic::set_loop_iterations:
954 case Intrinsic::test_set_loop_iterations:
955 case Intrinsic::loop_decrement:
956 case Intrinsic::loop_decrement_reg:
957 return true;
958 }
959 }
960 return false;
961 };
962
963 // Scan the instructions to see if there's any that we know will turn into a
964 // call or if this loop is already a low-overhead loop.
965 auto ScanLoop = [&](Loop *L) {
966 for (auto *BB : L->getBlocks()) {
967 for (auto &I : *BB) {
968 if (MaybeCall(I) || IsHardwareLoopIntrinsic(I))
969 return false;
970 }
971 }
972 return true;
973 };
974
975 // Visit inner loops.
976 for (auto Inner : *L)
977 if (!ScanLoop(Inner))
978 return false;
979
980 if (!ScanLoop(L))
981 return false;
982
983 // TODO: Check whether the trip count calculation is expensive. If L is the
984 // inner loop but we know it has a low trip count, calculating that trip
985 // count (in the parent loop) may be detrimental.
986
987 LLVMContext &C = L->getHeader()->getContext();
988 HWLoopInfo.CounterInReg = true;
989 HWLoopInfo.IsNestingLegal = false;
990 HWLoopInfo.PerformEntryTest = true;
991 HWLoopInfo.CountType = Type::getInt32Ty(C);
992 HWLoopInfo.LoopDecrement = ConstantInt::get(HWLoopInfo.CountType, 1);
993 return true;
994}
995
996void ARMTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
997 TTI::UnrollingPreferences &UP) {
998 // Only currently enable these preferences for M-Class cores.
999 if (!ST->isMClass())
1
Taking false branch
1000 return BasicTTIImplBase::getUnrollingPreferences(L, SE, UP);
1001
1002 // Disable loop unrolling for Oz and Os.
1003 UP.OptSizeThreshold = 0;
1004 UP.PartialOptSizeThreshold = 0;
1005 if (L->getHeader()->getParent()->hasOptSize())
2
Assuming the condition is false
3
Taking false branch
1006 return;
1007
1008 // Only enable on Thumb-2 targets.
1009 if (!ST->isThumb2())
4
Assuming the condition is false
5
Taking false branch
1010 return;
1011
1012 SmallVector<BasicBlock*, 4> ExitingBlocks;
1013 L->getExitingBlocks(ExitingBlocks);
1014 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
)
6
Assuming 'DebugFlag' is false
7
Loop condition is false. Exiting loop
1015 << "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
)
1016 << "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
)
;
1017
1018 // Only allow another exit other than the latch. This acts as an early exit
1019 // as it mirrors the profitability calculation of the runtime unroller.
1020 if (ExitingBlocks.size() > 2)
8
Assuming the condition is false
9
Taking false branch
1021 return;
1022
1023 // Limit the CFG of the loop body for targets with a branch predictor.
1024 // Allowing 4 blocks permits if-then-else diamonds in the body.
1025 if (ST->hasBranchPredictor() && L->getNumBlocks() > 4)
10
Assuming the condition is false
1026 return;
1027
1028 // Scan the loop: don't unroll loops with calls as this could prevent
1029 // inlining.
1030 unsigned Cost = 0;
1031 for (auto *BB : L->getBlocks()) {
11
Assuming '__begin1' is not equal to '__end1'
1032 for (auto &I : *BB) {
1033 if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
12
Assuming 'I' is not a 'CallInst'
13
Assuming 'I' is not a 'InvokeInst'
14
Taking false branch
1034 ImmutableCallSite CS(&I);
1035 if (const Function *F = CS.getCalledFunction()) {
1036 if (!isLoweredToCall(F))
1037 continue;
1038 }
1039 return;
1040 }
1041 // Don't unroll vectorised loop. MVE does not benefit from it as much as
1042 // scalar code.
1043 if (I.getType()->isVectorTy())
15
Taking false branch
1044 return;
1045
1046 SmallVector<const Value*, 4> Operands(I.value_op_begin(),
1047 I.value_op_end());
1048 Cost += getUserCost(&I, Operands);
16
Calling 'TargetTransformInfoImplCRTPBase::getUserCost'
1049 }
1050 }
1051
1052 LLVM_DEBUG(dbgs() << "Cost of loop: " << Cost << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("armtti")) { dbgs() << "Cost of loop: " << Cost <<
"\n"; } } while (false)
;
1053
1054 UP.Partial = true;
1055 UP.Runtime = true;
1056 UP.UpperBound = true;
1057 UP.UnrollRemainder = true;
1058 UP.DefaultUnrollRuntimeCount = 4;
1059 UP.UnrollAndJam = true;
1060 UP.UnrollAndJamInnerLoopThreshold = 60;
1061
1062 // Force unrolling small loops can be very useful because of the branch
1063 // taken cost of the backedge.
1064 if (Cost < 12)
1065 UP.Force = true;
1066}
1067
1068bool ARMTTIImpl::useReductionIntrinsic(unsigned Opcode, Type *Ty,
1069 TTI::ReductionFlags Flags) const {
1070 assert(isa<VectorType>(Ty) && "Expected Ty to be a vector type")((isa<VectorType>(Ty) && "Expected Ty to be a vector type"
) ? static_cast<void> (0) : __assert_fail ("isa<VectorType>(Ty) && \"Expected Ty to be a vector type\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Target/ARM/ARMTargetTransformInfo.cpp"
, 1070, __PRETTY_FUNCTION__))
;
1071 unsigned ScalarBits = Ty->getScalarSizeInBits();
1072 if (!ST->hasMVEIntegerOps())
1073 return false;
1074
1075 switch (Opcode) {
1076 case Instruction::FAdd:
1077 case Instruction::FMul:
1078 case Instruction::And:
1079 case Instruction::Or:
1080 case Instruction::Xor:
1081 case Instruction::Mul:
1082 case Instruction::FCmp:
1083 return false;
1084 case Instruction::ICmp:
1085 case Instruction::Add:
1086 return ScalarBits < 64 && ScalarBits * Ty->getVectorNumElements() == 128;
1087 default:
1088 llvm_unreachable("Unhandled reduction opcode")::llvm::llvm_unreachable_internal("Unhandled reduction opcode"
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Target/ARM/ARMTargetTransformInfo.cpp"
, 1088)
;
1089 }
1090 return false;
1091}

/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/Analysis/TargetTransformInfoImpl.h

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

/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/CallSite.h

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

/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/ADT/PointerIntPair.h

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

/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/Support/PointerLikeTypeTraits.h

1//===- llvm/Support/PointerLikeTypeTraits.h - Pointer Traits ----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the PointerLikeTypeTraits class. This allows data
10// structures to reason about pointers and other things that are pointer sized.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_SUPPORT_POINTERLIKETYPETRAITS_H
15#define LLVM_SUPPORT_POINTERLIKETYPETRAITS_H
16
17#include "llvm/Support/DataTypes.h"
18#include <assert.h>
19#include <type_traits>
20
21namespace llvm {
22
23/// A traits type that is used to handle pointer types and things that are just
24/// wrappers for pointers as a uniform entity.
25template <typename T> struct PointerLikeTypeTraits;
26
27namespace detail {
28/// A tiny meta function to compute the log2 of a compile time constant.
29template <size_t N>
30struct ConstantLog2
31 : std::integral_constant<size_t, ConstantLog2<N / 2>::value + 1> {};
32template <> struct ConstantLog2<1> : std::integral_constant<size_t, 0> {};
33
34// Provide a trait to check if T is pointer-like.
35template <typename T, typename U = void> struct HasPointerLikeTypeTraits {
36 static const bool value = false;
37};
38
39// sizeof(T) is valid only for a complete T.
40template <typename T> struct HasPointerLikeTypeTraits<
41 T, decltype((sizeof(PointerLikeTypeTraits<T>) + sizeof(T)), void())> {
42 static const bool value = true;
43};
44
45template <typename T> struct IsPointerLike {
46 static const bool value = HasPointerLikeTypeTraits<T>::value;
47};
48
49template <typename T> struct IsPointerLike<T *> {
50 static const bool value = true;
51};
52} // namespace detail
53
54// Provide PointerLikeTypeTraits for non-cvr pointers.
55template <typename T> struct PointerLikeTypeTraits<T *> {
56 static inline void *getAsVoidPointer(T *P) { return P; }
57 static inline T *getFromVoidPointer(void *P) { return static_cast<T *>(P); }
30
Returning null pointer (loaded from 'P'), which participates in a condition later
58
59 enum { NumLowBitsAvailable = detail::ConstantLog2<alignof(T)>::value };
60};
61
62template <> struct PointerLikeTypeTraits<void *> {
63 static inline void *getAsVoidPointer(void *P) { return P; }
64 static inline void *getFromVoidPointer(void *P) { return P; }
65
66 /// Note, we assume here that void* is related to raw malloc'ed memory and
67 /// that malloc returns objects at least 4-byte aligned. However, this may be
68 /// wrong, or pointers may be from something other than malloc. In this case,
69 /// you should specify a real typed pointer or avoid this template.
70 ///
71 /// All clients should use assertions to do a run-time check to ensure that
72 /// this is actually true.
73 enum { NumLowBitsAvailable = 2 };
74};
75
76// Provide PointerLikeTypeTraits for const things.
77template <typename T> struct PointerLikeTypeTraits<const T> {
78 typedef PointerLikeTypeTraits<T> NonConst;
79
80 static inline const void *getAsVoidPointer(const T P) {
81 return NonConst::getAsVoidPointer(P);
82 }
83 static inline const T getFromVoidPointer(const void *P) {
84 return NonConst::getFromVoidPointer(const_cast<void *>(P));
85 }
86 enum { NumLowBitsAvailable = NonConst::NumLowBitsAvailable };
87};
88
89// Provide PointerLikeTypeTraits for const pointers.
90template <typename T> struct PointerLikeTypeTraits<const T *> {
91 typedef PointerLikeTypeTraits<T *> NonConst;
92
93 static inline const void *getAsVoidPointer(const T *P) {
94 return NonConst::getAsVoidPointer(const_cast<T *>(P));
95 }
96 static inline const T *getFromVoidPointer(const void *P) {
97 return NonConst::getFromVoidPointer(const_cast<void *>(P));
29
Calling 'PointerLikeTypeTraits::getFromVoidPointer'
31
Returning from 'PointerLikeTypeTraits::getFromVoidPointer'
32
Returning null pointer, which participates in a condition later
98 }
99 enum { NumLowBitsAvailable = NonConst::NumLowBitsAvailable };
100};
101
102// Provide PointerLikeTypeTraits for uintptr_t.
103template <> struct PointerLikeTypeTraits<uintptr_t> {
104 static inline void *getAsVoidPointer(uintptr_t P) {
105 return reinterpret_cast<void *>(P);
106 }
107 static inline uintptr_t getFromVoidPointer(void *P) {
108 return reinterpret_cast<uintptr_t>(P);
109 }
110 // No bits are available!
111 enum { NumLowBitsAvailable = 0 };
112};
113
114/// Provide suitable custom traits struct for function pointers.
115///
116/// Function pointers can't be directly given these traits as functions can't
117/// have their alignment computed with `alignof` and we need different casting.
118///
119/// To rely on higher alignment for a specialized use, you can provide a
120/// customized form of this template explicitly with higher alignment, and
121/// potentially use alignment attributes on functions to satisfy that.
122template <int Alignment, typename FunctionPointerT>
123struct FunctionPointerLikeTypeTraits {
124 enum { NumLowBitsAvailable = detail::ConstantLog2<Alignment>::value };
125 static inline void *getAsVoidPointer(FunctionPointerT P) {
126 assert((reinterpret_cast<uintptr_t>(P) &(((reinterpret_cast<uintptr_t>(P) & ~((uintptr_t)-1
<< NumLowBitsAvailable)) == 0 && "Alignment not satisfied for an actual function pointer!"
) ? static_cast<void> (0) : __assert_fail ("(reinterpret_cast<uintptr_t>(P) & ~((uintptr_t)-1 << NumLowBitsAvailable)) == 0 && \"Alignment not satisfied for an actual function pointer!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/Support/PointerLikeTypeTraits.h"
, 128, __PRETTY_FUNCTION__))
127 ~((uintptr_t)-1 << NumLowBitsAvailable)) == 0 &&(((reinterpret_cast<uintptr_t>(P) & ~((uintptr_t)-1
<< NumLowBitsAvailable)) == 0 && "Alignment not satisfied for an actual function pointer!"
) ? static_cast<void> (0) : __assert_fail ("(reinterpret_cast<uintptr_t>(P) & ~((uintptr_t)-1 << NumLowBitsAvailable)) == 0 && \"Alignment not satisfied for an actual function pointer!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/Support/PointerLikeTypeTraits.h"
, 128, __PRETTY_FUNCTION__))
128 "Alignment not satisfied for an actual function pointer!")(((reinterpret_cast<uintptr_t>(P) & ~((uintptr_t)-1
<< NumLowBitsAvailable)) == 0 && "Alignment not satisfied for an actual function pointer!"
) ? static_cast<void> (0) : __assert_fail ("(reinterpret_cast<uintptr_t>(P) & ~((uintptr_t)-1 << NumLowBitsAvailable)) == 0 && \"Alignment not satisfied for an actual function pointer!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/Support/PointerLikeTypeTraits.h"
, 128, __PRETTY_FUNCTION__))
;
129 return reinterpret_cast<void *>(P);
130 }
131 static inline FunctionPointerT getFromVoidPointer(void *P) {
132 return reinterpret_cast<FunctionPointerT>(P);
133 }
134};
135
136/// Provide a default specialization for function pointers that assumes 4-byte
137/// alignment.
138///
139/// We assume here that functions used with this are always at least 4-byte
140/// aligned. This means that, for example, thumb functions won't work or systems
141/// with weird unaligned function pointers won't work. But all practical systems
142/// we support satisfy this requirement.
143template <typename ReturnT, typename... ParamTs>
144struct PointerLikeTypeTraits<ReturnT (*)(ParamTs...)>
145 : FunctionPointerLikeTypeTraits<4, ReturnT (*)(ParamTs...)> {};
146
147} // end namespace llvm
148
149#endif

/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Operator.h

1//===-- llvm/Operator.h - Operator utility subclass -------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines various classes for working with Instructions and
10// ConstantExprs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_IR_OPERATOR_H
15#define LLVM_IR_OPERATOR_H
16
17#include "llvm/ADT/None.h"
18#include "llvm/ADT/Optional.h"
19#include "llvm/IR/Constants.h"
20#include "llvm/IR/Instruction.h"
21#include "llvm/IR/Type.h"
22#include "llvm/IR/Value.h"
23#include "llvm/Support/Casting.h"
24#include <cstddef>
25
26namespace llvm {
27
28/// This is a utility class that provides an abstraction for the common
29/// functionality between Instructions and ConstantExprs.
30class Operator : public User {
31public:
32 // The Operator class is intended to be used as a utility, and is never itself
33 // instantiated.
34 Operator() = delete;
35 ~Operator() = delete;
36
37 void *operator new(size_t s) = delete;
38
39 /// Return the opcode for this Instruction or ConstantExpr.
40 unsigned getOpcode() const {
41 if (const Instruction *I = dyn_cast<Instruction>(this))
42 return I->getOpcode();
43 return cast<ConstantExpr>(this)->getOpcode();
44 }
45
46 /// If V is an Instruction or ConstantExpr, return its opcode.
47 /// Otherwise return UserOp1.
48 static unsigned getOpcode(const Value *V) {
49 if (const Instruction *I
46.1
'I' is non-null
46.1
'I' is non-null
46.1
'I' is non-null
46.1
'I' is non-null
46.1
'I' is non-null
46.1
'I' is non-null
46.1
'I' is non-null
= dyn_cast<Instruction>(V))
46
Assuming 'V' is a 'Instruction'
47
Taking true branch
50 return I->getOpcode();
48
Returning value, which participates in a condition later
51 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
52 return CE->getOpcode();
53 return Instruction::UserOp1;
54 }
55
56 static bool classof(const Instruction *) { return true; }
57 static bool classof(const ConstantExpr *) { return true; }
58 static bool classof(const Value *V) {
59 return isa<Instruction>(V) || isa<ConstantExpr>(V);
60 }
61};
62
63/// Utility class for integer operators which may exhibit overflow - Add, Sub,
64/// Mul, and Shl. It does not include SDiv, despite that operator having the
65/// potential for overflow.
66class OverflowingBinaryOperator : public Operator {
67public:
68 enum {
69 NoUnsignedWrap = (1 << 0),
70 NoSignedWrap = (1 << 1)
71 };
72
73private:
74 friend class Instruction;
75 friend class ConstantExpr;
76
77 void setHasNoUnsignedWrap(bool B) {
78 SubclassOptionalData =
79 (SubclassOptionalData & ~NoUnsignedWrap) | (B * NoUnsignedWrap);
80 }
81 void setHasNoSignedWrap(bool B) {
82 SubclassOptionalData =
83 (SubclassOptionalData & ~NoSignedWrap) | (B * NoSignedWrap);
84 }
85
86public:
87 /// Test whether this operation is known to never
88 /// undergo unsigned overflow, aka the nuw property.
89 bool hasNoUnsignedWrap() const {
90 return SubclassOptionalData & NoUnsignedWrap;
91 }
92
93 /// Test whether this operation is known to never
94 /// undergo signed overflow, aka the nsw property.
95 bool hasNoSignedWrap() const {
96 return (SubclassOptionalData & NoSignedWrap) != 0;
97 }
98
99 static bool classof(const Instruction *I) {
100 return I->getOpcode() == Instruction::Add ||
101 I->getOpcode() == Instruction::Sub ||
102 I->getOpcode() == Instruction::Mul ||
103 I->getOpcode() == Instruction::Shl;
104 }
105 static bool classof(const ConstantExpr *CE) {
106 return CE->getOpcode() == Instruction::Add ||
107 CE->getOpcode() == Instruction::Sub ||
108 CE->getOpcode() == Instruction::Mul ||
109 CE->getOpcode() == Instruction::Shl;
110 }
111 static bool classof(const Value *V) {
112 return (isa<Instruction>(V) && classof(cast<Instruction>(V))) ||
113 (isa<ConstantExpr>(V) && classof(cast<ConstantExpr>(V)));
114 }
115};
116
117/// A udiv or sdiv instruction, which can be marked as "exact",
118/// indicating that no bits are destroyed.
119class PossiblyExactOperator : public Operator {
120public:
121 enum {
122 IsExact = (1 << 0)
123 };
124
125private:
126 friend class Instruction;
127 friend class ConstantExpr;
128
129 void setIsExact(bool B) {
130 SubclassOptionalData = (SubclassOptionalData & ~IsExact) | (B * IsExact);
131 }
132
133public:
134 /// Test whether this division is known to be exact, with zero remainder.
135 bool isExact() const {
136 return SubclassOptionalData & IsExact;
137 }
138
139 static bool isPossiblyExactOpcode(unsigned OpC) {
140 return OpC == Instruction::SDiv ||
141 OpC == Instruction::UDiv ||
142 OpC == Instruction::AShr ||
143 OpC == Instruction::LShr;
144 }
145
146 static bool classof(const ConstantExpr *CE) {
147 return isPossiblyExactOpcode(CE->getOpcode());
148 }
149 static bool classof(const Instruction *I) {
150 return isPossiblyExactOpcode(I->getOpcode());
151 }
152 static bool classof(const Value *V) {
153 return (isa<Instruction>(V) && classof(cast<Instruction>(V))) ||
154 (isa<ConstantExpr>(V) && classof(cast<ConstantExpr>(V)));
155 }
156};
157
158/// Convenience struct for specifying and reasoning about fast-math flags.
159class FastMathFlags {
160private:
161 friend class FPMathOperator;
162
163 unsigned Flags = 0;
164
165 FastMathFlags(unsigned F) {
166 // If all 7 bits are set, turn this into -1. If the number of bits grows,
167 // this must be updated. This is intended to provide some forward binary
168 // compatibility insurance for the meaning of 'fast' in case bits are added.
169 if (F == 0x7F) Flags = ~0U;
170 else Flags = F;
171 }
172
173public:
174 // This is how the bits are used in Value::SubclassOptionalData so they
175 // should fit there too.
176 // WARNING: We're out of space. SubclassOptionalData only has 7 bits. New
177 // functionality will require a change in how this information is stored.
178 enum {
179 AllowReassoc = (1 << 0),
180 NoNaNs = (1 << 1),
181 NoInfs = (1 << 2),
182 NoSignedZeros = (1 << 3),
183 AllowReciprocal = (1 << 4),
184 AllowContract = (1 << 5),
185 ApproxFunc = (1 << 6)
186 };
187
188 FastMathFlags() = default;
189
190 static FastMathFlags getFast() {
191 FastMathFlags FMF;
192 FMF.setFast();
193 return FMF;
194 }
195
196 bool any() const { return Flags != 0; }
197 bool none() const { return Flags == 0; }
198 bool all() const { return Flags == ~0U; }
199
200 void clear() { Flags = 0; }
201 void set() { Flags = ~0U; }
202
203 /// Flag queries
204 bool allowReassoc() const { return 0 != (Flags & AllowReassoc); }
205 bool noNaNs() const { return 0 != (Flags & NoNaNs); }
206 bool noInfs() const { return 0 != (Flags & NoInfs); }
207 bool noSignedZeros() const { return 0 != (Flags & NoSignedZeros); }
208 bool allowReciprocal() const { return 0 != (Flags & AllowReciprocal); }
209 bool allowContract() const { return 0 != (Flags & AllowContract); }
210 bool approxFunc() const { return 0 != (Flags & ApproxFunc); }
211 /// 'Fast' means all bits are set.
212 bool isFast() const { return all(); }
213
214 /// Flag setters
215 void setAllowReassoc(bool B = true) {
216 Flags = (Flags & ~AllowReassoc) | B * AllowReassoc;
217 }
218 void setNoNaNs(bool B = true) {
219 Flags = (Flags & ~NoNaNs) | B * NoNaNs;
220 }
221 void setNoInfs(bool B = true) {
222 Flags = (Flags & ~NoInfs) | B * NoInfs;
223 }
224 void setNoSignedZeros(bool B = true) {
225 Flags = (Flags & ~NoSignedZeros) | B * NoSignedZeros;
226 }
227 void setAllowReciprocal(bool B = true) {
228 Flags = (Flags & ~AllowReciprocal) | B * AllowReciprocal;
229 }
230 void setAllowContract(bool B = true) {
231 Flags = (Flags & ~AllowContract) | B * AllowContract;
232 }
233 void setApproxFunc(bool B = true) {
234 Flags = (Flags & ~ApproxFunc) | B * ApproxFunc;
235 }
236 void setFast(bool B = true) { B ? set() : clear(); }
237
238 void operator&=(const FastMathFlags &OtherFlags) {
239 Flags &= OtherFlags.Flags;
240 }
241};
242
243/// Utility class for floating point operations which can have
244/// information about relaxed accuracy requirements attached to them.
245class FPMathOperator : public Operator {
246private:
247 friend class Instruction;
248
249 /// 'Fast' means all bits are set.
250 void setFast(bool B) {
251 setHasAllowReassoc(B);
252 setHasNoNaNs(B);
253 setHasNoInfs(B);
254 setHasNoSignedZeros(B);
255 setHasAllowReciprocal(B);
256 setHasAllowContract(B);
257 setHasApproxFunc(B);
258 }
259
260 void setHasAllowReassoc(bool B) {
261 SubclassOptionalData =
262 (SubclassOptionalData & ~FastMathFlags::AllowReassoc) |
263 (B * FastMathFlags::AllowReassoc);
264 }
265
266 void setHasNoNaNs(bool B) {
267 SubclassOptionalData =
268 (SubclassOptionalData & ~FastMathFlags::NoNaNs) |
269 (B * FastMathFlags::NoNaNs);
270 }
271
272 void setHasNoInfs(bool B) {
273 SubclassOptionalData =
274 (SubclassOptionalData & ~FastMathFlags::NoInfs) |
275 (B * FastMathFlags::NoInfs);
276 }
277
278 void setHasNoSignedZeros(bool B) {
279 SubclassOptionalData =
280 (SubclassOptionalData & ~FastMathFlags::NoSignedZeros) |
281 (B * FastMathFlags::NoSignedZeros);
282 }
283
284 void setHasAllowReciprocal(bool B) {
285 SubclassOptionalData =
286 (SubclassOptionalData & ~FastMathFlags::AllowReciprocal) |
287 (B * FastMathFlags::AllowReciprocal);
288 }
289
290 void setHasAllowContract(bool B) {
291 SubclassOptionalData =
292 (SubclassOptionalData & ~FastMathFlags::AllowContract) |
293 (B * FastMathFlags::AllowContract);
294 }
295
296 void setHasApproxFunc(bool B) {
297 SubclassOptionalData =
298 (SubclassOptionalData & ~FastMathFlags::ApproxFunc) |
299 (B * FastMathFlags::ApproxFunc);
300 }
301
302 /// Convenience function for setting multiple fast-math flags.
303 /// FMF is a mask of the bits to set.
304 void setFastMathFlags(FastMathFlags FMF) {
305 SubclassOptionalData |= FMF.Flags;
306 }
307
308 /// Convenience function for copying all fast-math flags.
309 /// All values in FMF are transferred to this operator.
310 void copyFastMathFlags(FastMathFlags FMF) {
311 SubclassOptionalData = FMF.Flags;
312 }
313
314public:
315 /// Test if this operation allows all non-strict floating-point transforms.
316 bool isFast() const {
317 return ((SubclassOptionalData & FastMathFlags::AllowReassoc) != 0 &&
318 (SubclassOptionalData & FastMathFlags::NoNaNs) != 0 &&
319 (SubclassOptionalData & FastMathFlags::NoInfs) != 0 &&
320 (SubclassOptionalData & FastMathFlags::NoSignedZeros) != 0 &&
321 (SubclassOptionalData & FastMathFlags::AllowReciprocal) != 0 &&
322 (SubclassOptionalData & FastMathFlags::AllowContract) != 0 &&
323 (SubclassOptionalData & FastMathFlags::ApproxFunc) != 0);
324 }
325
326 /// Test if this operation may be simplified with reassociative transforms.
327 bool hasAllowReassoc() const {
328 return (SubclassOptionalData & FastMathFlags::AllowReassoc) != 0;
329 }
330
331 /// Test if this operation's arguments and results are assumed not-NaN.
332 bool hasNoNaNs() const {
333 return (SubclassOptionalData & FastMathFlags::NoNaNs) != 0;
334 }
335
336 /// Test if this operation's arguments and results are assumed not-infinite.
337 bool hasNoInfs() const {
338 return (SubclassOptionalData & FastMathFlags::NoInfs) != 0;
339 }
340
341 /// Test if this operation can ignore the sign of zero.
342 bool hasNoSignedZeros() const {
343 return (SubclassOptionalData & FastMathFlags::NoSignedZeros) != 0;
344 }
345
346 /// Test if this operation can use reciprocal multiply instead of division.
347 bool hasAllowReciprocal() const {
348 return (SubclassOptionalData & FastMathFlags::AllowReciprocal) != 0;
349 }
350
351 /// Test if this operation can be floating-point contracted (FMA).
352 bool hasAllowContract() const {
353 return (SubclassOptionalData & FastMathFlags::AllowContract) != 0;
354 }
355
356 /// Test if this operation allows approximations of math library functions or
357 /// intrinsics.
358 bool hasApproxFunc() const {
359 return (SubclassOptionalData & FastMathFlags::ApproxFunc) != 0;
360 }
361
362 /// Convenience function for getting all the fast-math flags
363 FastMathFlags getFastMathFlags() const {
364 return FastMathFlags(SubclassOptionalData);
365 }
366
367 /// Get the maximum error permitted by this operation in ULPs. An accuracy of
368 /// 0.0 means that the operation should be performed with the default
369 /// precision.
370 float getFPAccuracy() const;
371
372 static bool classof(const Value *V) {
373 unsigned Opcode;
374 if (auto *I = dyn_cast<Instruction>(V))
375 Opcode = I->getOpcode();
376 else if (auto *CE = dyn_cast<ConstantExpr>(V))
377 Opcode = CE->getOpcode();
378 else
379 return false;
380
381 switch (Opcode) {
382 // FIXME: To clean up and correct the semantics of fast-math-flags, FCmp
383 // should not be treated as a math op, but the other opcodes should.
384 // This would make things consistent with Select/PHI (FP value type
385 // determines whether they are math ops and, therefore, capable of
386 // having fast-math-flags).
387 case Instruction::FCmp:
388 return true;
389 // non math FP Operators (no FMF)
390 case Instruction::ExtractElement:
391 case Instruction::ShuffleVector:
392 case Instruction::InsertElement:
393 return false;
394 default:
395 return V->getType()->isFPOrFPVectorTy();
396 }
397 }
398};
399
400/// A helper template for defining operators for individual opcodes.
401template<typename SuperClass, unsigned Opc>
402class ConcreteOperator : public SuperClass {
403public:
404 static bool classof(const Instruction *I) {
405 return I->getOpcode() == Opc;
406 }
407 static bool classof(const ConstantExpr *CE) {
408 return CE->getOpcode() == Opc;
409 }
410 static bool classof(const Value *V) {
411 return (isa<Instruction>(V) && classof(cast<Instruction>(V))) ||
412 (isa<ConstantExpr>(V) && classof(cast<ConstantExpr>(V)));
413 }
414};
415
416class AddOperator
417 : public ConcreteOperator<OverflowingBinaryOperator, Instruction::Add> {
418};
419class SubOperator
420 : public ConcreteOperator<OverflowingBinaryOperator, Instruction::Sub> {
421};
422class MulOperator
423 : public ConcreteOperator<OverflowingBinaryOperator, Instruction::Mul> {
424};
425class ShlOperator
426 : public ConcreteOperator<OverflowingBinaryOperator, Instruction::Shl> {
427};
428
429class SDivOperator
430 : public ConcreteOperator<PossiblyExactOperator, Instruction::SDiv> {
431};
432class UDivOperator
433 : public ConcreteOperator<PossiblyExactOperator, Instruction::UDiv> {
434};
435class AShrOperator
436 : public ConcreteOperator<PossiblyExactOperator, Instruction::AShr> {
437};
438class LShrOperator
439 : public ConcreteOperator<PossiblyExactOperator, Instruction::LShr> {
440};
441
442class ZExtOperator : public ConcreteOperator<Operator, Instruction::ZExt> {};
443
444class GEPOperator
445 : public ConcreteOperator<Operator, Instruction::GetElementPtr> {
446 friend class GetElementPtrInst;
447 friend class ConstantExpr;
448
449 enum {
450 IsInBounds = (1 << 0),
451 // InRangeIndex: bits 1-6
452 };
453
454 void setIsInBounds(bool B) {
455 SubclassOptionalData =
456 (SubclassOptionalData & ~IsInBounds) | (B * IsInBounds);
457 }
458
459public:
460 /// Test whether this is an inbounds GEP, as defined by LangRef.html.
461 bool isInBounds() const {
462 return SubclassOptionalData & IsInBounds;
463 }
464
465 /// Returns the offset of the index with an inrange attachment, or None if
466 /// none.
467 Optional<unsigned> getInRangeIndex() const {
468 if (SubclassOptionalData >> 1 == 0) return None;
469 return (SubclassOptionalData >> 1) - 1;
470 }
471
472 inline op_iterator idx_begin() { return op_begin()+1; }
473 inline const_op_iterator idx_begin() const { return op_begin()+1; }
474 inline op_iterator idx_end() { return op_end(); }
475 inline const_op_iterator idx_end() const { return op_end(); }
476
477 Value *getPointerOperand() {
478 return getOperand(0);
479 }
480 const Value *getPointerOperand() const {
481 return getOperand(0);
482 }
483 static unsigned getPointerOperandIndex() {
484 return 0U; // get index for modifying correct operand
485 }
486
487 /// Method to return the pointer operand as a PointerType.
488 Type *getPointerOperandType() const {
489 return getPointerOperand()->getType();
490 }
491
492 Type *getSourceElementType() const;
493 Type *getResultElementType() const;
494
495 /// Method to return the address space of the pointer operand.
496 unsigned getPointerAddressSpace() const {
497 return getPointerOperandType()->getPointerAddressSpace();
498 }
499
500 unsigned getNumIndices() const { // Note: always non-negative
501 return getNumOperands() - 1;
502 }
503
504 bool hasIndices() const {
505 return getNumOperands() > 1;
506 }
507
508 /// Return true if all of the indices of this GEP are zeros.
509 /// If so, the result pointer and the first operand have the same
510 /// value, just potentially different types.
511 bool hasAllZeroIndices() const {
512 for (const_op_iterator I = idx_begin(), E = idx_end(); I != E; ++I) {
513 if (ConstantInt *C = dyn_cast<ConstantInt>(I))
514 if (C->isZero())
515 continue;
516 return false;
517 }
518 return true;
519 }
520
521 /// Return true if all of the indices of this GEP are constant integers.
522 /// If so, the result pointer and the first operand have
523 /// a constant offset between them.
524 bool hasAllConstantIndices() const {
525 for (const_op_iterator I = idx_begin(), E = idx_end(); I != E; ++I) {
526 if (!isa<ConstantInt>(I))
527 return false;
528 }
529 return true;
530 }
531
532 unsigned countNonConstantIndices() const {
533 return count_if(make_range(idx_begin(), idx_end()), [](const Use& use) {
534 return !isa<ConstantInt>(*use);
535 });
536 }
537
538 /// Accumulate the constant address offset of this GEP if possible.
539 ///
540 /// This routine accepts an APInt into which it will accumulate the constant
541 /// offset of this GEP if the GEP is in fact constant. If the GEP is not
542 /// all-constant, it returns false and the value of the offset APInt is
543 /// undefined (it is *not* preserved!). The APInt passed into this routine
544 /// must be at exactly as wide as the IntPtr type for the address space of the
545 /// base GEP pointer.
546 bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
547};
548
549class PtrToIntOperator
550 : public ConcreteOperator<Operator, Instruction::PtrToInt> {
551 friend class PtrToInt;
552 friend class ConstantExpr;
553
554public:
555 Value *getPointerOperand() {
556 return getOperand(0);
557 }
558 const Value *getPointerOperand() const {
559 return getOperand(0);
560 }
561
562 static unsigned getPointerOperandIndex() {
563 return 0U; // get index for modifying correct operand
564 }
565
566 /// Method to return the pointer operand as a PointerType.
567 Type *getPointerOperandType() const {
568 return getPointerOperand()->getType();
569 }
570
571 /// Method to return the address space of the pointer operand.
572 unsigned getPointerAddressSpace() const {
573 return cast<PointerType>(getPointerOperandType())->getAddressSpace();
574 }
575};
576
577class BitCastOperator
578 : public ConcreteOperator<Operator, Instruction::BitCast> {
579 friend class BitCastInst;
580 friend class ConstantExpr;
581
582public:
583 Type *getSrcTy() const {
584 return getOperand(0)->getType();
585 }
586
587 Type *getDestTy() const {
588 return getType();
589 }
590};
591
592} // end namespace llvm
593
594#endif // LLVM_IR_OPERATOR_H

/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/CodeGen/BasicTTIImpl.h

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