Bug Summary

File:include/llvm/CodeGen/TargetLowering.h
Warning:line 1100, column 9
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ARMTargetTransformInfo.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-8/lib/clang/8.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/lib/Target/ARM -I /build/llvm-toolchain-snapshot-8~svn345461/lib/Target/ARM -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn345461/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/lib/Target/ARM -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-10-27-211344-32123-1 -x c++ /build/llvm-toolchain-snapshot-8~svn345461/lib/Target/ARM/ARMTargetTransformInfo.cpp -faddrsig

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

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

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

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

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

1//===- llvm/CodeGen/TargetLowering.h - Target Lowering Info -----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// This file describes how to lower LLVM code to machine code. This has two
12/// main components:
13///
14/// 1. Which ValueTypes are natively supported by the target.
15/// 2. Which operations are supported for supported ValueTypes.
16/// 3. Cost thresholds for alternative implementations of certain operations.
17///
18/// In addition it has a few other components, like information about FP
19/// immediates.
20///
21//===----------------------------------------------------------------------===//
22
23#ifndef LLVM_CODEGEN_TARGETLOWERING_H
24#define LLVM_CODEGEN_TARGETLOWERING_H
25
26#include "llvm/ADT/APInt.h"
27#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringRef.h"
32#include "llvm/Analysis/LegacyDivergenceAnalysis.h"
33#include "llvm/CodeGen/DAGCombine.h"
34#include "llvm/CodeGen/ISDOpcodes.h"
35#include "llvm/CodeGen/RuntimeLibcalls.h"
36#include "llvm/CodeGen/SelectionDAG.h"
37#include "llvm/CodeGen/SelectionDAGNodes.h"
38#include "llvm/CodeGen/TargetCallingConv.h"
39#include "llvm/CodeGen/ValueTypes.h"
40#include "llvm/IR/Attributes.h"
41#include "llvm/IR/CallSite.h"
42#include "llvm/IR/CallingConv.h"
43#include "llvm/IR/DataLayout.h"
44#include "llvm/IR/DerivedTypes.h"
45#include "llvm/IR/Function.h"
46#include "llvm/IR/IRBuilder.h"
47#include "llvm/IR/InlineAsm.h"
48#include "llvm/IR/Instruction.h"
49#include "llvm/IR/Instructions.h"
50#include "llvm/IR/Type.h"
51#include "llvm/MC/MCRegisterInfo.h"
52#include "llvm/Support/AtomicOrdering.h"
53#include "llvm/Support/Casting.h"
54#include "llvm/Support/ErrorHandling.h"
55#include "llvm/Support/MachineValueType.h"
56#include "llvm/Target/TargetMachine.h"
57#include <algorithm>
58#include <cassert>
59#include <climits>
60#include <cstdint>
61#include <iterator>
62#include <map>
63#include <string>
64#include <utility>
65#include <vector>
66
67namespace llvm {
68
69class BranchProbability;
70class CCState;
71class CCValAssign;
72class Constant;
73class FastISel;
74class FunctionLoweringInfo;
75class GlobalValue;
76class IntrinsicInst;
77struct KnownBits;
78class LLVMContext;
79class MachineBasicBlock;
80class MachineFunction;
81class MachineInstr;
82class MachineJumpTableInfo;
83class MachineLoop;
84class MachineRegisterInfo;
85class MCContext;
86class MCExpr;
87class Module;
88class TargetRegisterClass;
89class TargetLibraryInfo;
90class TargetRegisterInfo;
91class Value;
92
93namespace Sched {
94
95 enum Preference {
96 None, // No preference
97 Source, // Follow source order.
98 RegPressure, // Scheduling for lowest register pressure.
99 Hybrid, // Scheduling for both latency and register pressure.
100 ILP, // Scheduling for ILP in low register pressure mode.
101 VLIW // Scheduling for VLIW targets.
102 };
103
104} // end namespace Sched
105
106/// This base class for TargetLowering contains the SelectionDAG-independent
107/// parts that can be used from the rest of CodeGen.
108class TargetLoweringBase {
109public:
110 /// This enum indicates whether operations are valid for a target, and if not,
111 /// what action should be used to make them valid.
112 enum LegalizeAction : uint8_t {
113 Legal, // The target natively supports this operation.
114 Promote, // This operation should be executed in a larger type.
115 Expand, // Try to expand this to other ops, otherwise use a libcall.
116 LibCall, // Don't try to expand this to other ops, always use a libcall.
117 Custom // Use the LowerOperation hook to implement custom lowering.
118 };
119
120 /// This enum indicates whether a types are legal for a target, and if not,
121 /// what action should be used to make them valid.
122 enum LegalizeTypeAction : uint8_t {
123 TypeLegal, // The target natively supports this type.
124 TypePromoteInteger, // Replace this integer with a larger one.
125 TypeExpandInteger, // Split this integer into two of half the size.
126 TypeSoftenFloat, // Convert this float to a same size integer type,
127 // if an operation is not supported in target HW.
128 TypeExpandFloat, // Split this float into two of half the size.
129 TypeScalarizeVector, // Replace this one-element vector with its element.
130 TypeSplitVector, // Split this vector into two of half the size.
131 TypeWidenVector, // This vector should be widened into a larger vector.
132 TypePromoteFloat // Replace this float with a larger one.
133 };
134
135 /// LegalizeKind holds the legalization kind that needs to happen to EVT
136 /// in order to type-legalize it.
137 using LegalizeKind = std::pair<LegalizeTypeAction, EVT>;
138
139 /// Enum that describes how the target represents true/false values.
140 enum BooleanContent {
141 UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
142 ZeroOrOneBooleanContent, // All bits zero except for bit 0.
143 ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
144 };
145
146 /// Enum that describes what type of support for selects the target has.
147 enum SelectSupportKind {
148 ScalarValSelect, // The target supports scalar selects (ex: cmov).
149 ScalarCondVectorVal, // The target supports selects with a scalar condition
150 // and vector values (ex: cmov).
151 VectorMaskSelect // The target supports vector selects with a vector
152 // mask (ex: x86 blends).
153 };
154
155 /// Enum that specifies what an atomic load/AtomicRMWInst is expanded
156 /// to, if at all. Exists because different targets have different levels of
157 /// support for these atomic instructions, and also have different options
158 /// w.r.t. what they should expand to.
159 enum class AtomicExpansionKind {
160 None, // Don't expand the instruction.
161 LLSC, // Expand the instruction into loadlinked/storeconditional; used
162 // by ARM/AArch64.
163 LLOnly, // Expand the (load) instruction into just a load-linked, which has
164 // greater atomic guarantees than a normal load.
165 CmpXChg, // Expand the instruction into cmpxchg; used by at least X86.
166 MaskedIntrinsic, // Use a target-specific intrinsic for the LL/SC loop.
167 };
168
169 /// Enum that specifies when a multiplication should be expanded.
170 enum class MulExpansionKind {
171 Always, // Always expand the instruction.
172 OnlyLegalOrCustom, // Only expand when the resulting instructions are legal
173 // or custom.
174 };
175
176 class ArgListEntry {
177 public:
178 Value *Val = nullptr;
179 SDValue Node = SDValue();
180 Type *Ty = nullptr;
181 bool IsSExt : 1;
182 bool IsZExt : 1;
183 bool IsInReg : 1;
184 bool IsSRet : 1;
185 bool IsNest : 1;
186 bool IsByVal : 1;
187 bool IsInAlloca : 1;
188 bool IsReturned : 1;
189 bool IsSwiftSelf : 1;
190 bool IsSwiftError : 1;
191 uint16_t Alignment = 0;
192
193 ArgListEntry()
194 : IsSExt(false), IsZExt(false), IsInReg(false), IsSRet(false),
195 IsNest(false), IsByVal(false), IsInAlloca(false), IsReturned(false),
196 IsSwiftSelf(false), IsSwiftError(false) {}
197
198 void setAttributes(ImmutableCallSite *CS, unsigned ArgIdx);
199 };
200 using ArgListTy = std::vector<ArgListEntry>;
201
202 virtual void markLibCallAttributes(MachineFunction *MF, unsigned CC,
203 ArgListTy &Args) const {};
204
205 static ISD::NodeType getExtendForContent(BooleanContent Content) {
206 switch (Content) {
207 case UndefinedBooleanContent:
208 // Extend by adding rubbish bits.
209 return ISD::ANY_EXTEND;
210 case ZeroOrOneBooleanContent:
211 // Extend by adding zero bits.
212 return ISD::ZERO_EXTEND;
213 case ZeroOrNegativeOneBooleanContent:
214 // Extend by copying the sign bit.
215 return ISD::SIGN_EXTEND;
216 }
217 llvm_unreachable("Invalid content kind")::llvm::llvm_unreachable_internal("Invalid content kind", "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 217)
;
218 }
219
220 /// NOTE: The TargetMachine owns TLOF.
221 explicit TargetLoweringBase(const TargetMachine &TM);
222 TargetLoweringBase(const TargetLoweringBase &) = delete;
223 TargetLoweringBase &operator=(const TargetLoweringBase &) = delete;
224 virtual ~TargetLoweringBase() = default;
225
226protected:
227 /// Initialize all of the actions to default values.
228 void initActions();
229
230public:
231 const TargetMachine &getTargetMachine() const { return TM; }
232
233 virtual bool useSoftFloat() const { return false; }
234
235 /// Return the pointer type for the given address space, defaults to
236 /// the pointer type from the data layout.
237 /// FIXME: The default needs to be removed once all the code is updated.
238 MVT getPointerTy(const DataLayout &DL, uint32_t AS = 0) const {
239 return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
240 }
241
242 /// Return the type for frame index, which is determined by
243 /// the alloca address space specified through the data layout.
244 MVT getFrameIndexTy(const DataLayout &DL) const {
245 return getPointerTy(DL, DL.getAllocaAddrSpace());
246 }
247
248 /// Return the type for operands of fence.
249 /// TODO: Let fence operands be of i32 type and remove this.
250 virtual MVT getFenceOperandTy(const DataLayout &DL) const {
251 return getPointerTy(DL);
252 }
253
254 /// EVT is not used in-tree, but is used by out-of-tree target.
255 /// A documentation for this function would be nice...
256 virtual MVT getScalarShiftAmountTy(const DataLayout &, EVT) const;
257
258 EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL,
259 bool LegalTypes = true) const;
260
261 /// Returns the type to be used for the index operand of:
262 /// ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
263 /// ISD::INSERT_SUBVECTOR, and ISD::EXTRACT_SUBVECTOR
264 virtual MVT getVectorIdxTy(const DataLayout &DL) const {
265 return getPointerTy(DL);
266 }
267
268 virtual bool isSelectSupported(SelectSupportKind /*kind*/) const {
269 return true;
270 }
271
272 /// Return true if multiple condition registers are available.
273 bool hasMultipleConditionRegisters() const {
274 return HasMultipleConditionRegisters;
275 }
276
277 /// Return true if the target has BitExtract instructions.
278 bool hasExtractBitsInsn() const { return HasExtractBitsInsn; }
279
280 /// Return the preferred vector type legalization action.
281 virtual TargetLoweringBase::LegalizeTypeAction
282 getPreferredVectorAction(EVT VT) const {
283 // The default action for one element vectors is to scalarize
284 if (VT.getVectorNumElements() == 1)
285 return TypeScalarizeVector;
286 // The default action for other vectors is to promote
287 return TypePromoteInteger;
288 }
289
290 // There are two general methods for expanding a BUILD_VECTOR node:
291 // 1. Use SCALAR_TO_VECTOR on the defined scalar values and then shuffle
292 // them together.
293 // 2. Build the vector on the stack and then load it.
294 // If this function returns true, then method (1) will be used, subject to
295 // the constraint that all of the necessary shuffles are legal (as determined
296 // by isShuffleMaskLegal). If this function returns false, then method (2) is
297 // always used. The vector type, and the number of defined values, are
298 // provided.
299 virtual bool
300 shouldExpandBuildVectorWithShuffles(EVT /* VT */,
301 unsigned DefinedValues) const {
302 return DefinedValues < 3;
303 }
304
305 /// Return true if integer divide is usually cheaper than a sequence of
306 /// several shifts, adds, and multiplies for this target.
307 /// The definition of "cheaper" may depend on whether we're optimizing
308 /// for speed or for size.
309 virtual bool isIntDivCheap(EVT VT, AttributeList Attr) const { return false; }
310
311 /// Return true if the target can handle a standalone remainder operation.
312 virtual bool hasStandaloneRem(EVT VT) const {
313 return true;
314 }
315
316 /// Return true if SQRT(X) shouldn't be replaced with X*RSQRT(X).
317 virtual bool isFsqrtCheap(SDValue X, SelectionDAG &DAG) const {
318 // Default behavior is to replace SQRT(X) with X*RSQRT(X).
319 return false;
320 }
321
322 /// Reciprocal estimate status values used by the functions below.
323 enum ReciprocalEstimate : int {
324 Unspecified = -1,
325 Disabled = 0,
326 Enabled = 1
327 };
328
329 /// Return a ReciprocalEstimate enum value for a square root of the given type
330 /// based on the function's attributes. If the operation is not overridden by
331 /// the function's attributes, "Unspecified" is returned and target defaults
332 /// are expected to be used for instruction selection.
333 int getRecipEstimateSqrtEnabled(EVT VT, MachineFunction &MF) const;
334
335 /// Return a ReciprocalEstimate enum value for a division of the given type
336 /// based on the function's attributes. If the operation is not overridden by
337 /// the function's attributes, "Unspecified" is returned and target defaults
338 /// are expected to be used for instruction selection.
339 int getRecipEstimateDivEnabled(EVT VT, MachineFunction &MF) const;
340
341 /// Return the refinement step count for a square root of the given type based
342 /// on the function's attributes. If the operation is not overridden by
343 /// the function's attributes, "Unspecified" is returned and target defaults
344 /// are expected to be used for instruction selection.
345 int getSqrtRefinementSteps(EVT VT, MachineFunction &MF) const;
346
347 /// Return the refinement step count for a division of the given type based
348 /// on the function's attributes. If the operation is not overridden by
349 /// the function's attributes, "Unspecified" is returned and target defaults
350 /// are expected to be used for instruction selection.
351 int getDivRefinementSteps(EVT VT, MachineFunction &MF) const;
352
353 /// Returns true if target has indicated at least one type should be bypassed.
354 bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
355
356 /// Returns map of slow types for division or remainder with corresponding
357 /// fast types
358 const DenseMap<unsigned int, unsigned int> &getBypassSlowDivWidths() const {
359 return BypassSlowDivWidths;
360 }
361
362 /// Return true if Flow Control is an expensive operation that should be
363 /// avoided.
364 bool isJumpExpensive() const { return JumpIsExpensive; }
365
366 /// Return true if selects are only cheaper than branches if the branch is
367 /// unlikely to be predicted right.
368 bool isPredictableSelectExpensive() const {
369 return PredictableSelectIsExpensive;
370 }
371
372 /// If a branch or a select condition is skewed in one direction by more than
373 /// this factor, it is very likely to be predicted correctly.
374 virtual BranchProbability getPredictableBranchThreshold() const;
375
376 /// Return true if the following transform is beneficial:
377 /// fold (conv (load x)) -> (load (conv*)x)
378 /// On architectures that don't natively support some vector loads
379 /// efficiently, casting the load to a smaller vector of larger types and
380 /// loading is more efficient, however, this can be undone by optimizations in
381 /// dag combiner.
382 virtual bool isLoadBitCastBeneficial(EVT LoadVT,
383 EVT BitcastVT) const {
384 // Don't do if we could do an indexed load on the original type, but not on
385 // the new one.
386 if (!LoadVT.isSimple() || !BitcastVT.isSimple())
387 return true;
388
389 MVT LoadMVT = LoadVT.getSimpleVT();
390
391 // Don't bother doing this if it's just going to be promoted again later, as
392 // doing so might interfere with other combines.
393 if (getOperationAction(ISD::LOAD, LoadMVT) == Promote &&
394 getTypeToPromoteTo(ISD::LOAD, LoadMVT) == BitcastVT.getSimpleVT())
395 return false;
396
397 return true;
398 }
399
400 /// Return true if the following transform is beneficial:
401 /// (store (y (conv x)), y*)) -> (store x, (x*))
402 virtual bool isStoreBitCastBeneficial(EVT StoreVT, EVT BitcastVT) const {
403 // Default to the same logic as loads.
404 return isLoadBitCastBeneficial(StoreVT, BitcastVT);
405 }
406
407 /// Return true if it is expected to be cheaper to do a store of a non-zero
408 /// vector constant with the given size and type for the address space than to
409 /// store the individual scalar element constants.
410 virtual bool storeOfVectorConstantIsCheap(EVT MemVT,
411 unsigned NumElem,
412 unsigned AddrSpace) const {
413 return false;
414 }
415
416 /// Allow store merging after legalization in addition to before legalization.
417 /// This may catch stores that do not exist earlier (eg, stores created from
418 /// intrinsics).
419 virtual bool mergeStoresAfterLegalization() const { return true; }
420
421 /// Returns if it's reasonable to merge stores to MemVT size.
422 virtual bool canMergeStoresTo(unsigned AS, EVT MemVT,
423 const SelectionDAG &DAG) const {
424 return true;
425 }
426
427 /// Return true if it is cheap to speculate a call to intrinsic cttz.
428 virtual bool isCheapToSpeculateCttz() const {
429 return false;
430 }
431
432 /// Return true if it is cheap to speculate a call to intrinsic ctlz.
433 virtual bool isCheapToSpeculateCtlz() const {
434 return false;
435 }
436
437 /// Return true if ctlz instruction is fast.
438 virtual bool isCtlzFast() const {
439 return false;
440 }
441
442 /// Return true if it is safe to transform an integer-domain bitwise operation
443 /// into the equivalent floating-point operation. This should be set to true
444 /// if the target has IEEE-754-compliant fabs/fneg operations for the input
445 /// type.
446 virtual bool hasBitPreservingFPLogic(EVT VT) const {
447 return false;
448 }
449
450 /// Return true if it is cheaper to split the store of a merged int val
451 /// from a pair of smaller values into multiple stores.
452 virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const {
453 return false;
454 }
455
456 /// Return if the target supports combining a
457 /// chain like:
458 /// \code
459 /// %andResult = and %val1, #mask
460 /// %icmpResult = icmp %andResult, 0
461 /// \endcode
462 /// into a single machine instruction of a form like:
463 /// \code
464 /// cc = test %register, #mask
465 /// \endcode
466 virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
467 return false;
468 }
469
470 /// Use bitwise logic to make pairs of compares more efficient. For example:
471 /// and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
472 /// This should be true when it takes more than one instruction to lower
473 /// setcc (cmp+set on x86 scalar), when bitwise ops are faster than logic on
474 /// condition bits (crand on PowerPC), and/or when reducing cmp+br is a win.
475 virtual bool convertSetCCLogicToBitwiseLogic(EVT VT) const {
476 return false;
477 }
478
479 /// Return the preferred operand type if the target has a quick way to compare
480 /// integer values of the given size. Assume that any legal integer type can
481 /// be compared efficiently. Targets may override this to allow illegal wide
482 /// types to return a vector type if there is support to compare that type.
483 virtual MVT hasFastEqualityCompare(unsigned NumBits) const {
484 MVT VT = MVT::getIntegerVT(NumBits);
485 return isTypeLegal(VT) ? VT : MVT::INVALID_SIMPLE_VALUE_TYPE;
486 }
487
488 /// Return true if the target should transform:
489 /// (X & Y) == Y ---> (~X & Y) == 0
490 /// (X & Y) != Y ---> (~X & Y) != 0
491 ///
492 /// This may be profitable if the target has a bitwise and-not operation that
493 /// sets comparison flags. A target may want to limit the transformation based
494 /// on the type of Y or if Y is a constant.
495 ///
496 /// Note that the transform will not occur if Y is known to be a power-of-2
497 /// because a mask and compare of a single bit can be handled by inverting the
498 /// predicate, for example:
499 /// (X & 8) == 8 ---> (X & 8) != 0
500 virtual bool hasAndNotCompare(SDValue Y) const {
501 return false;
502 }
503
504 /// Return true if the target has a bitwise and-not operation:
505 /// X = ~A & B
506 /// This can be used to simplify select or other instructions.
507 virtual bool hasAndNot(SDValue X) const {
508 // If the target has the more complex version of this operation, assume that
509 // it has this operation too.
510 return hasAndNotCompare(X);
511 }
512
513 /// There are two ways to clear extreme bits (either low or high):
514 /// Mask: x & (-1 << y) (the instcombine canonical form)
515 /// Shifts: x >> y << y
516 /// Return true if the variant with 2 shifts is preferred.
517 /// Return false if there is no preference.
518 virtual bool preferShiftsToClearExtremeBits(SDValue X) const {
519 // By default, let's assume that no one prefers shifts.
520 return false;
521 }
522
523 /// Should we tranform the IR-optimal check for whether given truncation
524 /// down into KeptBits would be truncating or not:
525 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
526 /// Into it's more traditional form:
527 /// ((%x << C) a>> C) dstcond %x
528 /// Return true if we should transform.
529 /// Return false if there is no preference.
530 virtual bool shouldTransformSignedTruncationCheck(EVT XVT,
531 unsigned KeptBits) const {
532 // By default, let's assume that no one prefers shifts.
533 return false;
534 }
535
536 /// Return true if the target wants to use the optimization that
537 /// turns ext(promotableInst1(...(promotableInstN(load)))) into
538 /// promotedInst1(...(promotedInstN(ext(load)))).
539 bool enableExtLdPromotion() const { return EnableExtLdPromotion; }
540
541 /// Return true if the target can combine store(extractelement VectorTy,
542 /// Idx).
543 /// \p Cost[out] gives the cost of that transformation when this is true.
544 virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
545 unsigned &Cost) const {
546 return false;
547 }
548
549 /// Return true if inserting a scalar into a variable element of an undef
550 /// vector is more efficiently handled by splatting the scalar instead.
551 virtual bool shouldSplatInsEltVarIndex(EVT) const {
552 return false;
553 }
554
555 /// Return true if target supports floating point exceptions.
556 bool hasFloatingPointExceptions() const {
557 return HasFloatingPointExceptions;
558 }
559
560 /// Return true if target always beneficiates from combining into FMA for a
561 /// given value type. This must typically return false on targets where FMA
562 /// takes more cycles to execute than FADD.
563 virtual bool enableAggressiveFMAFusion(EVT VT) const {
564 return false;
565 }
566
567 /// Return the ValueType of the result of SETCC operations.
568 virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context,
569 EVT VT) const;
570
571 /// Return the ValueType for comparison libcalls. Comparions libcalls include
572 /// floating point comparion calls, and Ordered/Unordered check calls on
573 /// floating point numbers.
574 virtual
575 MVT::SimpleValueType getCmpLibcallReturnType() const;
576
577 /// For targets without i1 registers, this gives the nature of the high-bits
578 /// of boolean values held in types wider than i1.
579 ///
580 /// "Boolean values" are special true/false values produced by nodes like
581 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
582 /// Not to be confused with general values promoted from i1. Some cpus
583 /// distinguish between vectors of boolean and scalars; the isVec parameter
584 /// selects between the two kinds. For example on X86 a scalar boolean should
585 /// be zero extended from i1, while the elements of a vector of booleans
586 /// should be sign extended from i1.
587 ///
588 /// Some cpus also treat floating point types the same way as they treat
589 /// vectors instead of the way they treat scalars.
590 BooleanContent getBooleanContents(bool isVec, bool isFloat) const {
591 if (isVec)
592 return BooleanVectorContents;
593 return isFloat ? BooleanFloatContents : BooleanContents;
594 }
595
596 BooleanContent getBooleanContents(EVT Type) const {
597 return getBooleanContents(Type.isVector(), Type.isFloatingPoint());
598 }
599
600 /// Return target scheduling preference.
601 Sched::Preference getSchedulingPreference() const {
602 return SchedPreferenceInfo;
603 }
604
605 /// Some scheduler, e.g. hybrid, can switch to different scheduling heuristics
606 /// for different nodes. This function returns the preference (or none) for
607 /// the given node.
608 virtual Sched::Preference getSchedulingPreference(SDNode *) const {
609 return Sched::None;
610 }
611
612 /// Return the register class that should be used for the specified value
613 /// type.
614 virtual const TargetRegisterClass *getRegClassFor(MVT VT) const {
615 const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
616 assert(RC && "This value type is not natively supported!")((RC && "This value type is not natively supported!")
? static_cast<void> (0) : __assert_fail ("RC && \"This value type is not natively supported!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 616, __PRETTY_FUNCTION__))
;
617 return RC;
618 }
619
620 /// Return the 'representative' register class for the specified value
621 /// type.
622 ///
623 /// The 'representative' register class is the largest legal super-reg
624 /// register class for the register class of the value type. For example, on
625 /// i386 the rep register class for i8, i16, and i32 are GR32; while the rep
626 /// register class is GR64 on x86_64.
627 virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
628 const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
629 return RC;
630 }
631
632 /// Return the cost of the 'representative' register class for the specified
633 /// value type.
634 virtual uint8_t getRepRegClassCostFor(MVT VT) const {
635 return RepRegClassCostForVT[VT.SimpleTy];
636 }
637
638 /// Return true if the target has native support for the specified value type.
639 /// This means that it has a register that directly holds it without
640 /// promotions or expansions.
641 bool isTypeLegal(EVT VT) const {
642 assert(!VT.isSimple() ||((!VT.isSimple() || (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof
(RegClassForVT)) ? static_cast<void> (0) : __assert_fail
("!VT.isSimple() || (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT)"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 643, __PRETTY_FUNCTION__))
643 (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT))((!VT.isSimple() || (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof
(RegClassForVT)) ? static_cast<void> (0) : __assert_fail
("!VT.isSimple() || (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT)"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 643, __PRETTY_FUNCTION__))
;
644 return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != nullptr;
645 }
646
647 class ValueTypeActionImpl {
648 /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
649 /// that indicates how instruction selection should deal with the type.
650 LegalizeTypeAction ValueTypeActions[MVT::LAST_VALUETYPE];
651
652 public:
653 ValueTypeActionImpl() {
654 std::fill(std::begin(ValueTypeActions), std::end(ValueTypeActions),
655 TypeLegal);
656 }
657
658 LegalizeTypeAction getTypeAction(MVT VT) const {
659 return ValueTypeActions[VT.SimpleTy];
660 }
661
662 void setTypeAction(MVT VT, LegalizeTypeAction Action) {
663 ValueTypeActions[VT.SimpleTy] = Action;
664 }
665 };
666
667 const ValueTypeActionImpl &getValueTypeActions() const {
668 return ValueTypeActions;
669 }
670
671 /// Return how we should legalize values of this type, either it is already
672 /// legal (return 'Legal') or we need to promote it to a larger type (return
673 /// 'Promote'), or we need to expand it into multiple registers of smaller
674 /// integer type (return 'Expand'). 'Custom' is not an option.
675 LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const {
676 return getTypeConversion(Context, VT).first;
677 }
678 LegalizeTypeAction getTypeAction(MVT VT) const {
679 return ValueTypeActions.getTypeAction(VT);
680 }
681
682 /// For types supported by the target, this is an identity function. For
683 /// types that must be promoted to larger types, this returns the larger type
684 /// to promote to. For integer types that are larger than the largest integer
685 /// register, this contains one step in the expansion to get to the smaller
686 /// register. For illegal floating point types, this returns the integer type
687 /// to transform to.
688 EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
689 return getTypeConversion(Context, VT).second;
690 }
691
692 /// For types supported by the target, this is an identity function. For
693 /// types that must be expanded (i.e. integer types that are larger than the
694 /// largest integer register or illegal floating point types), this returns
695 /// the largest legal type it will be expanded to.
696 EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
697 assert(!VT.isVector())((!VT.isVector()) ? static_cast<void> (0) : __assert_fail
("!VT.isVector()", "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 697, __PRETTY_FUNCTION__))
;
698 while (true) {
699 switch (getTypeAction(Context, VT)) {
700 case TypeLegal:
701 return VT;
702 case TypeExpandInteger:
703 VT = getTypeToTransformTo(Context, VT);
704 break;
705 default:
706 llvm_unreachable("Type is not legal nor is it to be expanded!")::llvm::llvm_unreachable_internal("Type is not legal nor is it to be expanded!"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 706)
;
707 }
708 }
709 }
710
711 /// Vector types are broken down into some number of legal first class types.
712 /// For example, EVT::v8f32 maps to 2 EVT::v4f32 with Altivec or SSE1, or 8
713 /// promoted EVT::f64 values with the X86 FP stack. Similarly, EVT::v2i64
714 /// turns into 4 EVT::i32 values with both PPC and X86.
715 ///
716 /// This method returns the number of registers needed, and the VT for each
717 /// register. It also returns the VT and quantity of the intermediate values
718 /// before they are promoted/expanded.
719 unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
720 EVT &IntermediateVT,
721 unsigned &NumIntermediates,
722 MVT &RegisterVT) const;
723
724 /// Certain targets such as MIPS require that some types such as vectors are
725 /// always broken down into scalars in some contexts. This occurs even if the
726 /// vector type is legal.
727 virtual unsigned getVectorTypeBreakdownForCallingConv(
728 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
729 unsigned &NumIntermediates, MVT &RegisterVT) const {
730 return getVectorTypeBreakdown(Context, VT, IntermediateVT, NumIntermediates,
731 RegisterVT);
732 }
733
734 struct IntrinsicInfo {
735 unsigned opc = 0; // target opcode
736 EVT memVT; // memory VT
737
738 // value representing memory location
739 PointerUnion<const Value *, const PseudoSourceValue *> ptrVal;
740
741 int offset = 0; // offset off of ptrVal
742 unsigned size = 0; // the size of the memory location
743 // (taken from memVT if zero)
744 unsigned align = 1; // alignment
745
746 MachineMemOperand::Flags flags = MachineMemOperand::MONone;
747 IntrinsicInfo() = default;
748 };
749
750 /// Given an intrinsic, checks if on the target the intrinsic will need to map
751 /// to a MemIntrinsicNode (touches memory). If this is the case, it returns
752 /// true and store the intrinsic information into the IntrinsicInfo that was
753 /// passed to the function.
754 virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
755 MachineFunction &,
756 unsigned /*Intrinsic*/) const {
757 return false;
758 }
759
760 /// Returns true if the target can instruction select the specified FP
761 /// immediate natively. If false, the legalizer will materialize the FP
762 /// immediate as a load from a constant pool.
763 virtual bool isFPImmLegal(const APFloat &/*Imm*/, EVT /*VT*/) const {
764 return false;
765 }
766
767 /// Targets can use this to indicate that they only support *some*
768 /// VECTOR_SHUFFLE operations, those with specific masks. By default, if a
769 /// target supports the VECTOR_SHUFFLE node, all mask values are assumed to be
770 /// legal.
771 virtual bool isShuffleMaskLegal(ArrayRef<int> /*Mask*/, EVT /*VT*/) const {
772 return true;
773 }
774
775 /// Returns true if the operation can trap for the value type.
776 ///
777 /// VT must be a legal type. By default, we optimistically assume most
778 /// operations don't trap except for integer divide and remainder.
779 virtual bool canOpTrap(unsigned Op, EVT VT) const;
780
781 /// Similar to isShuffleMaskLegal. Targets can use this to indicate if there
782 /// is a suitable VECTOR_SHUFFLE that can be used to replace a VAND with a
783 /// constant pool entry.
784 virtual bool isVectorClearMaskLegal(ArrayRef<int> /*Mask*/,
785 EVT /*VT*/) const {
786 return false;
787 }
788
789 /// Return how this operation should be treated: either it is legal, needs to
790 /// be promoted to a larger size, needs to be expanded to some other code
791 /// sequence, or the target has a custom expander for it.
792 LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
793 if (VT.isExtended()) return Expand;
794 // If a target-specific SDNode requires legalization, require the target
795 // to provide custom legalization for it.
796 if (Op >= array_lengthof(OpActions[0])) return Custom;
797 return OpActions[(unsigned)VT.getSimpleVT().SimpleTy][Op];
798 }
799
800 LegalizeAction getStrictFPOperationAction(unsigned Op, EVT VT) const {
801 unsigned EqOpc;
802 switch (Op) {
803 default: llvm_unreachable("Unexpected FP pseudo-opcode")::llvm::llvm_unreachable_internal("Unexpected FP pseudo-opcode"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 803)
;
804 case ISD::STRICT_FADD: EqOpc = ISD::FADD; break;
805 case ISD::STRICT_FSUB: EqOpc = ISD::FSUB; break;
806 case ISD::STRICT_FMUL: EqOpc = ISD::FMUL; break;
807 case ISD::STRICT_FDIV: EqOpc = ISD::FDIV; break;
808 case ISD::STRICT_FREM: EqOpc = ISD::FREM; break;
809 case ISD::STRICT_FSQRT: EqOpc = ISD::FSQRT; break;
810 case ISD::STRICT_FPOW: EqOpc = ISD::FPOW; break;
811 case ISD::STRICT_FPOWI: EqOpc = ISD::FPOWI; break;
812 case ISD::STRICT_FMA: EqOpc = ISD::FMA; break;
813 case ISD::STRICT_FSIN: EqOpc = ISD::FSIN; break;
814 case ISD::STRICT_FCOS: EqOpc = ISD::FCOS; break;
815 case ISD::STRICT_FEXP: EqOpc = ISD::FEXP; break;
816 case ISD::STRICT_FEXP2: EqOpc = ISD::FEXP2; break;
817 case ISD::STRICT_FLOG: EqOpc = ISD::FLOG; break;
818 case ISD::STRICT_FLOG10: EqOpc = ISD::FLOG10; break;
819 case ISD::STRICT_FLOG2: EqOpc = ISD::FLOG2; break;
820 case ISD::STRICT_FRINT: EqOpc = ISD::FRINT; break;
821 case ISD::STRICT_FNEARBYINT: EqOpc = ISD::FNEARBYINT; break;
822 }
823
824 auto Action = getOperationAction(EqOpc, VT);
825
826 // We don't currently handle Custom or Promote for strict FP pseudo-ops.
827 // For now, we just expand for those cases.
828 if (Action != Legal)
829 Action = Expand;
830
831 return Action;
832 }
833
834 /// Return true if the specified operation is legal on this target or can be
835 /// made legal with custom lowering. This is used to help guide high-level
836 /// lowering decisions.
837 bool isOperationLegalOrCustom(unsigned Op, EVT VT) const {
838 return (VT == MVT::Other || isTypeLegal(VT)) &&
839 (getOperationAction(Op, VT) == Legal ||
840 getOperationAction(Op, VT) == Custom);
841 }
842
843 /// Return true if the specified operation is legal on this target or can be
844 /// made legal using promotion. This is used to help guide high-level lowering
845 /// decisions.
846 bool isOperationLegalOrPromote(unsigned Op, EVT VT) const {
847 return (VT == MVT::Other || isTypeLegal(VT)) &&
848 (getOperationAction(Op, VT) == Legal ||
849 getOperationAction(Op, VT) == Promote);
850 }
851
852 /// Return true if the specified operation is legal on this target or can be
853 /// made legal with custom lowering or using promotion. This is used to help
854 /// guide high-level lowering decisions.
855 bool isOperationLegalOrCustomOrPromote(unsigned Op, EVT VT) const {
856 return (VT == MVT::Other || isTypeLegal(VT)) &&
857 (getOperationAction(Op, VT) == Legal ||
858 getOperationAction(Op, VT) == Custom ||
859 getOperationAction(Op, VT) == Promote);
860 }
861
862 /// Return true if the operation uses custom lowering, regardless of whether
863 /// the type is legal or not.
864 bool isOperationCustom(unsigned Op, EVT VT) const {
865 return getOperationAction(Op, VT) == Custom;
866 }
867
868 /// Return true if lowering to a jump table is allowed.
869 virtual bool areJTsAllowed(const Function *Fn) const {
870 if (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true")
871 return false;
872
873 return isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
874 isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
875 }
876
877 /// Check whether the range [Low,High] fits in a machine word.
878 bool rangeFitsInWord(const APInt &Low, const APInt &High,
879 const DataLayout &DL) const {
880 // FIXME: Using the pointer type doesn't seem ideal.
881 uint64_t BW = DL.getIndexSizeInBits(0u);
882 uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX(18446744073709551615UL) - 1) + 1;
883 return Range <= BW;
884 }
885
886 /// Return true if lowering to a jump table is suitable for a set of case
887 /// clusters which may contain \p NumCases cases, \p Range range of values.
888 /// FIXME: This function check the maximum table size and density, but the
889 /// minimum size is not checked. It would be nice if the minimum size is
890 /// also combined within this function. Currently, the minimum size check is
891 /// performed in findJumpTable() in SelectionDAGBuiler and
892 /// getEstimatedNumberOfCaseClusters() in BasicTTIImpl.
893 virtual bool isSuitableForJumpTable(const SwitchInst *SI, uint64_t NumCases,
894 uint64_t Range) const {
895 const bool OptForSize = SI->getParent()->getParent()->optForSize();
896 const unsigned MinDensity = getMinimumJumpTableDensity(OptForSize);
897 const unsigned MaxJumpTableSize =
898 OptForSize || getMaximumJumpTableSize() == 0
899 ? UINT_MAX(2147483647 *2U +1U)
900 : getMaximumJumpTableSize();
901 // Check whether a range of clusters is dense enough for a jump table.
902 if (Range <= MaxJumpTableSize &&
903 (NumCases * 100 >= Range * MinDensity)) {
904 return true;
905 }
906 return false;
907 }
908
909 /// Return true if lowering to a bit test is suitable for a set of case
910 /// clusters which contains \p NumDests unique destinations, \p Low and
911 /// \p High as its lowest and highest case values, and expects \p NumCmps
912 /// case value comparisons. Check if the number of destinations, comparison
913 /// metric, and range are all suitable.
914 bool isSuitableForBitTests(unsigned NumDests, unsigned NumCmps,
915 const APInt &Low, const APInt &High,
916 const DataLayout &DL) const {
917 // FIXME: I don't think NumCmps is the correct metric: a single case and a
918 // range of cases both require only one branch to lower. Just looking at the
919 // number of clusters and destinations should be enough to decide whether to
920 // build bit tests.
921
922 // To lower a range with bit tests, the range must fit the bitwidth of a
923 // machine word.
924 if (!rangeFitsInWord(Low, High, DL))
925 return false;
926
927 // Decide whether it's profitable to lower this range with bit tests. Each
928 // destination requires a bit test and branch, and there is an overall range
929 // check branch. For a small number of clusters, separate comparisons might
930 // be cheaper, and for many destinations, splitting the range might be
931 // better.
932 return (NumDests == 1 && NumCmps >= 3) || (NumDests == 2 && NumCmps >= 5) ||
933 (NumDests == 3 && NumCmps >= 6);
934 }
935
936 /// Return true if the specified operation is illegal on this target or
937 /// unlikely to be made legal with custom lowering. This is used to help guide
938 /// high-level lowering decisions.
939 bool isOperationExpand(unsigned Op, EVT VT) const {
940 return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
941 }
942
943 /// Return true if the specified operation is legal on this target.
944 bool isOperationLegal(unsigned Op, EVT VT) const {
945 return (VT == MVT::Other || isTypeLegal(VT)) &&
946 getOperationAction(Op, VT) == Legal;
947 }
948
949 /// Return how this load with extension should be treated: either it is legal,
950 /// needs to be promoted to a larger size, needs to be expanded to some other
951 /// code sequence, or the target has a custom expander for it.
952 LegalizeAction getLoadExtAction(unsigned ExtType, EVT ValVT,
953 EVT MemVT) const {
954 if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
955 unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
956 unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
957 assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValI < MVT::LAST_VALUETYPE &&((ExtType < ISD::LAST_LOADEXT_TYPE && ValI < MVT
::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE &&
"Table isn't big enough!") ? static_cast<void> (0) : __assert_fail
("ExtType < ISD::LAST_LOADEXT_TYPE && ValI < MVT::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 958, __PRETTY_FUNCTION__))
958 MemI < MVT::LAST_VALUETYPE && "Table isn't big enough!")((ExtType < ISD::LAST_LOADEXT_TYPE && ValI < MVT
::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE &&
"Table isn't big enough!") ? static_cast<void> (0) : __assert_fail
("ExtType < ISD::LAST_LOADEXT_TYPE && ValI < MVT::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 958, __PRETTY_FUNCTION__))
;
959 unsigned Shift = 4 * ExtType;
960 return (LegalizeAction)((LoadExtActions[ValI][MemI] >> Shift) & 0xf);
961 }
962
963 /// Return true if the specified load with extension is legal on this target.
964 bool isLoadExtLegal(unsigned ExtType, EVT ValVT, EVT MemVT) const {
965 return getLoadExtAction(ExtType, ValVT, MemVT) == Legal;
966 }
967
968 /// Return true if the specified load with extension is legal or custom
969 /// on this target.
970 bool isLoadExtLegalOrCustom(unsigned ExtType, EVT ValVT, EVT MemVT) const {
971 return getLoadExtAction(ExtType, ValVT, MemVT) == Legal ||
972 getLoadExtAction(ExtType, ValVT, MemVT) == Custom;
973 }
974
975 /// Return how this store with truncation should be treated: either it is
976 /// legal, needs to be promoted to a larger size, needs to be expanded to some
977 /// other code sequence, or the target has a custom expander for it.
978 LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT) const {
979 if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
980 unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
981 unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
982 assert(ValI < MVT::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE &&((ValI < MVT::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE
&& "Table isn't big enough!") ? static_cast<void>
(0) : __assert_fail ("ValI < MVT::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 983, __PRETTY_FUNCTION__))
983 "Table isn't big enough!")((ValI < MVT::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE
&& "Table isn't big enough!") ? static_cast<void>
(0) : __assert_fail ("ValI < MVT::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 983, __PRETTY_FUNCTION__))
;
984 return TruncStoreActions[ValI][MemI];
985 }
986
987 /// Return true if the specified store with truncation is legal on this
988 /// target.
989 bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
990 return isTypeLegal(ValVT) && getTruncStoreAction(ValVT, MemVT) == Legal;
991 }
992
993 /// Return true if the specified store with truncation has solution on this
994 /// target.
995 bool isTruncStoreLegalOrCustom(EVT ValVT, EVT MemVT) const {
996 return isTypeLegal(ValVT) &&
997 (getTruncStoreAction(ValVT, MemVT) == Legal ||
998 getTruncStoreAction(ValVT, MemVT) == Custom);
999 }
1000
1001 /// Return how the indexed load should be treated: either it is legal, needs
1002 /// to be promoted to a larger size, needs to be expanded to some other code
1003 /// sequence, or the target has a custom expander for it.
1004 LegalizeAction
1005 getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
1006 assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&((IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid()
&& "Table isn't big enough!") ? static_cast<void>
(0) : __assert_fail ("IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1007, __PRETTY_FUNCTION__))
1007 "Table isn't big enough!")((IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid()
&& "Table isn't big enough!") ? static_cast<void>
(0) : __assert_fail ("IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1007, __PRETTY_FUNCTION__))
;
1008 unsigned Ty = (unsigned)VT.SimpleTy;
1009 return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] & 0xf0) >> 4);
1010 }
1011
1012 /// Return true if the specified indexed load is legal on this target.
1013 bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
1014 return VT.isSimple() &&
1015 (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
1016 getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
1017 }
1018
1019 /// Return how the indexed store should be treated: either it is legal, needs
1020 /// to be promoted to a larger size, needs to be expanded to some other code
1021 /// sequence, or the target has a custom expander for it.
1022 LegalizeAction
1023 getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
1024 assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&((IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid()
&& "Table isn't big enough!") ? static_cast<void>
(0) : __assert_fail ("IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1025, __PRETTY_FUNCTION__))
1025 "Table isn't big enough!")((IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid()
&& "Table isn't big enough!") ? static_cast<void>
(0) : __assert_fail ("IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1025, __PRETTY_FUNCTION__))
;
1026 unsigned Ty = (unsigned)VT.SimpleTy;
1027 return (LegalizeAction)(IndexedModeActions[Ty][IdxMode] & 0x0f);
1028 }
1029
1030 /// Return true if the specified indexed load is legal on this target.
1031 bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
1032 return VT.isSimple() &&
1033 (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
1034 getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
1035 }
1036
1037 /// Return how the condition code should be treated: either it is legal, needs
1038 /// to be expanded to some other code sequence, or the target has a custom
1039 /// expander for it.
1040 LegalizeAction
1041 getCondCodeAction(ISD::CondCode CC, MVT VT) const {
1042 assert((unsigned)CC < array_lengthof(CondCodeActions) &&(((unsigned)CC < array_lengthof(CondCodeActions) &&
((unsigned)VT.SimpleTy >> 3) < array_lengthof(CondCodeActions
[0]) && "Table isn't big enough!") ? static_cast<void
> (0) : __assert_fail ("(unsigned)CC < array_lengthof(CondCodeActions) && ((unsigned)VT.SimpleTy >> 3) < array_lengthof(CondCodeActions[0]) && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1044, __PRETTY_FUNCTION__))
1043 ((unsigned)VT.SimpleTy >> 3) < array_lengthof(CondCodeActions[0]) &&(((unsigned)CC < array_lengthof(CondCodeActions) &&
((unsigned)VT.SimpleTy >> 3) < array_lengthof(CondCodeActions
[0]) && "Table isn't big enough!") ? static_cast<void
> (0) : __assert_fail ("(unsigned)CC < array_lengthof(CondCodeActions) && ((unsigned)VT.SimpleTy >> 3) < array_lengthof(CondCodeActions[0]) && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1044, __PRETTY_FUNCTION__))
1044 "Table isn't big enough!")(((unsigned)CC < array_lengthof(CondCodeActions) &&
((unsigned)VT.SimpleTy >> 3) < array_lengthof(CondCodeActions
[0]) && "Table isn't big enough!") ? static_cast<void
> (0) : __assert_fail ("(unsigned)CC < array_lengthof(CondCodeActions) && ((unsigned)VT.SimpleTy >> 3) < array_lengthof(CondCodeActions[0]) && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1044, __PRETTY_FUNCTION__))
;
1045 // See setCondCodeAction for how this is encoded.
1046 uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
1047 uint32_t Value = CondCodeActions[CC][VT.SimpleTy >> 3];
1048 LegalizeAction Action = (LegalizeAction) ((Value >> Shift) & 0xF);
1049 assert(Action != Promote && "Can't promote condition code!")((Action != Promote && "Can't promote condition code!"
) ? static_cast<void> (0) : __assert_fail ("Action != Promote && \"Can't promote condition code!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1049, __PRETTY_FUNCTION__))
;
1050 return Action;
1051 }
1052
1053 /// Return true if the specified condition code is legal on this target.
1054 bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
1055 return getCondCodeAction(CC, VT) == Legal;
1056 }
1057
1058 /// Return true if the specified condition code is legal or custom on this
1059 /// target.
1060 bool isCondCodeLegalOrCustom(ISD::CondCode CC, MVT VT) const {
1061 return getCondCodeAction(CC, VT) == Legal ||
1062 getCondCodeAction(CC, VT) == Custom;
1063 }
1064
1065 /// If the action for this operation is to promote, this method returns the
1066 /// ValueType to promote to.
1067 MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
1068 assert(getOperationAction(Op, VT) == Promote &&((getOperationAction(Op, VT) == Promote && "This operation isn't promoted!"
) ? static_cast<void> (0) : __assert_fail ("getOperationAction(Op, VT) == Promote && \"This operation isn't promoted!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1069, __PRETTY_FUNCTION__))
1069 "This operation isn't promoted!")((getOperationAction(Op, VT) == Promote && "This operation isn't promoted!"
) ? static_cast<void> (0) : __assert_fail ("getOperationAction(Op, VT) == Promote && \"This operation isn't promoted!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1069, __PRETTY_FUNCTION__))
;
1070
1071 // See if this has an explicit type specified.
1072 std::map<std::pair<unsigned, MVT::SimpleValueType>,
1073 MVT::SimpleValueType>::const_iterator PTTI =
1074 PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
1075 if (PTTI != PromoteToType.end()) return PTTI->second;
1076
1077 assert((VT.isInteger() || VT.isFloatingPoint()) &&(((VT.isInteger() || VT.isFloatingPoint()) && "Cannot autopromote this type, add it with AddPromotedToType."
) ? static_cast<void> (0) : __assert_fail ("(VT.isInteger() || VT.isFloatingPoint()) && \"Cannot autopromote this type, add it with AddPromotedToType.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1078, __PRETTY_FUNCTION__))
1078 "Cannot autopromote this type, add it with AddPromotedToType.")(((VT.isInteger() || VT.isFloatingPoint()) && "Cannot autopromote this type, add it with AddPromotedToType."
) ? static_cast<void> (0) : __assert_fail ("(VT.isInteger() || VT.isFloatingPoint()) && \"Cannot autopromote this type, add it with AddPromotedToType.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1078, __PRETTY_FUNCTION__))
;
1079
1080 MVT NVT = VT;
1081 do {
1082 NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
1083 assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&((NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid
&& "Didn't find type to promote to!") ? static_cast<
void> (0) : __assert_fail ("NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid && \"Didn't find type to promote to!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1084, __PRETTY_FUNCTION__))
1084 "Didn't find type to promote to!")((NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid
&& "Didn't find type to promote to!") ? static_cast<
void> (0) : __assert_fail ("NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid && \"Didn't find type to promote to!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1084, __PRETTY_FUNCTION__))
;
1085 } while (!isTypeLegal(NVT) ||
1086 getOperationAction(Op, NVT) == Promote);
1087 return NVT;
1088 }
1089
1090 /// Return the EVT corresponding to this LLVM type. This is fixed by the LLVM
1091 /// operations except for the pointer size. If AllowUnknown is true, this
1092 /// will return MVT::Other for types with no EVT counterpart (e.g. structs),
1093 /// otherwise it will assert.
1094 EVT getValueType(const DataLayout &DL, Type *Ty,
1095 bool AllowUnknown = false) const {
1096 // Lower scalar pointers to native pointer types.
1097 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
16
Taking false branch
1098 return getPointerTy(DL, PTy->getAddressSpace());
1099
1100 if (Ty->isVectorTy()) {
17
Called C++ object pointer is null
1101 VectorType *VTy = cast<VectorType>(Ty);
1102 Type *Elm = VTy->getElementType();
1103 // Lower vectors of pointers to native pointer types.
1104 if (PointerType *PT = dyn_cast<PointerType>(Elm)) {
1105 EVT PointerTy(getPointerTy(DL, PT->getAddressSpace()));
1106 Elm = PointerTy.getTypeForEVT(Ty->getContext());
1107 }
1108
1109 return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
1110 VTy->getNumElements());
1111 }
1112 return EVT::getEVT(Ty, AllowUnknown);
1113 }
1114
1115 /// Return the MVT corresponding to this LLVM type. See getValueType.
1116 MVT getSimpleValueType(const DataLayout &DL, Type *Ty,
1117 bool AllowUnknown = false) const {
1118 return getValueType(DL, Ty, AllowUnknown).getSimpleVT();
1119 }
1120
1121 /// Return the desired alignment for ByVal or InAlloca aggregate function
1122 /// arguments in the caller parameter area. This is the actual alignment, not
1123 /// its logarithm.
1124 virtual unsigned getByValTypeAlignment(Type *Ty, const DataLayout &DL) const;
1125
1126 /// Return the type of registers that this ValueType will eventually require.
1127 MVT getRegisterType(MVT VT) const {
1128 assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT))(((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT
)) ? static_cast<void> (0) : __assert_fail ("(unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT)"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1128, __PRETTY_FUNCTION__))
;
1129 return RegisterTypeForVT[VT.SimpleTy];
1130 }
1131
1132 /// Return the type of registers that this ValueType will eventually require.
1133 MVT getRegisterType(LLVMContext &Context, EVT VT) const {
1134 if (VT.isSimple()) {
1135 assert((unsigned)VT.getSimpleVT().SimpleTy <(((unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegisterTypeForVT
)) ? static_cast<void> (0) : __assert_fail ("(unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegisterTypeForVT)"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1136, __PRETTY_FUNCTION__))
1136 array_lengthof(RegisterTypeForVT))(((unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegisterTypeForVT
)) ? static_cast<void> (0) : __assert_fail ("(unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegisterTypeForVT)"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1136, __PRETTY_FUNCTION__))
;
1137 return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
1138 }
1139 if (VT.isVector()) {
1140 EVT VT1;
1141 MVT RegisterVT;
1142 unsigned NumIntermediates;
1143 (void)getVectorTypeBreakdown(Context, VT, VT1,
1144 NumIntermediates, RegisterVT);
1145 return RegisterVT;
1146 }
1147 if (VT.isInteger()) {
1148 return getRegisterType(Context, getTypeToTransformTo(Context, VT));
1149 }
1150 llvm_unreachable("Unsupported extended type!")::llvm::llvm_unreachable_internal("Unsupported extended type!"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1150)
;
1151 }
1152
1153 /// Return the number of registers that this ValueType will eventually
1154 /// require.
1155 ///
1156 /// This is one for any types promoted to live in larger registers, but may be
1157 /// more than one for types (like i64) that are split into pieces. For types
1158 /// like i140, which are first promoted then expanded, it is the number of
1159 /// registers needed to hold all the bits of the original type. For an i140
1160 /// on a 32 bit machine this means 5 registers.
1161 unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
1162 if (VT.isSimple()) {
1163 assert((unsigned)VT.getSimpleVT().SimpleTy <(((unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(NumRegistersForVT
)) ? static_cast<void> (0) : __assert_fail ("(unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(NumRegistersForVT)"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1164, __PRETTY_FUNCTION__))
1164 array_lengthof(NumRegistersForVT))(((unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(NumRegistersForVT
)) ? static_cast<void> (0) : __assert_fail ("(unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(NumRegistersForVT)"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1164, __PRETTY_FUNCTION__))
;
1165 return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
1166 }
1167 if (VT.isVector()) {
1168 EVT VT1;
1169 MVT VT2;
1170 unsigned NumIntermediates;
1171 return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
1172 }
1173 if (VT.isInteger()) {
1174 unsigned BitWidth = VT.getSizeInBits();
1175 unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
1176 return (BitWidth + RegWidth - 1) / RegWidth;
1177 }
1178 llvm_unreachable("Unsupported extended type!")::llvm::llvm_unreachable_internal("Unsupported extended type!"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1178)
;
1179 }
1180
1181 /// Certain combinations of ABIs, Targets and features require that types
1182 /// are legal for some operations and not for other operations.
1183 /// For MIPS all vector types must be passed through the integer register set.
1184 virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context,
1185 CallingConv::ID CC, EVT VT) const {
1186 return getRegisterType(Context, VT);
1187 }
1188
1189 /// Certain targets require unusual breakdowns of certain types. For MIPS,
1190 /// this occurs when a vector type is used, as vector are passed through the
1191 /// integer register set.
1192 virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context,
1193 CallingConv::ID CC,
1194 EVT VT) const {
1195 return getNumRegisters(Context, VT);
1196 }
1197
1198 /// Certain targets have context senstive alignment requirements, where one
1199 /// type has the alignment requirement of another type.
1200 virtual unsigned getABIAlignmentForCallingConv(Type *ArgTy,
1201 DataLayout DL) const {
1202 return DL.getABITypeAlignment(ArgTy);
1203 }
1204
1205 /// If true, then instruction selection should seek to shrink the FP constant
1206 /// of the specified type to a smaller type in order to save space and / or
1207 /// reduce runtime.
1208 virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
1209
1210 // Return true if it is profitable to reduce the given load node to a smaller
1211 // type.
1212 //
1213 // e.g. (i16 (trunc (i32 (load x))) -> i16 load x should be performed
1214 virtual bool shouldReduceLoadWidth(SDNode *Load,
1215 ISD::LoadExtType ExtTy,
1216 EVT NewVT) const {
1217 return true;
1218 }
1219
1220 /// When splitting a value of the specified type into parts, does the Lo
1221 /// or Hi part come first? This usually follows the endianness, except
1222 /// for ppcf128, where the Hi part always comes first.
1223 bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const {
1224 return DL.isBigEndian() || VT == MVT::ppcf128;
1225 }
1226
1227 /// If true, the target has custom DAG combine transformations that it can
1228 /// perform for the specified node.
1229 bool hasTargetDAGCombine(ISD::NodeType NT) const {
1230 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray))((unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray
)) ? static_cast<void> (0) : __assert_fail ("unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray)"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1230, __PRETTY_FUNCTION__))
;
1231 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
1232 }
1233
1234 unsigned getGatherAllAliasesMaxDepth() const {
1235 return GatherAllAliasesMaxDepth;
1236 }
1237
1238 /// Returns the size of the platform's va_list object.
1239 virtual unsigned getVaListSizeInBits(const DataLayout &DL) const {
1240 return getPointerTy(DL).getSizeInBits();
1241 }
1242
1243 /// Get maximum # of store operations permitted for llvm.memset
1244 ///
1245 /// This function returns the maximum number of store operations permitted
1246 /// to replace a call to llvm.memset. The value is set by the target at the
1247 /// performance threshold for such a replacement. If OptSize is true,
1248 /// return the limit for functions that have OptSize attribute.
1249 unsigned getMaxStoresPerMemset(bool OptSize) const {
1250 return OptSize ? MaxStoresPerMemsetOptSize : MaxStoresPerMemset;
1251 }
1252
1253 /// Get maximum # of store operations permitted for llvm.memcpy
1254 ///
1255 /// This function returns the maximum number of store operations permitted
1256 /// to replace a call to llvm.memcpy. The value is set by the target at the
1257 /// performance threshold for such a replacement. If OptSize is true,
1258 /// return the limit for functions that have OptSize attribute.
1259 unsigned getMaxStoresPerMemcpy(bool OptSize) const {
1260 return OptSize ? MaxStoresPerMemcpyOptSize : MaxStoresPerMemcpy;
1261 }
1262
1263 /// \brief Get maximum # of store operations to be glued together
1264 ///
1265 /// This function returns the maximum number of store operations permitted
1266 /// to glue together during lowering of llvm.memcpy. The value is set by
1267 // the target at the performance threshold for such a replacement.
1268 virtual unsigned getMaxGluedStoresPerMemcpy() const {
1269 return MaxGluedStoresPerMemcpy;
1270 }
1271
1272 /// Get maximum # of load operations permitted for memcmp
1273 ///
1274 /// This function returns the maximum number of load operations permitted
1275 /// to replace a call to memcmp. The value is set by the target at the
1276 /// performance threshold for such a replacement. If OptSize is true,
1277 /// return the limit for functions that have OptSize attribute.
1278 unsigned getMaxExpandSizeMemcmp(bool OptSize) const {
1279 return OptSize ? MaxLoadsPerMemcmpOptSize : MaxLoadsPerMemcmp;
1280 }
1281
1282 /// For memcmp expansion when the memcmp result is only compared equal or
1283 /// not-equal to 0, allow up to this number of load pairs per block. As an
1284 /// example, this may allow 'memcmp(a, b, 3) == 0' in a single block:
1285 /// a0 = load2bytes &a[0]
1286 /// b0 = load2bytes &b[0]
1287 /// a2 = load1byte &a[2]
1288 /// b2 = load1byte &b[2]
1289 /// r = cmp eq (a0 ^ b0 | a2 ^ b2), 0
1290 virtual unsigned getMemcmpEqZeroLoadsPerBlock() const {
1291 return 1;
1292 }
1293
1294 /// Get maximum # of store operations permitted for llvm.memmove
1295 ///
1296 /// This function returns the maximum number of store operations permitted
1297 /// to replace a call to llvm.memmove. The value is set by the target at the
1298 /// performance threshold for such a replacement. If OptSize is true,
1299 /// return the limit for functions that have OptSize attribute.
1300 unsigned getMaxStoresPerMemmove(bool OptSize) const {
1301 return OptSize ? MaxStoresPerMemmoveOptSize : MaxStoresPerMemmove;
1302 }
1303
1304 /// Determine if the target supports unaligned memory accesses.
1305 ///
1306 /// This function returns true if the target allows unaligned memory accesses
1307 /// of the specified type in the given address space. If true, it also returns
1308 /// whether the unaligned memory access is "fast" in the last argument by
1309 /// reference. This is used, for example, in situations where an array
1310 /// copy/move/set is converted to a sequence of store operations. Its use
1311 /// helps to ensure that such replacements don't generate code that causes an
1312 /// alignment error (trap) on the target machine.
1313 virtual bool allowsMisalignedMemoryAccesses(EVT,
1314 unsigned AddrSpace = 0,
1315 unsigned Align = 1,
1316 bool * /*Fast*/ = nullptr) const {
1317 return false;
1318 }
1319
1320 /// Return true if the target supports a memory access of this type for the
1321 /// given address space and alignment. If the access is allowed, the optional
1322 /// final parameter returns if the access is also fast (as defined by the
1323 /// target).
1324 bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT,
1325 unsigned AddrSpace = 0, unsigned Alignment = 1,
1326 bool *Fast = nullptr) const;
1327
1328 /// Returns the target specific optimal type for load and store operations as
1329 /// a result of memset, memcpy, and memmove lowering.
1330 ///
1331 /// If DstAlign is zero that means it's safe to destination alignment can
1332 /// satisfy any constraint. Similarly if SrcAlign is zero it means there isn't
1333 /// a need to check it against alignment requirement, probably because the
1334 /// source does not need to be loaded. If 'IsMemset' is true, that means it's
1335 /// expanding a memset. If 'ZeroMemset' is true, that means it's a memset of
1336 /// zero. 'MemcpyStrSrc' indicates whether the memcpy source is constant so it
1337 /// does not need to be loaded. It returns EVT::Other if the type should be
1338 /// determined using generic target-independent logic.
1339 virtual EVT getOptimalMemOpType(uint64_t /*Size*/,
1340 unsigned /*DstAlign*/, unsigned /*SrcAlign*/,
1341 bool /*IsMemset*/,
1342 bool /*ZeroMemset*/,
1343 bool /*MemcpyStrSrc*/,
1344 MachineFunction &/*MF*/) const {
1345 return MVT::Other;
1346 }
1347
1348 /// Returns true if it's safe to use load / store of the specified type to
1349 /// expand memcpy / memset inline.
1350 ///
1351 /// This is mostly true for all types except for some special cases. For
1352 /// example, on X86 targets without SSE2 f64 load / store are done with fldl /
1353 /// fstpl which also does type conversion. Note the specified type doesn't
1354 /// have to be legal as the hook is used before type legalization.
1355 virtual bool isSafeMemOpType(MVT /*VT*/) const { return true; }
1356
1357 /// Determine if we should use _setjmp or setjmp to implement llvm.setjmp.
1358 bool usesUnderscoreSetJmp() const {
1359 return UseUnderscoreSetJmp;
1360 }
1361
1362 /// Determine if we should use _longjmp or longjmp to implement llvm.longjmp.
1363 bool usesUnderscoreLongJmp() const {
1364 return UseUnderscoreLongJmp;
1365 }
1366
1367 /// Return lower limit for number of blocks in a jump table.
1368 virtual unsigned getMinimumJumpTableEntries() const;
1369
1370 /// Return lower limit of the density in a jump table.
1371 unsigned getMinimumJumpTableDensity(bool OptForSize) const;
1372
1373 /// Return upper limit for number of entries in a jump table.
1374 /// Zero if no limit.
1375 unsigned getMaximumJumpTableSize() const;
1376
1377 virtual bool isJumpTableRelative() const {
1378 return TM.isPositionIndependent();
1379 }
1380
1381 /// If a physical register, this specifies the register that
1382 /// llvm.savestack/llvm.restorestack should save and restore.
1383 unsigned getStackPointerRegisterToSaveRestore() const {
1384 return StackPointerRegisterToSaveRestore;
1385 }
1386
1387 /// If a physical register, this returns the register that receives the
1388 /// exception address on entry to an EH pad.
1389 virtual unsigned
1390 getExceptionPointerRegister(const Constant *PersonalityFn) const {
1391 // 0 is guaranteed to be the NoRegister value on all targets
1392 return 0;
1393 }
1394
1395 /// If a physical register, this returns the register that receives the
1396 /// exception typeid on entry to a landing pad.
1397 virtual unsigned
1398 getExceptionSelectorRegister(const Constant *PersonalityFn) const {
1399 // 0 is guaranteed to be the NoRegister value on all targets
1400 return 0;
1401 }
1402
1403 virtual bool needsFixedCatchObjects() const {
1404 report_fatal_error("Funclet EH is not implemented for this target");
1405 }
1406
1407 /// Returns the target's jmp_buf size in bytes (if never set, the default is
1408 /// 200)
1409 unsigned getJumpBufSize() const {
1410 return JumpBufSize;
1411 }
1412
1413 /// Returns the target's jmp_buf alignment in bytes (if never set, the default
1414 /// is 0)
1415 unsigned getJumpBufAlignment() const {
1416 return JumpBufAlignment;
1417 }
1418
1419 /// Return the minimum stack alignment of an argument.
1420 unsigned getMinStackArgumentAlignment() const {
1421 return MinStackArgumentAlignment;
1422 }
1423
1424 /// Return the minimum function alignment.
1425 unsigned getMinFunctionAlignment() const {
1426 return MinFunctionAlignment;
1427 }
1428
1429 /// Return the preferred function alignment.
1430 unsigned getPrefFunctionAlignment() const {
1431 return PrefFunctionAlignment;
1432 }
1433
1434 /// Return the preferred loop alignment.
1435 virtual unsigned getPrefLoopAlignment(MachineLoop *ML = nullptr) const {
1436 return PrefLoopAlignment;
1437 }
1438
1439 /// Should loops be aligned even when the function is marked OptSize (but not
1440 /// MinSize).
1441 virtual bool alignLoopsWithOptSize() const {
1442 return false;
1443 }
1444
1445 /// If the target has a standard location for the stack protector guard,
1446 /// returns the address of that location. Otherwise, returns nullptr.
1447 /// DEPRECATED: please override useLoadStackGuardNode and customize
1448 /// LOAD_STACK_GUARD, or customize \@llvm.stackguard().
1449 virtual Value *getIRStackGuard(IRBuilder<> &IRB) const;
1450
1451 /// Inserts necessary declarations for SSP (stack protection) purpose.
1452 /// Should be used only when getIRStackGuard returns nullptr.
1453 virtual void insertSSPDeclarations(Module &M) const;
1454
1455 /// Return the variable that's previously inserted by insertSSPDeclarations,
1456 /// if any, otherwise return nullptr. Should be used only when
1457 /// getIRStackGuard returns nullptr.
1458 virtual Value *getSDagStackGuard(const Module &M) const;
1459
1460 /// If this function returns true, stack protection checks should XOR the
1461 /// frame pointer (or whichever pointer is used to address locals) into the
1462 /// stack guard value before checking it. getIRStackGuard must return nullptr
1463 /// if this returns true.
1464 virtual bool useStackGuardXorFP() const { return false; }
1465
1466 /// If the target has a standard stack protection check function that
1467 /// performs validation and error handling, returns the function. Otherwise,
1468 /// returns nullptr. Must be previously inserted by insertSSPDeclarations.
1469 /// Should be used only when getIRStackGuard returns nullptr.
1470 virtual Value *getSSPStackGuardCheck(const Module &M) const;
1471
1472protected:
1473 Value *getDefaultSafeStackPointerLocation(IRBuilder<> &IRB,
1474 bool UseTLS) const;
1475
1476public:
1477 /// Returns the target-specific address of the unsafe stack pointer.
1478 virtual Value *getSafeStackPointerLocation(IRBuilder<> &IRB) const;
1479
1480 /// Returns the name of the symbol used to emit stack probes or the empty
1481 /// string if not applicable.
1482 virtual StringRef getStackProbeSymbolName(MachineFunction &MF) const {
1483 return "";
1484 }
1485
1486 /// Returns true if a cast between SrcAS and DestAS is a noop.
1487 virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const {
1488 return false;
1489 }
1490
1491 /// Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g. we
1492 /// are happy to sink it into basic blocks.
1493 virtual bool isCheapAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const {
1494 return isNoopAddrSpaceCast(SrcAS, DestAS);
1495 }
1496
1497 /// Return true if the pointer arguments to CI should be aligned by aligning
1498 /// the object whose address is being passed. If so then MinSize is set to the
1499 /// minimum size the object must be to be aligned and PrefAlign is set to the
1500 /// preferred alignment.
1501 virtual bool shouldAlignPointerArgs(CallInst * /*CI*/, unsigned & /*MinSize*/,
1502 unsigned & /*PrefAlign*/) const {
1503 return false;
1504 }
1505
1506 //===--------------------------------------------------------------------===//
1507 /// \name Helpers for TargetTransformInfo implementations
1508 /// @{
1509
1510 /// Get the ISD node that corresponds to the Instruction class opcode.
1511 int InstructionOpcodeToISD(unsigned Opcode) const;
1512
1513 /// Estimate the cost of type-legalization and the legalized type.
1514 std::pair<int, MVT> getTypeLegalizationCost(const DataLayout &DL,
1515 Type *Ty) const;
1516
1517 /// @}
1518
1519 //===--------------------------------------------------------------------===//
1520 /// \name Helpers for atomic expansion.
1521 /// @{
1522
1523 /// Returns the maximum atomic operation size (in bits) supported by
1524 /// the backend. Atomic operations greater than this size (as well
1525 /// as ones that are not naturally aligned), will be expanded by
1526 /// AtomicExpandPass into an __atomic_* library call.
1527 unsigned getMaxAtomicSizeInBitsSupported() const {
1528 return MaxAtomicSizeInBitsSupported;
1529 }
1530
1531 /// Returns the size of the smallest cmpxchg or ll/sc instruction
1532 /// the backend supports. Any smaller operations are widened in
1533 /// AtomicExpandPass.
1534 ///
1535 /// Note that *unlike* operations above the maximum size, atomic ops
1536 /// are still natively supported below the minimum; they just
1537 /// require a more complex expansion.
1538 unsigned getMinCmpXchgSizeInBits() const { return MinCmpXchgSizeInBits; }
1539
1540 /// Whether the target supports unaligned atomic operations.
1541 bool supportsUnalignedAtomics() const { return SupportsUnalignedAtomics; }
1542
1543 /// Whether AtomicExpandPass should automatically insert fences and reduce
1544 /// ordering for this atomic. This should be true for most architectures with
1545 /// weak memory ordering. Defaults to false.
1546 virtual bool shouldInsertFencesForAtomic(const Instruction *I) const {
1547 return false;
1548 }
1549
1550 /// Perform a load-linked operation on Addr, returning a "Value *" with the
1551 /// corresponding pointee type. This may entail some non-trivial operations to
1552 /// truncate or reconstruct types that will be illegal in the backend. See
1553 /// ARMISelLowering for an example implementation.
1554 virtual Value *emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
1555 AtomicOrdering Ord) const {
1556 llvm_unreachable("Load linked unimplemented on this target")::llvm::llvm_unreachable_internal("Load linked unimplemented on this target"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1556)
;
1557 }
1558
1559 /// Perform a store-conditional operation to Addr. Return the status of the
1560 /// store. This should be 0 if the store succeeded, non-zero otherwise.
1561 virtual Value *emitStoreConditional(IRBuilder<> &Builder, Value *Val,
1562 Value *Addr, AtomicOrdering Ord) const {
1563 llvm_unreachable("Store conditional unimplemented on this target")::llvm::llvm_unreachable_internal("Store conditional unimplemented on this target"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1563)
;
1564 }
1565
1566 /// Perform a masked atomicrmw using a target-specific intrinsic. This
1567 /// represents the core LL/SC loop which will be lowered at a late stage by
1568 /// the backend.
1569 virtual Value *emitMaskedAtomicRMWIntrinsic(IRBuilder<> &Builder,
1570 AtomicRMWInst *AI,
1571 Value *AlignedAddr, Value *Incr,
1572 Value *Mask, Value *ShiftAmt,
1573 AtomicOrdering Ord) const {
1574 llvm_unreachable("Masked atomicrmw expansion unimplemented on this target")::llvm::llvm_unreachable_internal("Masked atomicrmw expansion unimplemented on this target"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1574)
;
1575 }
1576
1577 /// Perform a masked cmpxchg using a target-specific intrinsic. This
1578 /// represents the core LL/SC loop which will be lowered at a late stage by
1579 /// the backend.
1580 virtual Value *emitMaskedAtomicCmpXchgIntrinsic(
1581 IRBuilder<> &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
1582 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
1583 llvm_unreachable("Masked cmpxchg expansion unimplemented on this target")::llvm::llvm_unreachable_internal("Masked cmpxchg expansion unimplemented on this target"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1583)
;
1584 }
1585
1586 /// Inserts in the IR a target-specific intrinsic specifying a fence.
1587 /// It is called by AtomicExpandPass before expanding an
1588 /// AtomicRMW/AtomicCmpXchg/AtomicStore/AtomicLoad
1589 /// if shouldInsertFencesForAtomic returns true.
1590 ///
1591 /// Inst is the original atomic instruction, prior to other expansions that
1592 /// may be performed.
1593 ///
1594 /// This function should either return a nullptr, or a pointer to an IR-level
1595 /// Instruction*. Even complex fence sequences can be represented by a
1596 /// single Instruction* through an intrinsic to be lowered later.
1597 /// Backends should override this method to produce target-specific intrinsic
1598 /// for their fences.
1599 /// FIXME: Please note that the default implementation here in terms of
1600 /// IR-level fences exists for historical/compatibility reasons and is
1601 /// *unsound* ! Fences cannot, in general, be used to restore sequential
1602 /// consistency. For example, consider the following example:
1603 /// atomic<int> x = y = 0;
1604 /// int r1, r2, r3, r4;
1605 /// Thread 0:
1606 /// x.store(1);
1607 /// Thread 1:
1608 /// y.store(1);
1609 /// Thread 2:
1610 /// r1 = x.load();
1611 /// r2 = y.load();
1612 /// Thread 3:
1613 /// r3 = y.load();
1614 /// r4 = x.load();
1615 /// r1 = r3 = 1 and r2 = r4 = 0 is impossible as long as the accesses are all
1616 /// seq_cst. But if they are lowered to monotonic accesses, no amount of
1617 /// IR-level fences can prevent it.
1618 /// @{
1619 virtual Instruction *emitLeadingFence(IRBuilder<> &Builder, Instruction *Inst,
1620 AtomicOrdering Ord) const {
1621 if (isReleaseOrStronger(Ord) && Inst->hasAtomicStore())
1622 return Builder.CreateFence(Ord);
1623 else
1624 return nullptr;
1625 }
1626
1627 virtual Instruction *emitTrailingFence(IRBuilder<> &Builder,
1628 Instruction *Inst,
1629 AtomicOrdering Ord) const {
1630 if (isAcquireOrStronger(Ord))
1631 return Builder.CreateFence(Ord);
1632 else
1633 return nullptr;
1634 }
1635 /// @}
1636
1637 // Emits code that executes when the comparison result in the ll/sc
1638 // expansion of a cmpxchg instruction is such that the store-conditional will
1639 // not execute. This makes it possible to balance out the load-linked with
1640 // a dedicated instruction, if desired.
1641 // E.g., on ARM, if ldrex isn't followed by strex, the exclusive monitor would
1642 // be unnecessarily held, except if clrex, inserted by this hook, is executed.
1643 virtual void emitAtomicCmpXchgNoStoreLLBalance(IRBuilder<> &Builder) const {}
1644
1645 /// Returns true if the given (atomic) store should be expanded by the
1646 /// IR-level AtomicExpand pass into an "atomic xchg" which ignores its input.
1647 virtual bool shouldExpandAtomicStoreInIR(StoreInst *SI) const {
1648 return false;
1649 }
1650
1651 /// Returns true if arguments should be sign-extended in lib calls.
1652 virtual bool shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
1653 return IsSigned;
1654 }
1655
1656 /// Returns how the given (atomic) load should be expanded by the
1657 /// IR-level AtomicExpand pass.
1658 virtual AtomicExpansionKind shouldExpandAtomicLoadInIR(LoadInst *LI) const {
1659 return AtomicExpansionKind::None;
1660 }
1661
1662 /// Returns how the given atomic cmpxchg should be expanded by the IR-level
1663 /// AtomicExpand pass.
1664 virtual AtomicExpansionKind
1665 shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
1666 return AtomicExpansionKind::None;
1667 }
1668
1669 /// Returns how the IR-level AtomicExpand pass should expand the given
1670 /// AtomicRMW, if at all. Default is to never expand.
1671 virtual AtomicExpansionKind shouldExpandAtomicRMWInIR(AtomicRMWInst *) const {
1672 return AtomicExpansionKind::None;
1673 }
1674
1675 /// On some platforms, an AtomicRMW that never actually modifies the value
1676 /// (such as fetch_add of 0) can be turned into a fence followed by an
1677 /// atomic load. This may sound useless, but it makes it possible for the
1678 /// processor to keep the cacheline shared, dramatically improving
1679 /// performance. And such idempotent RMWs are useful for implementing some
1680 /// kinds of locks, see for example (justification + benchmarks):
1681 /// http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf
1682 /// This method tries doing that transformation, returning the atomic load if
1683 /// it succeeds, and nullptr otherwise.
1684 /// If shouldExpandAtomicLoadInIR returns true on that load, it will undergo
1685 /// another round of expansion.
1686 virtual LoadInst *
1687 lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *RMWI) const {
1688 return nullptr;
1689 }
1690
1691 /// Returns how the platform's atomic operations are extended (ZERO_EXTEND,
1692 /// SIGN_EXTEND, or ANY_EXTEND).
1693 virtual ISD::NodeType getExtendForAtomicOps() const {
1694 return ISD::ZERO_EXTEND;
1695 }
1696
1697 /// @}
1698
1699 /// Returns true if we should normalize
1700 /// select(N0&N1, X, Y) => select(N0, select(N1, X, Y), Y) and
1701 /// select(N0|N1, X, Y) => select(N0, select(N1, X, Y, Y)) if it is likely
1702 /// that it saves us from materializing N0 and N1 in an integer register.
1703 /// Targets that are able to perform and/or on flags should return false here.
1704 virtual bool shouldNormalizeToSelectSequence(LLVMContext &Context,
1705 EVT VT) const {
1706 // If a target has multiple condition registers, then it likely has logical
1707 // operations on those registers.
1708 if (hasMultipleConditionRegisters())
1709 return false;
1710 // Only do the transform if the value won't be split into multiple
1711 // registers.
1712 LegalizeTypeAction Action = getTypeAction(Context, VT);
1713 return Action != TypeExpandInteger && Action != TypeExpandFloat &&
1714 Action != TypeSplitVector;
1715 }
1716
1717 /// Return true if a select of constants (select Cond, C1, C2) should be
1718 /// transformed into simple math ops with the condition value. For example:
1719 /// select Cond, C1, C1-1 --> add (zext Cond), C1-1
1720 virtual bool convertSelectOfConstantsToMath(EVT VT) const {
1721 return false;
1722 }
1723
1724 /// Return true if it is profitable to transform an integer
1725 /// multiplication-by-constant into simpler operations like shifts and adds.
1726 /// This may be true if the target does not directly support the
1727 /// multiplication operation for the specified type or the sequence of simpler
1728 /// ops is faster than the multiply.
1729 virtual bool decomposeMulByConstant(EVT VT, SDValue C) const {
1730 return false;
1731 }
1732
1733 //===--------------------------------------------------------------------===//
1734 // TargetLowering Configuration Methods - These methods should be invoked by
1735 // the derived class constructor to configure this object for the target.
1736 //
1737protected:
1738 /// Specify how the target extends the result of integer and floating point
1739 /// boolean values from i1 to a wider type. See getBooleanContents.
1740 void setBooleanContents(BooleanContent Ty) {
1741 BooleanContents = Ty;
1742 BooleanFloatContents = Ty;
1743 }
1744
1745 /// Specify how the target extends the result of integer and floating point
1746 /// boolean values from i1 to a wider type. See getBooleanContents.
1747 void setBooleanContents(BooleanContent IntTy, BooleanContent FloatTy) {
1748 BooleanContents = IntTy;
1749 BooleanFloatContents = FloatTy;
1750 }
1751
1752 /// Specify how the target extends the result of a vector boolean value from a
1753 /// vector of i1 to a wider type. See getBooleanContents.
1754 void setBooleanVectorContents(BooleanContent Ty) {
1755 BooleanVectorContents = Ty;
1756 }
1757
1758 /// Specify the target scheduling preference.
1759 void setSchedulingPreference(Sched::Preference Pref) {
1760 SchedPreferenceInfo = Pref;
1761 }
1762
1763 /// Indicate whether this target prefers to use _setjmp to implement
1764 /// llvm.setjmp or the version without _. Defaults to false.
1765 void setUseUnderscoreSetJmp(bool Val) {
1766 UseUnderscoreSetJmp = Val;
1767 }
1768
1769 /// Indicate whether this target prefers to use _longjmp to implement
1770 /// llvm.longjmp or the version without _. Defaults to false.
1771 void setUseUnderscoreLongJmp(bool Val) {
1772 UseUnderscoreLongJmp = Val;
1773 }
1774
1775 /// Indicate the minimum number of blocks to generate jump tables.
1776 void setMinimumJumpTableEntries(unsigned Val);
1777
1778 /// Indicate the maximum number of entries in jump tables.
1779 /// Set to zero to generate unlimited jump tables.
1780 void setMaximumJumpTableSize(unsigned);
1781
1782 /// If set to a physical register, this specifies the register that
1783 /// llvm.savestack/llvm.restorestack should save and restore.
1784 void setStackPointerRegisterToSaveRestore(unsigned R) {
1785 StackPointerRegisterToSaveRestore = R;
1786 }
1787
1788 /// Tells the code generator that the target has multiple (allocatable)
1789 /// condition registers that can be used to store the results of comparisons
1790 /// for use by selects and conditional branches. With multiple condition
1791 /// registers, the code generator will not aggressively sink comparisons into
1792 /// the blocks of their users.
1793 void setHasMultipleConditionRegisters(bool hasManyRegs = true) {
1794 HasMultipleConditionRegisters = hasManyRegs;
1795 }
1796
1797 /// Tells the code generator that the target has BitExtract instructions.
1798 /// The code generator will aggressively sink "shift"s into the blocks of
1799 /// their users if the users will generate "and" instructions which can be
1800 /// combined with "shift" to BitExtract instructions.
1801 void setHasExtractBitsInsn(bool hasExtractInsn = true) {
1802 HasExtractBitsInsn = hasExtractInsn;
1803 }
1804
1805 /// Tells the code generator not to expand logic operations on comparison
1806 /// predicates into separate sequences that increase the amount of flow
1807 /// control.
1808 void setJumpIsExpensive(bool isExpensive = true);
1809
1810 /// Tells the code generator that this target supports floating point
1811 /// exceptions and cares about preserving floating point exception behavior.
1812 void setHasFloatingPointExceptions(bool FPExceptions = true) {
1813 HasFloatingPointExceptions = FPExceptions;
1814 }
1815
1816 /// Tells the code generator which bitwidths to bypass.
1817 void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
1818 BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
1819 }
1820
1821 /// Add the specified register class as an available regclass for the
1822 /// specified value type. This indicates the selector can handle values of
1823 /// that class natively.
1824 void addRegisterClass(MVT VT, const TargetRegisterClass *RC) {
1825 assert((unsigned)VT.SimpleTy < array_lengthof(RegClassForVT))(((unsigned)VT.SimpleTy < array_lengthof(RegClassForVT)) ?
static_cast<void> (0) : __assert_fail ("(unsigned)VT.SimpleTy < array_lengthof(RegClassForVT)"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1825, __PRETTY_FUNCTION__))
;
1826 RegClassForVT[VT.SimpleTy] = RC;
1827 }
1828
1829 /// Return the largest legal super-reg register class of the register class
1830 /// for the specified type and its associated "cost".
1831 virtual std::pair<const TargetRegisterClass *, uint8_t>
1832 findRepresentativeClass(const TargetRegisterInfo *TRI, MVT VT) const;
1833
1834 /// Once all of the register classes are added, this allows us to compute
1835 /// derived properties we expose.
1836 void computeRegisterProperties(const TargetRegisterInfo *TRI);
1837
1838 /// Indicate that the specified operation does not work with the specified
1839 /// type and indicate what to do about it. Note that VT may refer to either
1840 /// the type of a result or that of an operand of Op.
1841 void setOperationAction(unsigned Op, MVT VT,
1842 LegalizeAction Action) {
1843 assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!")((Op < array_lengthof(OpActions[0]) && "Table isn't big enough!"
) ? static_cast<void> (0) : __assert_fail ("Op < array_lengthof(OpActions[0]) && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1843, __PRETTY_FUNCTION__))
;
1844 OpActions[(unsigned)VT.SimpleTy][Op] = Action;
1845 }
1846
1847 /// Indicate that the specified load with extension does not work with the
1848 /// specified type and indicate what to do about it.
1849 void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT,
1850 LegalizeAction Action) {
1851 assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() &&((ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid
() && MemVT.isValid() && "Table isn't big enough!"
) ? static_cast<void> (0) : __assert_fail ("ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() && MemVT.isValid() && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1852, __PRETTY_FUNCTION__))
1852 MemVT.isValid() && "Table isn't big enough!")((ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid
() && MemVT.isValid() && "Table isn't big enough!"
) ? static_cast<void> (0) : __assert_fail ("ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() && MemVT.isValid() && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1852, __PRETTY_FUNCTION__))
;
1853 assert((unsigned)Action < 0x10 && "too many bits for bitfield array")(((unsigned)Action < 0x10 && "too many bits for bitfield array"
) ? static_cast<void> (0) : __assert_fail ("(unsigned)Action < 0x10 && \"too many bits for bitfield array\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1853, __PRETTY_FUNCTION__))
;
1854 unsigned Shift = 4 * ExtType;
1855 LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] &= ~((uint16_t)0xF << Shift);
1856 LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] |= (uint16_t)Action << Shift;
1857 }
1858
1859 /// Indicate that the specified truncating store does not work with the
1860 /// specified type and indicate what to do about it.
1861 void setTruncStoreAction(MVT ValVT, MVT MemVT,
1862 LegalizeAction Action) {
1863 assert(ValVT.isValid() && MemVT.isValid() && "Table isn't big enough!")((ValVT.isValid() && MemVT.isValid() && "Table isn't big enough!"
) ? static_cast<void> (0) : __assert_fail ("ValVT.isValid() && MemVT.isValid() && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1863, __PRETTY_FUNCTION__))
;
1864 TruncStoreActions[(unsigned)ValVT.SimpleTy][MemVT.SimpleTy] = Action;
1865 }
1866
1867 /// Indicate that the specified indexed load does or does not work with the
1868 /// specified type and indicate what to do abort it.
1869 ///
1870 /// NOTE: All indexed mode loads are initialized to Expand in
1871 /// TargetLowering.cpp
1872 void setIndexedLoadAction(unsigned IdxMode, MVT VT,
1873 LegalizeAction Action) {
1874 assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&((VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE
&& (unsigned)Action < 0xf && "Table isn't big enough!"
) ? static_cast<void> (0) : __assert_fail ("VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE && (unsigned)Action < 0xf && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1875, __PRETTY_FUNCTION__))
1875 (unsigned)Action < 0xf && "Table isn't big enough!")((VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE
&& (unsigned)Action < 0xf && "Table isn't big enough!"
) ? static_cast<void> (0) : __assert_fail ("VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE && (unsigned)Action < 0xf && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1875, __PRETTY_FUNCTION__))
;
1876 // Load action are kept in the upper half.
1877 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0xf0;
1878 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action) <<4;
1879 }
1880
1881 /// Indicate that the specified indexed store does or does not work with the
1882 /// specified type and indicate what to do about it.
1883 ///
1884 /// NOTE: All indexed mode stores are initialized to Expand in
1885 /// TargetLowering.cpp
1886 void setIndexedStoreAction(unsigned IdxMode, MVT VT,
1887 LegalizeAction Action) {
1888 assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&((VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE
&& (unsigned)Action < 0xf && "Table isn't big enough!"
) ? static_cast<void> (0) : __assert_fail ("VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE && (unsigned)Action < 0xf && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1889, __PRETTY_FUNCTION__))
1889 (unsigned)Action < 0xf && "Table isn't big enough!")((VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE
&& (unsigned)Action < 0xf && "Table isn't big enough!"
) ? static_cast<void> (0) : __assert_fail ("VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE && (unsigned)Action < 0xf && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1889, __PRETTY_FUNCTION__))
;
1890 // Store action are kept in the lower half.
1891 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0x0f;
1892 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action);
1893 }
1894
1895 /// Indicate that the specified condition code is or isn't supported on the
1896 /// target and indicate what to do about it.
1897 void setCondCodeAction(ISD::CondCode CC, MVT VT,
1898 LegalizeAction Action) {
1899 assert(VT.isValid() && (unsigned)CC < array_lengthof(CondCodeActions) &&((VT.isValid() && (unsigned)CC < array_lengthof(CondCodeActions
) && "Table isn't big enough!") ? static_cast<void
> (0) : __assert_fail ("VT.isValid() && (unsigned)CC < array_lengthof(CondCodeActions) && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1900, __PRETTY_FUNCTION__))
1900 "Table isn't big enough!")((VT.isValid() && (unsigned)CC < array_lengthof(CondCodeActions
) && "Table isn't big enough!") ? static_cast<void
> (0) : __assert_fail ("VT.isValid() && (unsigned)CC < array_lengthof(CondCodeActions) && \"Table isn't big enough!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1900, __PRETTY_FUNCTION__))
;
1901 assert((unsigned)Action < 0x10 && "too many bits for bitfield array")(((unsigned)Action < 0x10 && "too many bits for bitfield array"
) ? static_cast<void> (0) : __assert_fail ("(unsigned)Action < 0x10 && \"too many bits for bitfield array\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1901, __PRETTY_FUNCTION__))
;
1902 /// The lower 3 bits of the SimpleTy index into Nth 4bit set from the 32-bit
1903 /// value and the upper 29 bits index into the second dimension of the array
1904 /// to select what 32-bit value to use.
1905 uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
1906 CondCodeActions[CC][VT.SimpleTy >> 3] &= ~((uint32_t)0xF << Shift);
1907 CondCodeActions[CC][VT.SimpleTy >> 3] |= (uint32_t)Action << Shift;
1908 }
1909
1910 /// If Opc/OrigVT is specified as being promoted, the promotion code defaults
1911 /// to trying a larger integer/fp until it can find one that works. If that
1912 /// default is insufficient, this method can be used by the target to override
1913 /// the default.
1914 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1915 PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
1916 }
1917
1918 /// Convenience method to set an operation to Promote and specify the type
1919 /// in a single call.
1920 void setOperationPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1921 setOperationAction(Opc, OrigVT, Promote);
1922 AddPromotedToType(Opc, OrigVT, DestVT);
1923 }
1924
1925 /// Targets should invoke this method for each target independent node that
1926 /// they want to provide a custom DAG combiner for by implementing the
1927 /// PerformDAGCombine virtual method.
1928 void setTargetDAGCombine(ISD::NodeType NT) {
1929 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray))((unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray
)) ? static_cast<void> (0) : __assert_fail ("unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray)"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 1929, __PRETTY_FUNCTION__))
;
1930 TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
1931 }
1932
1933 /// Set the target's required jmp_buf buffer size (in bytes); default is 200
1934 void setJumpBufSize(unsigned Size) {
1935 JumpBufSize = Size;
1936 }
1937
1938 /// Set the target's required jmp_buf buffer alignment (in bytes); default is
1939 /// 0
1940 void setJumpBufAlignment(unsigned Align) {
1941 JumpBufAlignment = Align;
1942 }
1943
1944 /// Set the target's minimum function alignment (in log2(bytes))
1945 void setMinFunctionAlignment(unsigned Align) {
1946 MinFunctionAlignment = Align;
1947 }
1948
1949 /// Set the target's preferred function alignment. This should be set if
1950 /// there is a performance benefit to higher-than-minimum alignment (in
1951 /// log2(bytes))
1952 void setPrefFunctionAlignment(unsigned Align) {
1953 PrefFunctionAlignment = Align;
1954 }
1955
1956 /// Set the target's preferred loop alignment. Default alignment is zero, it
1957 /// means the target does not care about loop alignment. The alignment is
1958 /// specified in log2(bytes). The target may also override
1959 /// getPrefLoopAlignment to provide per-loop values.
1960 void setPrefLoopAlignment(unsigned Align) {
1961 PrefLoopAlignment = Align;
1962 }
1963
1964 /// Set the minimum stack alignment of an argument (in log2(bytes)).
1965 void setMinStackArgumentAlignment(unsigned Align) {
1966 MinStackArgumentAlignment = Align;
1967 }
1968
1969 /// Set the maximum atomic operation size supported by the
1970 /// backend. Atomic operations greater than this size (as well as
1971 /// ones that are not naturally aligned), will be expanded by
1972 /// AtomicExpandPass into an __atomic_* library call.
1973 void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits) {
1974 MaxAtomicSizeInBitsSupported = SizeInBits;
1975 }
1976
1977 /// Sets the minimum cmpxchg or ll/sc size supported by the backend.
1978 void setMinCmpXchgSizeInBits(unsigned SizeInBits) {
1979 MinCmpXchgSizeInBits = SizeInBits;
1980 }
1981
1982 /// Sets whether unaligned atomic operations are supported.
1983 void setSupportsUnalignedAtomics(bool UnalignedSupported) {
1984 SupportsUnalignedAtomics = UnalignedSupported;
1985 }
1986
1987public:
1988 //===--------------------------------------------------------------------===//
1989 // Addressing mode description hooks (used by LSR etc).
1990 //
1991
1992 /// CodeGenPrepare sinks address calculations into the same BB as Load/Store
1993 /// instructions reading the address. This allows as much computation as
1994 /// possible to be done in the address mode for that operand. This hook lets
1995 /// targets also pass back when this should be done on intrinsics which
1996 /// load/store.
1997 virtual bool getAddrModeArguments(IntrinsicInst * /*I*/,
1998 SmallVectorImpl<Value*> &/*Ops*/,
1999 Type *&/*AccessTy*/) const {
2000 return false;
2001 }
2002
2003 /// This represents an addressing mode of:
2004 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
2005 /// If BaseGV is null, there is no BaseGV.
2006 /// If BaseOffs is zero, there is no base offset.
2007 /// If HasBaseReg is false, there is no base register.
2008 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
2009 /// no scale.
2010 struct AddrMode {
2011 GlobalValue *BaseGV = nullptr;
2012 int64_t BaseOffs = 0;
2013 bool HasBaseReg = false;
2014 int64_t Scale = 0;
2015 AddrMode() = default;
2016 };
2017
2018 /// Return true if the addressing mode represented by AM is legal for this
2019 /// target, for a load/store of the specified type.
2020 ///
2021 /// The type may be VoidTy, in which case only return true if the addressing
2022 /// mode is legal for a load/store of any legal type. TODO: Handle
2023 /// pre/postinc as well.
2024 ///
2025 /// If the address space cannot be determined, it will be -1.
2026 ///
2027 /// TODO: Remove default argument
2028 virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM,
2029 Type *Ty, unsigned AddrSpace,
2030 Instruction *I = nullptr) const;
2031
2032 /// Return the cost of the scaling factor used in the addressing mode
2033 /// represented by AM for this target, for a load/store of the specified type.
2034 ///
2035 /// If the AM is supported, the return value must be >= 0.
2036 /// If the AM is not supported, it returns a negative value.
2037 /// TODO: Handle pre/postinc as well.
2038 /// TODO: Remove default argument
2039 virtual int getScalingFactorCost(const DataLayout &DL, const AddrMode &AM,
2040 Type *Ty, unsigned AS = 0) const {
2041 // Default: assume that any scaling factor used in a legal AM is free.
2042 if (isLegalAddressingMode(DL, AM, Ty, AS))
2043 return 0;
2044 return -1;
2045 }
2046
2047 /// Return true if the specified immediate is legal icmp immediate, that is
2048 /// the target has icmp instructions which can compare a register against the
2049 /// immediate without having to materialize the immediate into a register.
2050 virtual bool isLegalICmpImmediate(int64_t) const {
2051 return true;
2052 }
2053
2054 /// Return true if the specified immediate is legal add immediate, that is the
2055 /// target has add instructions which can add a register with the immediate
2056 /// without having to materialize the immediate into a register.
2057 virtual bool isLegalAddImmediate(int64_t) const {
2058 return true;
2059 }
2060
2061 /// Return true if the specified immediate is legal for the value input of a
2062 /// store instruction.
2063 virtual bool isLegalStoreImmediate(int64_t Value) const {
2064 // Default implementation assumes that at least 0 works since it is likely
2065 // that a zero register exists or a zero immediate is allowed.
2066 return Value == 0;
2067 }
2068
2069 /// Return true if it's significantly cheaper to shift a vector by a uniform
2070 /// scalar than by an amount which will vary across each lane. On x86, for
2071 /// example, there is a "psllw" instruction for the former case, but no simple
2072 /// instruction for a general "a << b" operation on vectors.
2073 virtual bool isVectorShiftByScalarCheap(Type *Ty) const {
2074 return false;
2075 }
2076
2077 /// Returns true if the opcode is a commutative binary operation.
2078 virtual bool isCommutativeBinOp(unsigned Opcode) const {
2079 // FIXME: This should get its info from the td file.
2080 switch (Opcode) {
2081 case ISD::ADD:
2082 case ISD::SMIN:
2083 case ISD::SMAX:
2084 case ISD::UMIN:
2085 case ISD::UMAX:
2086 case ISD::MUL:
2087 case ISD::MULHU:
2088 case ISD::MULHS:
2089 case ISD::SMUL_LOHI:
2090 case ISD::UMUL_LOHI:
2091 case ISD::FADD:
2092 case ISD::FMUL:
2093 case ISD::AND:
2094 case ISD::OR:
2095 case ISD::XOR:
2096 case ISD::SADDO:
2097 case ISD::UADDO:
2098 case ISD::ADDC:
2099 case ISD::ADDE:
2100 case ISD::FMINNUM:
2101 case ISD::FMAXNUM:
2102 case ISD::FMINIMUM:
2103 case ISD::FMAXIMUM:
2104 return true;
2105 default: return false;
2106 }
2107 }
2108
2109 /// Return true if it's free to truncate a value of type FromTy to type
2110 /// ToTy. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
2111 /// by referencing its sub-register AX.
2112 /// Targets must return false when FromTy <= ToTy.
2113 virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const {
2114 return false;
2115 }
2116
2117 /// Return true if a truncation from FromTy to ToTy is permitted when deciding
2118 /// whether a call is in tail position. Typically this means that both results
2119 /// would be assigned to the same register or stack slot, but it could mean
2120 /// the target performs adequate checks of its own before proceeding with the
2121 /// tail call. Targets must return false when FromTy <= ToTy.
2122 virtual bool allowTruncateForTailCall(Type *FromTy, Type *ToTy) const {
2123 return false;
2124 }
2125
2126 virtual bool isTruncateFree(EVT FromVT, EVT ToVT) const {
2127 return false;
2128 }
2129
2130 virtual bool isProfitableToHoist(Instruction *I) const { return true; }
2131
2132 /// Return true if the extension represented by \p I is free.
2133 /// Unlikely the is[Z|FP]ExtFree family which is based on types,
2134 /// this method can use the context provided by \p I to decide
2135 /// whether or not \p I is free.
2136 /// This method extends the behavior of the is[Z|FP]ExtFree family.
2137 /// In other words, if is[Z|FP]Free returns true, then this method
2138 /// returns true as well. The converse is not true.
2139 /// The target can perform the adequate checks by overriding isExtFreeImpl.
2140 /// \pre \p I must be a sign, zero, or fp extension.
2141 bool isExtFree(const Instruction *I) const {
2142 switch (I->getOpcode()) {
2143 case Instruction::FPExt:
2144 if (isFPExtFree(EVT::getEVT(I->getType()),
2145 EVT::getEVT(I->getOperand(0)->getType())))
2146 return true;
2147 break;
2148 case Instruction::ZExt:
2149 if (isZExtFree(I->getOperand(0)->getType(), I->getType()))
2150 return true;
2151 break;
2152 case Instruction::SExt:
2153 break;
2154 default:
2155 llvm_unreachable("Instruction is not an extension")::llvm::llvm_unreachable_internal("Instruction is not an extension"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 2155)
;
2156 }
2157 return isExtFreeImpl(I);
2158 }
2159
2160 /// Return true if \p Load and \p Ext can form an ExtLoad.
2161 /// For example, in AArch64
2162 /// %L = load i8, i8* %ptr
2163 /// %E = zext i8 %L to i32
2164 /// can be lowered into one load instruction
2165 /// ldrb w0, [x0]
2166 bool isExtLoad(const LoadInst *Load, const Instruction *Ext,
2167 const DataLayout &DL) const {
2168 EVT VT = getValueType(DL, Ext->getType());
2169 EVT LoadVT = getValueType(DL, Load->getType());
2170
2171 // If the load has other users and the truncate is not free, the ext
2172 // probably isn't free.
2173 if (!Load->hasOneUse() && (isTypeLegal(LoadVT) || !isTypeLegal(VT)) &&
2174 !isTruncateFree(Ext->getType(), Load->getType()))
2175 return false;
2176
2177 // Check whether the target supports casts folded into loads.
2178 unsigned LType;
2179 if (isa<ZExtInst>(Ext))
2180 LType = ISD::ZEXTLOAD;
2181 else {
2182 assert(isa<SExtInst>(Ext) && "Unexpected ext type!")((isa<SExtInst>(Ext) && "Unexpected ext type!")
? static_cast<void> (0) : __assert_fail ("isa<SExtInst>(Ext) && \"Unexpected ext type!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 2182, __PRETTY_FUNCTION__))
;
2183 LType = ISD::SEXTLOAD;
2184 }
2185
2186 return isLoadExtLegal(LType, VT, LoadVT);
2187 }
2188
2189 /// Return true if any actual instruction that defines a value of type FromTy
2190 /// implicitly zero-extends the value to ToTy in the result register.
2191 ///
2192 /// The function should return true when it is likely that the truncate can
2193 /// be freely folded with an instruction defining a value of FromTy. If
2194 /// the defining instruction is unknown (because you're looking at a
2195 /// function argument, PHI, etc.) then the target may require an
2196 /// explicit truncate, which is not necessarily free, but this function
2197 /// does not deal with those cases.
2198 /// Targets must return false when FromTy >= ToTy.
2199 virtual bool isZExtFree(Type *FromTy, Type *ToTy) const {
2200 return false;
2201 }
2202
2203 virtual bool isZExtFree(EVT FromTy, EVT ToTy) const {
2204 return false;
2205 }
2206
2207 /// Return true if the target supplies and combines to a paired load
2208 /// two loaded values of type LoadedType next to each other in memory.
2209 /// RequiredAlignment gives the minimal alignment constraints that must be met
2210 /// to be able to select this paired load.
2211 ///
2212 /// This information is *not* used to generate actual paired loads, but it is
2213 /// used to generate a sequence of loads that is easier to combine into a
2214 /// paired load.
2215 /// For instance, something like this:
2216 /// a = load i64* addr
2217 /// b = trunc i64 a to i32
2218 /// c = lshr i64 a, 32
2219 /// d = trunc i64 c to i32
2220 /// will be optimized into:
2221 /// b = load i32* addr1
2222 /// d = load i32* addr2
2223 /// Where addr1 = addr2 +/- sizeof(i32).
2224 ///
2225 /// In other words, unless the target performs a post-isel load combining,
2226 /// this information should not be provided because it will generate more
2227 /// loads.
2228 virtual bool hasPairedLoad(EVT /*LoadedType*/,
2229 unsigned & /*RequiredAlignment*/) const {
2230 return false;
2231 }
2232
2233 /// Return true if the target has a vector blend instruction.
2234 virtual bool hasVectorBlend() const { return false; }
2235
2236 /// Get the maximum supported factor for interleaved memory accesses.
2237 /// Default to be the minimum interleave factor: 2.
2238 virtual unsigned getMaxSupportedInterleaveFactor() const { return 2; }
2239
2240 /// Lower an interleaved load to target specific intrinsics. Return
2241 /// true on success.
2242 ///
2243 /// \p LI is the vector load instruction.
2244 /// \p Shuffles is the shufflevector list to DE-interleave the loaded vector.
2245 /// \p Indices is the corresponding indices for each shufflevector.
2246 /// \p Factor is the interleave factor.
2247 virtual bool lowerInterleavedLoad(LoadInst *LI,
2248 ArrayRef<ShuffleVectorInst *> Shuffles,
2249 ArrayRef<unsigned> Indices,
2250 unsigned Factor) const {
2251 return false;
2252 }
2253
2254 /// Lower an interleaved store to target specific intrinsics. Return
2255 /// true on success.
2256 ///
2257 /// \p SI is the vector store instruction.
2258 /// \p SVI is the shufflevector to RE-interleave the stored vector.
2259 /// \p Factor is the interleave factor.
2260 virtual bool lowerInterleavedStore(StoreInst *SI, ShuffleVectorInst *SVI,
2261 unsigned Factor) const {
2262 return false;
2263 }
2264
2265 /// Return true if zero-extending the specific node Val to type VT2 is free
2266 /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
2267 /// because it's folded such as X86 zero-extending loads).
2268 virtual bool isZExtFree(SDValue Val, EVT VT2) const {
2269 return isZExtFree(Val.getValueType(), VT2);
2270 }
2271
2272 /// Return true if an fpext operation is free (for instance, because
2273 /// single-precision floating-point numbers are implicitly extended to
2274 /// double-precision).
2275 virtual bool isFPExtFree(EVT DestVT, EVT SrcVT) const {
2276 assert(SrcVT.isFloatingPoint() && DestVT.isFloatingPoint() &&((SrcVT.isFloatingPoint() && DestVT.isFloatingPoint()
&& "invalid fpext types") ? static_cast<void> (
0) : __assert_fail ("SrcVT.isFloatingPoint() && DestVT.isFloatingPoint() && \"invalid fpext types\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 2277, __PRETTY_FUNCTION__))
2277 "invalid fpext types")((SrcVT.isFloatingPoint() && DestVT.isFloatingPoint()
&& "invalid fpext types") ? static_cast<void> (
0) : __assert_fail ("SrcVT.isFloatingPoint() && DestVT.isFloatingPoint() && \"invalid fpext types\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 2277, __PRETTY_FUNCTION__))
;
2278 return false;
2279 }
2280
2281 /// Return true if an fpext operation input to an \p Opcode operation is free
2282 /// (for instance, because half-precision floating-point numbers are
2283 /// implicitly extended to float-precision) for an FMA instruction.
2284 virtual bool isFPExtFoldable(unsigned Opcode, EVT DestVT, EVT SrcVT) const {
2285 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&((DestVT.isFloatingPoint() && SrcVT.isFloatingPoint()
&& "invalid fpext types") ? static_cast<void> (
0) : __assert_fail ("DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && \"invalid fpext types\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 2286, __PRETTY_FUNCTION__))
2286 "invalid fpext types")((DestVT.isFloatingPoint() && SrcVT.isFloatingPoint()
&& "invalid fpext types") ? static_cast<void> (
0) : __assert_fail ("DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && \"invalid fpext types\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 2286, __PRETTY_FUNCTION__))
;
2287 return isFPExtFree(DestVT, SrcVT);
2288 }
2289
2290 /// Return true if folding a vector load into ExtVal (a sign, zero, or any
2291 /// extend node) is profitable.
2292 virtual bool isVectorLoadExtDesirable(SDValue ExtVal) const { return false; }
2293
2294 /// Return true if an fneg operation is free to the point where it is never
2295 /// worthwhile to replace it with a bitwise operation.
2296 virtual bool isFNegFree(EVT VT) const {
2297 assert(VT.isFloatingPoint())((VT.isFloatingPoint()) ? static_cast<void> (0) : __assert_fail
("VT.isFloatingPoint()", "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 2297, __PRETTY_FUNCTION__))
;
2298 return false;
2299 }
2300
2301 /// Return true if an fabs operation is free to the point where it is never
2302 /// worthwhile to replace it with a bitwise operation.
2303 virtual bool isFAbsFree(EVT VT) const {
2304 assert(VT.isFloatingPoint())((VT.isFloatingPoint()) ? static_cast<void> (0) : __assert_fail
("VT.isFloatingPoint()", "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 2304, __PRETTY_FUNCTION__))
;
2305 return false;
2306 }
2307
2308 /// Return true if an FMA operation is faster than a pair of fmul and fadd
2309 /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
2310 /// returns true, otherwise fmuladd is expanded to fmul + fadd.
2311 ///
2312 /// NOTE: This may be called before legalization on types for which FMAs are
2313 /// not legal, but should return true if those types will eventually legalize
2314 /// to types that support FMAs. After legalization, it will only be called on
2315 /// types that support FMAs (via Legal or Custom actions)
2316 virtual bool isFMAFasterThanFMulAndFAdd(EVT) const {
2317 return false;
2318 }
2319
2320 /// Return true if it's profitable to narrow operations of type VT1 to
2321 /// VT2. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
2322 /// i32 to i16.
2323 virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
2324 return false;
2325 }
2326
2327 /// Return true if it is beneficial to convert a load of a constant to
2328 /// just the constant itself.
2329 /// On some targets it might be more efficient to use a combination of
2330 /// arithmetic instructions to materialize the constant instead of loading it
2331 /// from a constant pool.
2332 virtual bool shouldConvertConstantLoadToIntImm(const APInt &Imm,
2333 Type *Ty) const {
2334 return false;
2335 }
2336
2337 /// Return true if EXTRACT_SUBVECTOR is cheap for extracting this result type
2338 /// from this source type with this index. This is needed because
2339 /// EXTRACT_SUBVECTOR usually has custom lowering that depends on the index of
2340 /// the first element, and only the target knows which lowering is cheap.
2341 virtual bool isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
2342 unsigned Index) const {
2343 return false;
2344 }
2345
2346 // Return true if it is profitable to use a scalar input to a BUILD_VECTOR
2347 // even if the vector itself has multiple uses.
2348 virtual bool aggressivelyPreferBuildVectorSources(EVT VecVT) const {
2349 return false;
2350 }
2351
2352 // Return true if CodeGenPrepare should consider splitting large offset of a
2353 // GEP to make the GEP fit into the addressing mode and can be sunk into the
2354 // same blocks of its users.
2355 virtual bool shouldConsiderGEPOffsetSplit() const { return false; }
2356
2357 //===--------------------------------------------------------------------===//
2358 // Runtime Library hooks
2359 //
2360
2361 /// Rename the default libcall routine name for the specified libcall.
2362 void setLibcallName(RTLIB::Libcall Call, const char *Name) {
2363 LibcallRoutineNames[Call] = Name;
2364 }
2365
2366 /// Get the libcall routine name for the specified libcall.
2367 const char *getLibcallName(RTLIB::Libcall Call) const {
2368 return LibcallRoutineNames[Call];
2369 }
2370
2371 /// Override the default CondCode to be used to test the result of the
2372 /// comparison libcall against zero.
2373 void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
2374 CmpLibcallCCs[Call] = CC;
2375 }
2376
2377 /// Get the CondCode that's to be used to test the result of the comparison
2378 /// libcall against zero.
2379 ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
2380 return CmpLibcallCCs[Call];
2381 }
2382
2383 /// Set the CallingConv that should be used for the specified libcall.
2384 void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
2385 LibcallCallingConvs[Call] = CC;
2386 }
2387
2388 /// Get the CallingConv that should be used for the specified libcall.
2389 CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
2390 return LibcallCallingConvs[Call];
2391 }
2392
2393 /// Execute target specific actions to finalize target lowering.
2394 /// This is used to set extra flags in MachineFrameInformation and freezing
2395 /// the set of reserved registers.
2396 /// The default implementation just freezes the set of reserved registers.
2397 virtual void finalizeLowering(MachineFunction &MF) const;
2398
2399private:
2400 const TargetMachine &TM;
2401
2402 /// Tells the code generator that the target has multiple (allocatable)
2403 /// condition registers that can be used to store the results of comparisons
2404 /// for use by selects and conditional branches. With multiple condition
2405 /// registers, the code generator will not aggressively sink comparisons into
2406 /// the blocks of their users.
2407 bool HasMultipleConditionRegisters;
2408
2409 /// Tells the code generator that the target has BitExtract instructions.
2410 /// The code generator will aggressively sink "shift"s into the blocks of
2411 /// their users if the users will generate "and" instructions which can be
2412 /// combined with "shift" to BitExtract instructions.
2413 bool HasExtractBitsInsn;
2414
2415 /// Tells the code generator to bypass slow divide or remainder
2416 /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
2417 /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
2418 /// div/rem when the operands are positive and less than 256.
2419 DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
2420
2421 /// Tells the code generator that it shouldn't generate extra flow control
2422 /// instructions and should attempt to combine flow control instructions via
2423 /// predication.
2424 bool JumpIsExpensive;
2425
2426 /// Whether the target supports or cares about preserving floating point
2427 /// exception behavior.
2428 bool HasFloatingPointExceptions;
2429
2430 /// This target prefers to use _setjmp to implement llvm.setjmp.
2431 ///
2432 /// Defaults to false.
2433 bool UseUnderscoreSetJmp;
2434
2435 /// This target prefers to use _longjmp to implement llvm.longjmp.
2436 ///
2437 /// Defaults to false.
2438 bool UseUnderscoreLongJmp;
2439
2440 /// Information about the contents of the high-bits in boolean values held in
2441 /// a type wider than i1. See getBooleanContents.
2442 BooleanContent BooleanContents;
2443
2444 /// Information about the contents of the high-bits in boolean values held in
2445 /// a type wider than i1. See getBooleanContents.
2446 BooleanContent BooleanFloatContents;
2447
2448 /// Information about the contents of the high-bits in boolean vector values
2449 /// when the element type is wider than i1. See getBooleanContents.
2450 BooleanContent BooleanVectorContents;
2451
2452 /// The target scheduling preference: shortest possible total cycles or lowest
2453 /// register usage.
2454 Sched::Preference SchedPreferenceInfo;
2455
2456 /// The size, in bytes, of the target's jmp_buf buffers
2457 unsigned JumpBufSize;
2458
2459 /// The alignment, in bytes, of the target's jmp_buf buffers
2460 unsigned JumpBufAlignment;
2461
2462 /// The minimum alignment that any argument on the stack needs to have.
2463 unsigned MinStackArgumentAlignment;
2464
2465 /// The minimum function alignment (used when optimizing for size, and to
2466 /// prevent explicitly provided alignment from leading to incorrect code).
2467 unsigned MinFunctionAlignment;
2468
2469 /// The preferred function alignment (used when alignment unspecified and
2470 /// optimizing for speed).
2471 unsigned PrefFunctionAlignment;
2472
2473 /// The preferred loop alignment.
2474 unsigned PrefLoopAlignment;
2475
2476 /// Size in bits of the maximum atomics size the backend supports.
2477 /// Accesses larger than this will be expanded by AtomicExpandPass.
2478 unsigned MaxAtomicSizeInBitsSupported;
2479
2480 /// Size in bits of the minimum cmpxchg or ll/sc operation the
2481 /// backend supports.
2482 unsigned MinCmpXchgSizeInBits;
2483
2484 /// This indicates if the target supports unaligned atomic operations.
2485 bool SupportsUnalignedAtomics;
2486
2487 /// If set to a physical register, this specifies the register that
2488 /// llvm.savestack/llvm.restorestack should save and restore.
2489 unsigned StackPointerRegisterToSaveRestore;
2490
2491 /// This indicates the default register class to use for each ValueType the
2492 /// target supports natively.
2493 const TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
2494 unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
2495 MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
2496
2497 /// This indicates the "representative" register class to use for each
2498 /// ValueType the target supports natively. This information is used by the
2499 /// scheduler to track register pressure. By default, the representative
2500 /// register class is the largest legal super-reg register class of the
2501 /// register class of the specified type. e.g. On x86, i8, i16, and i32's
2502 /// representative class would be GR32.
2503 const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
2504
2505 /// This indicates the "cost" of the "representative" register class for each
2506 /// ValueType. The cost is used by the scheduler to approximate register
2507 /// pressure.
2508 uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
2509
2510 /// For any value types we are promoting or expanding, this contains the value
2511 /// type that we are changing to. For Expanded types, this contains one step
2512 /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
2513 /// (e.g. i64 -> i16). For types natively supported by the system, this holds
2514 /// the same type (e.g. i32 -> i32).
2515 MVT TransformToType[MVT::LAST_VALUETYPE];
2516
2517 /// For each operation and each value type, keep a LegalizeAction that
2518 /// indicates how instruction selection should deal with the operation. Most
2519 /// operations are Legal (aka, supported natively by the target), but
2520 /// operations that are not should be described. Note that operations on
2521 /// non-legal value types are not described here.
2522 LegalizeAction OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END];
2523
2524 /// For each load extension type and each value type, keep a LegalizeAction
2525 /// that indicates how instruction selection should deal with a load of a
2526 /// specific value type and extension type. Uses 4-bits to store the action
2527 /// for each of the 4 load ext types.
2528 uint16_t LoadExtActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
2529
2530 /// For each value type pair keep a LegalizeAction that indicates whether a
2531 /// truncating store of a specific value type and truncating type is legal.
2532 LegalizeAction TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
2533
2534 /// For each indexed mode and each value type, keep a pair of LegalizeAction
2535 /// that indicates how instruction selection should deal with the load /
2536 /// store.
2537 ///
2538 /// The first dimension is the value_type for the reference. The second
2539 /// dimension represents the various modes for load store.
2540 uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
2541
2542 /// For each condition code (ISD::CondCode) keep a LegalizeAction that
2543 /// indicates how instruction selection should deal with the condition code.
2544 ///
2545 /// Because each CC action takes up 4 bits, we need to have the array size be
2546 /// large enough to fit all of the value types. This can be done by rounding
2547 /// up the MVT::LAST_VALUETYPE value to the next multiple of 8.
2548 uint32_t CondCodeActions[ISD::SETCC_INVALID][(MVT::LAST_VALUETYPE + 7) / 8];
2549
2550protected:
2551 ValueTypeActionImpl ValueTypeActions;
2552
2553private:
2554 LegalizeKind getTypeConversion(LLVMContext &Context, EVT VT) const;
2555
2556 /// Targets can specify ISD nodes that they would like PerformDAGCombine
2557 /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
2558 /// array.
2559 unsigned char
2560 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT8-1)/CHAR_BIT8];
2561
2562 /// For operations that must be promoted to a specific type, this holds the
2563 /// destination type. This map should be sparse, so don't hold it as an
2564 /// array.
2565 ///
2566 /// Targets add entries to this map with AddPromotedToType(..), clients access
2567 /// this with getTypeToPromoteTo(..).
2568 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
2569 PromoteToType;
2570
2571 /// Stores the name each libcall.
2572 const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL + 1];
2573
2574 /// The ISD::CondCode that should be used to test the result of each of the
2575 /// comparison libcall against zero.
2576 ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
2577
2578 /// Stores the CallingConv that should be used for each libcall.
2579 CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
2580
2581 /// Set default libcall names and calling conventions.
2582 void InitLibcalls(const Triple &TT);
2583
2584protected:
2585 /// Return true if the extension represented by \p I is free.
2586 /// \pre \p I is a sign, zero, or fp extension and
2587 /// is[Z|FP]ExtFree of the related types is not true.
2588 virtual bool isExtFreeImpl(const Instruction *I) const { return false; }
2589
2590 /// Depth that GatherAllAliases should should continue looking for chain
2591 /// dependencies when trying to find a more preferable chain. As an
2592 /// approximation, this should be more than the number of consecutive stores
2593 /// expected to be merged.
2594 unsigned GatherAllAliasesMaxDepth;
2595
2596 /// Specify maximum number of store instructions per memset call.
2597 ///
2598 /// When lowering \@llvm.memset this field specifies the maximum number of
2599 /// store operations that may be substituted for the call to memset. Targets
2600 /// must set this value based on the cost threshold for that target. Targets
2601 /// should assume that the memset will be done using as many of the largest
2602 /// store operations first, followed by smaller ones, if necessary, per
2603 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
2604 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
2605 /// store. This only applies to setting a constant array of a constant size.
2606 unsigned MaxStoresPerMemset;
2607
2608 /// Maximum number of stores operations that may be substituted for the call
2609 /// to memset, used for functions with OptSize attribute.
2610 unsigned MaxStoresPerMemsetOptSize;
2611
2612 /// Specify maximum bytes of store instructions per memcpy call.
2613 ///
2614 /// When lowering \@llvm.memcpy this field specifies the maximum number of
2615 /// store operations that may be substituted for a call to memcpy. Targets
2616 /// must set this value based on the cost threshold for that target. Targets
2617 /// should assume that the memcpy will be done using as many of the largest
2618 /// store operations first, followed by smaller ones, if necessary, per
2619 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
2620 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
2621 /// and one 1-byte store. This only applies to copying a constant array of
2622 /// constant size.
2623 unsigned MaxStoresPerMemcpy;
2624
2625
2626 /// \brief Specify max number of store instructions to glue in inlined memcpy.
2627 ///
2628 /// When memcpy is inlined based on MaxStoresPerMemcpy, specify maximum number
2629 /// of store instructions to keep together. This helps in pairing and
2630 // vectorization later on.
2631 unsigned MaxGluedStoresPerMemcpy = 0;
2632
2633 /// Maximum number of store operations that may be substituted for a call to
2634 /// memcpy, used for functions with OptSize attribute.
2635 unsigned MaxStoresPerMemcpyOptSize;
2636 unsigned MaxLoadsPerMemcmp;
2637 unsigned MaxLoadsPerMemcmpOptSize;
2638
2639 /// Specify maximum bytes of store instructions per memmove call.
2640 ///
2641 /// When lowering \@llvm.memmove this field specifies the maximum number of
2642 /// store instructions that may be substituted for a call to memmove. Targets
2643 /// must set this value based on the cost threshold for that target. Targets
2644 /// should assume that the memmove will be done using as many of the largest
2645 /// store operations first, followed by smaller ones, if necessary, per
2646 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
2647 /// with 8-bit alignment would result in nine 1-byte stores. This only
2648 /// applies to copying a constant array of constant size.
2649 unsigned MaxStoresPerMemmove;
2650
2651 /// Maximum number of store instructions that may be substituted for a call to
2652 /// memmove, used for functions with OptSize attribute.
2653 unsigned MaxStoresPerMemmoveOptSize;
2654
2655 /// Tells the code generator that select is more expensive than a branch if
2656 /// the branch is usually predicted right.
2657 bool PredictableSelectIsExpensive;
2658
2659 /// \see enableExtLdPromotion.
2660 bool EnableExtLdPromotion;
2661
2662 /// Return true if the value types that can be represented by the specified
2663 /// register class are all legal.
2664 bool isLegalRC(const TargetRegisterInfo &TRI,
2665 const TargetRegisterClass &RC) const;
2666
2667 /// Replace/modify any TargetFrameIndex operands with a targte-dependent
2668 /// sequence of memory operands that is recognized by PrologEpilogInserter.
2669 MachineBasicBlock *emitPatchPoint(MachineInstr &MI,
2670 MachineBasicBlock *MBB) const;
2671
2672 /// Replace/modify the XRay custom event operands with target-dependent
2673 /// details.
2674 MachineBasicBlock *emitXRayCustomEvent(MachineInstr &MI,
2675 MachineBasicBlock *MBB) const;
2676
2677 /// Replace/modify the XRay typed event operands with target-dependent
2678 /// details.
2679 MachineBasicBlock *emitXRayTypedEvent(MachineInstr &MI,
2680 MachineBasicBlock *MBB) const;
2681};
2682
2683/// This class defines information used to lower LLVM code to legal SelectionDAG
2684/// operators that the target instruction selector can accept natively.
2685///
2686/// This class also defines callbacks that targets must implement to lower
2687/// target-specific constructs to SelectionDAG operators.
2688class TargetLowering : public TargetLoweringBase {
2689public:
2690 struct DAGCombinerInfo;
2691
2692 TargetLowering(const TargetLowering &) = delete;
2693 TargetLowering &operator=(const TargetLowering &) = delete;
2694
2695 /// NOTE: The TargetMachine owns TLOF.
2696 explicit TargetLowering(const TargetMachine &TM);
2697
2698 bool isPositionIndependent() const;
2699
2700 virtual bool isSDNodeSourceOfDivergence(const SDNode *N,
2701 FunctionLoweringInfo *FLI,
2702 LegacyDivergenceAnalysis *DA) const {
2703 return false;
2704 }
2705
2706 virtual bool isSDNodeAlwaysUniform(const SDNode * N) const {
2707 return false;
2708 }
2709
2710 /// Returns true by value, base pointer and offset pointer and addressing mode
2711 /// by reference if the node's address can be legally represented as
2712 /// pre-indexed load / store address.
2713 virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
2714 SDValue &/*Offset*/,
2715 ISD::MemIndexedMode &/*AM*/,
2716 SelectionDAG &/*DAG*/) const {
2717 return false;
2718 }
2719
2720 /// Returns true by value, base pointer and offset pointer and addressing mode
2721 /// by reference if this node can be combined with a load / store to form a
2722 /// post-indexed load / store.
2723 virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
2724 SDValue &/*Base*/,
2725 SDValue &/*Offset*/,
2726 ISD::MemIndexedMode &/*AM*/,
2727 SelectionDAG &/*DAG*/) const {
2728 return false;
2729 }
2730
2731 /// Return the entry encoding for a jump table in the current function. The
2732 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
2733 virtual unsigned getJumpTableEncoding() const;
2734
2735 virtual const MCExpr *
2736 LowerCustomJumpTableEntry(const MachineJumpTableInfo * /*MJTI*/,
2737 const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
2738 MCContext &/*Ctx*/) const {
2739 llvm_unreachable("Need to implement this hook if target has custom JTIs")::llvm::llvm_unreachable_internal("Need to implement this hook if target has custom JTIs"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 2739)
;
2740 }
2741
2742 /// Returns relocation base for the given PIC jumptable.
2743 virtual SDValue getPICJumpTableRelocBase(SDValue Table,
2744 SelectionDAG &DAG) const;
2745
2746 /// This returns the relocation base for the given PIC jumptable, the same as
2747 /// getPICJumpTableRelocBase, but as an MCExpr.
2748 virtual const MCExpr *
2749 getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2750 unsigned JTI, MCContext &Ctx) const;
2751
2752 /// Return true if folding a constant offset with the given GlobalAddress is
2753 /// legal. It is frequently not legal in PIC relocation models.
2754 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
2755
2756 bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
2757 SDValue &Chain) const;
2758
2759 void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
2760 SDValue &NewRHS, ISD::CondCode &CCCode,
2761 const SDLoc &DL) const;
2762
2763 /// Returns a pair of (return value, chain).
2764 /// It is an error to pass RTLIB::UNKNOWN_LIBCALL as \p LC.
2765 std::pair<SDValue, SDValue> makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC,
2766 EVT RetVT, ArrayRef<SDValue> Ops,
2767 bool isSigned, const SDLoc &dl,
2768 bool doesNotReturn = false,
2769 bool isReturnValueUsed = true) const;
2770
2771 /// Check whether parameters to a call that are passed in callee saved
2772 /// registers are the same as from the calling function. This needs to be
2773 /// checked for tail call eligibility.
2774 bool parametersInCSRMatch(const MachineRegisterInfo &MRI,
2775 const uint32_t *CallerPreservedMask,
2776 const SmallVectorImpl<CCValAssign> &ArgLocs,
2777 const SmallVectorImpl<SDValue> &OutVals) const;
2778
2779 //===--------------------------------------------------------------------===//
2780 // TargetLowering Optimization Methods
2781 //
2782
2783 /// A convenience struct that encapsulates a DAG, and two SDValues for
2784 /// returning information from TargetLowering to its clients that want to
2785 /// combine.
2786 struct TargetLoweringOpt {
2787 SelectionDAG &DAG;
2788 bool LegalTys;
2789 bool LegalOps;
2790 SDValue Old;
2791 SDValue New;
2792
2793 explicit TargetLoweringOpt(SelectionDAG &InDAG,
2794 bool LT, bool LO) :
2795 DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
2796
2797 bool LegalTypes() const { return LegalTys; }
2798 bool LegalOperations() const { return LegalOps; }
2799
2800 bool CombineTo(SDValue O, SDValue N) {
2801 Old = O;
2802 New = N;
2803 return true;
2804 }
2805 };
2806
2807 /// Check to see if the specified operand of the specified instruction is a
2808 /// constant integer. If so, check to see if there are any bits set in the
2809 /// constant that are not demanded. If so, shrink the constant and return
2810 /// true.
2811 bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded,
2812 TargetLoweringOpt &TLO) const;
2813
2814 // Target hook to do target-specific const optimization, which is called by
2815 // ShrinkDemandedConstant. This function should return true if the target
2816 // doesn't want ShrinkDemandedConstant to further optimize the constant.
2817 virtual bool targetShrinkDemandedConstant(SDValue Op, const APInt &Demanded,
2818 TargetLoweringOpt &TLO) const {
2819 return false;
2820 }
2821
2822 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. This
2823 /// uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
2824 /// generalized for targets with other types of implicit widening casts.
2825 bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
2826 TargetLoweringOpt &TLO) const;
2827
2828 /// Helper for SimplifyDemandedBits that can simplify an operation with
2829 /// multiple uses. This function simplifies operand \p OpIdx of \p User and
2830 /// then updates \p User with the simplified version. No other uses of
2831 /// \p OpIdx are updated. If \p User is the only user of \p OpIdx, this
2832 /// function behaves exactly like function SimplifyDemandedBits declared
2833 /// below except that it also updates the DAG by calling
2834 /// DCI.CommitTargetLoweringOpt.
2835 bool SimplifyDemandedBits(SDNode *User, unsigned OpIdx, const APInt &Demanded,
2836 DAGCombinerInfo &DCI, TargetLoweringOpt &TLO) const;
2837
2838 /// Look at Op. At this point, we know that only the DemandedMask bits of the
2839 /// result of Op are ever used downstream. If we can use this information to
2840 /// simplify Op, create a new simplified DAG node and return true, returning
2841 /// the original and new nodes in Old and New. Otherwise, analyze the
2842 /// expression and return a mask of KnownOne and KnownZero bits for the
2843 /// expression (used to simplify the caller). The KnownZero/One bits may only
2844 /// be accurate for those bits in the DemandedMask.
2845 /// \p AssumeSingleUse When this parameter is true, this function will
2846 /// attempt to simplify \p Op even if there are multiple uses.
2847 /// Callers are responsible for correctly updating the DAG based on the
2848 /// results of this function, because simply replacing replacing TLO.Old
2849 /// with TLO.New will be incorrect when this parameter is true and TLO.Old
2850 /// has multiple uses.
2851 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
2852 KnownBits &Known,
2853 TargetLoweringOpt &TLO,
2854 unsigned Depth = 0,
2855 bool AssumeSingleUse = false) const;
2856
2857 /// Helper wrapper around SimplifyDemandedBits.
2858 /// Adds Op back to the worklist upon success.
2859 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
2860 DAGCombinerInfo &DCI) const;
2861
2862 /// Look at Vector Op. At this point, we know that only the DemandedElts
2863 /// elements of the result of Op are ever used downstream. If we can use
2864 /// this information to simplify Op, create a new simplified DAG node and
2865 /// return true, storing the original and new nodes in TLO.
2866 /// Otherwise, analyze the expression and return a mask of KnownUndef and
2867 /// KnownZero elements for the expression (used to simplify the caller).
2868 /// The KnownUndef/Zero elements may only be accurate for those bits
2869 /// in the DemandedMask.
2870 /// \p AssumeSingleUse When this parameter is true, this function will
2871 /// attempt to simplify \p Op even if there are multiple uses.
2872 /// Callers are responsible for correctly updating the DAG based on the
2873 /// results of this function, because simply replacing replacing TLO.Old
2874 /// with TLO.New will be incorrect when this parameter is true and TLO.Old
2875 /// has multiple uses.
2876 bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedEltMask,
2877 APInt &KnownUndef, APInt &KnownZero,
2878 TargetLoweringOpt &TLO, unsigned Depth = 0,
2879 bool AssumeSingleUse = false) const;
2880
2881 /// Helper wrapper around SimplifyDemandedVectorElts.
2882 /// Adds Op back to the worklist upon success.
2883 bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedElts,
2884 APInt &KnownUndef, APInt &KnownZero,
2885 DAGCombinerInfo &DCI) const;
2886
2887 /// Determine which of the bits specified in Mask are known to be either zero
2888 /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
2889 /// argument allows us to only collect the known bits that are shared by the
2890 /// requested vector elements.
2891 virtual void computeKnownBitsForTargetNode(const SDValue Op,
2892 KnownBits &Known,
2893 const APInt &DemandedElts,
2894 const SelectionDAG &DAG,
2895 unsigned Depth = 0) const;
2896
2897 /// Determine which of the bits of FrameIndex \p FIOp are known to be 0.
2898 /// Default implementation computes low bits based on alignment
2899 /// information. This should preserve known bits passed into it.
2900 virtual void computeKnownBitsForFrameIndex(const SDValue FIOp,
2901 KnownBits &Known,
2902 const APInt &DemandedElts,
2903 const SelectionDAG &DAG,
2904 unsigned Depth = 0) const;
2905
2906 /// This method can be implemented by targets that want to expose additional
2907 /// information about sign bits to the DAG Combiner. The DemandedElts
2908 /// argument allows us to only collect the minimum sign bits that are shared
2909 /// by the requested vector elements.
2910 virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
2911 const APInt &DemandedElts,
2912 const SelectionDAG &DAG,
2913 unsigned Depth = 0) const;
2914
2915 /// Attempt to simplify any target nodes based on the demanded vector
2916 /// elements, returning true on success. Otherwise, analyze the expression and
2917 /// return a mask of KnownUndef and KnownZero elements for the expression
2918 /// (used to simplify the caller). The KnownUndef/Zero elements may only be
2919 /// accurate for those bits in the DemandedMask.
2920 virtual bool SimplifyDemandedVectorEltsForTargetNode(
2921 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef,
2922 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth = 0) const;
2923
2924 /// Attempt to simplify any target nodes based on the demanded bits,
2925 /// returning true on success. Otherwise, analyze the
2926 /// expression and return a mask of KnownOne and KnownZero bits for the
2927 /// expression (used to simplify the caller). The KnownZero/One bits may only
2928 /// be accurate for those bits in the DemandedMask.
2929 virtual bool SimplifyDemandedBitsForTargetNode(SDValue Op,
2930 const APInt &DemandedBits,
2931 KnownBits &Known,
2932 TargetLoweringOpt &TLO,
2933 unsigned Depth = 0) const;
2934
2935 /// If \p SNaN is false, \returns true if \p Op is known to never be any
2936 /// NaN. If \p sNaN is true, returns if \p Op is known to never be a signaling
2937 /// NaN.
2938 virtual bool isKnownNeverNaNForTargetNode(SDValue Op,
2939 const SelectionDAG &DAG,
2940 bool SNaN = false,
2941 unsigned Depth = 0) const;
2942 struct DAGCombinerInfo {
2943 void *DC; // The DAG Combiner object.
2944 CombineLevel Level;
2945 bool CalledByLegalizer;
2946
2947 public:
2948 SelectionDAG &DAG;
2949
2950 DAGCombinerInfo(SelectionDAG &dag, CombineLevel level, bool cl, void *dc)
2951 : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
2952
2953 bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
2954 bool isBeforeLegalizeOps() const { return Level < AfterLegalizeVectorOps; }
2955 bool isAfterLegalizeDAG() const {
2956 return Level == AfterLegalizeDAG;
2957 }
2958 CombineLevel getDAGCombineLevel() { return Level; }
2959 bool isCalledByLegalizer() const { return CalledByLegalizer; }
2960
2961 void AddToWorklist(SDNode *N);
2962 SDValue CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo = true);
2963 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
2964 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
2965
2966 void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
2967 };
2968
2969 /// Return if the N is a constant or constant vector equal to the true value
2970 /// from getBooleanContents().
2971 bool isConstTrueVal(const SDNode *N) const;
2972
2973 /// Return if the N is a constant or constant vector equal to the false value
2974 /// from getBooleanContents().
2975 bool isConstFalseVal(const SDNode *N) const;
2976
2977 /// Return if \p N is a True value when extended to \p VT.
2978 bool isExtendedTrueVal(const ConstantSDNode *N, EVT VT, bool SExt) const;
2979
2980 /// Try to simplify a setcc built with the specified operands and cc. If it is
2981 /// unable to simplify it, return a null SDValue.
2982 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
2983 bool foldBooleans, DAGCombinerInfo &DCI,
2984 const SDLoc &dl) const;
2985
2986 // For targets which wrap address, unwrap for analysis.
2987 virtual SDValue unwrapAddress(SDValue N) const { return N; }
2988
2989 /// Returns true (and the GlobalValue and the offset) if the node is a
2990 /// GlobalAddress + offset.
2991 virtual bool
2992 isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
2993
2994 /// This method will be invoked for all target nodes and for any
2995 /// target-independent nodes that the target has registered with invoke it
2996 /// for.
2997 ///
2998 /// The semantics are as follows:
2999 /// Return Value:
3000 /// SDValue.Val == 0 - No change was made
3001 /// SDValue.Val == N - N was replaced, is dead, and is already handled.
3002 /// otherwise - N should be replaced by the returned Operand.
3003 ///
3004 /// In addition, methods provided by DAGCombinerInfo may be used to perform
3005 /// more complex transformations.
3006 ///
3007 virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
3008
3009 /// Return true if it is profitable to move this shift by a constant amount
3010 /// though its operand, adjusting any immediate operands as necessary to
3011 /// preserve semantics. This transformation may not be desirable if it
3012 /// disrupts a particularly auspicious target-specific tree (e.g. bitfield
3013 /// extraction in AArch64). By default, it returns true.
3014 ///
3015 /// @param N the shift node
3016 /// @param Level the current DAGCombine legalization level.
3017 virtual bool isDesirableToCommuteWithShift(const SDNode *N,
3018 CombineLevel Level) const {
3019 return true;
3020 }
3021
3022 // Return true if it is profitable to combine a BUILD_VECTOR with a stride-pattern
3023 // to a shuffle and a truncate.
3024 // Example of such a combine:
3025 // v4i32 build_vector((extract_elt V, 1),
3026 // (extract_elt V, 3),
3027 // (extract_elt V, 5),
3028 // (extract_elt V, 7))
3029 // -->
3030 // v4i32 truncate (bitcast (shuffle<1,u,3,u,5,u,7,u> V, u) to v4i64)
3031 virtual bool isDesirableToCombineBuildVectorToShuffleTruncate(
3032 ArrayRef<int> ShuffleMask, EVT SrcVT, EVT TruncVT) const {
3033 return false;
3034 }
3035
3036 /// Return true if the target has native support for the specified value type
3037 /// and it is 'desirable' to use the type for the given node type. e.g. On x86
3038 /// i16 is legal, but undesirable since i16 instruction encodings are longer
3039 /// and some i16 instructions are slow.
3040 virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
3041 // By default, assume all legal types are desirable.
3042 return isTypeLegal(VT);
3043 }
3044
3045 /// Return true if it is profitable for dag combiner to transform a floating
3046 /// point op of specified opcode to a equivalent op of an integer
3047 /// type. e.g. f32 load -> i32 load can be profitable on ARM.
3048 virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
3049 EVT /*VT*/) const {
3050 return false;
3051 }
3052
3053 /// This method query the target whether it is beneficial for dag combiner to
3054 /// promote the specified node. If true, it should return the desired
3055 /// promotion type by reference.
3056 virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
3057 return false;
3058 }
3059
3060 /// Return true if the target supports swifterror attribute. It optimizes
3061 /// loads and stores to reading and writing a specific register.
3062 virtual bool supportSwiftError() const {
3063 return false;
3064 }
3065
3066 /// Return true if the target supports that a subset of CSRs for the given
3067 /// machine function is handled explicitly via copies.
3068 virtual bool supportSplitCSR(MachineFunction *MF) const {
3069 return false;
3070 }
3071
3072 /// Perform necessary initialization to handle a subset of CSRs explicitly
3073 /// via copies. This function is called at the beginning of instruction
3074 /// selection.
3075 virtual void initializeSplitCSR(MachineBasicBlock *Entry) const {
3076 llvm_unreachable("Not Implemented")::llvm::llvm_unreachable_internal("Not Implemented", "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 3076)
;
3077 }
3078
3079 /// Insert explicit copies in entry and exit blocks. We copy a subset of
3080 /// CSRs to virtual registers in the entry block, and copy them back to
3081 /// physical registers in the exit blocks. This function is called at the end
3082 /// of instruction selection.
3083 virtual void insertCopiesSplitCSR(
3084 MachineBasicBlock *Entry,
3085 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
3086 llvm_unreachable("Not Implemented")::llvm::llvm_unreachable_internal("Not Implemented", "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 3086)
;
3087 }
3088
3089 //===--------------------------------------------------------------------===//
3090 // Lowering methods - These methods must be implemented by targets so that
3091 // the SelectionDAGBuilder code knows how to lower these.
3092 //
3093
3094 /// This hook must be implemented to lower the incoming (formal) arguments,
3095 /// described by the Ins array, into the specified DAG. The implementation
3096 /// should fill in the InVals array with legal-type argument values, and
3097 /// return the resulting token chain value.
3098 virtual SDValue LowerFormalArguments(
3099 SDValue /*Chain*/, CallingConv::ID /*CallConv*/, bool /*isVarArg*/,
3100 const SmallVectorImpl<ISD::InputArg> & /*Ins*/, const SDLoc & /*dl*/,
3101 SelectionDAG & /*DAG*/, SmallVectorImpl<SDValue> & /*InVals*/) const {
3102 llvm_unreachable("Not Implemented")::llvm::llvm_unreachable_internal("Not Implemented", "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 3102)
;
3103 }
3104
3105 /// This structure contains all information that is necessary for lowering
3106 /// calls. It is passed to TLI::LowerCallTo when the SelectionDAG builder
3107 /// needs to lower a call, and targets will see this struct in their LowerCall
3108 /// implementation.
3109 struct CallLoweringInfo {
3110 SDValue Chain;
3111 Type *RetTy = nullptr;
3112 bool RetSExt : 1;
3113 bool RetZExt : 1;
3114 bool IsVarArg : 1;
3115 bool IsInReg : 1;
3116 bool DoesNotReturn : 1;
3117 bool IsReturnValueUsed : 1;
3118 bool IsConvergent : 1;
3119 bool IsPatchPoint : 1;
3120
3121 // IsTailCall should be modified by implementations of
3122 // TargetLowering::LowerCall that perform tail call conversions.
3123 bool IsTailCall = false;
3124
3125 // Is Call lowering done post SelectionDAG type legalization.
3126 bool IsPostTypeLegalization = false;
3127
3128 unsigned NumFixedArgs = -1;
3129 CallingConv::ID CallConv = CallingConv::C;
3130 SDValue Callee;
3131 ArgListTy Args;
3132 SelectionDAG &DAG;
3133 SDLoc DL;
3134 ImmutableCallSite CS;
3135 SmallVector<ISD::OutputArg, 32> Outs;
3136 SmallVector<SDValue, 32> OutVals;
3137 SmallVector<ISD::InputArg, 32> Ins;
3138 SmallVector<SDValue, 4> InVals;
3139
3140 CallLoweringInfo(SelectionDAG &DAG)
3141 : RetSExt(false), RetZExt(false), IsVarArg(false), IsInReg(false),
3142 DoesNotReturn(false), IsReturnValueUsed(true), IsConvergent(false),
3143 IsPatchPoint(false), DAG(DAG) {}
3144
3145 CallLoweringInfo &setDebugLoc(const SDLoc &dl) {
3146 DL = dl;
3147 return *this;
3148 }
3149
3150 CallLoweringInfo &setChain(SDValue InChain) {
3151 Chain = InChain;
3152 return *this;
3153 }
3154
3155 // setCallee with target/module-specific attributes
3156 CallLoweringInfo &setLibCallee(CallingConv::ID CC, Type *ResultType,
3157 SDValue Target, ArgListTy &&ArgsList) {
3158 RetTy = ResultType;
3159 Callee = Target;
3160 CallConv = CC;
3161 NumFixedArgs = ArgsList.size();
3162 Args = std::move(ArgsList);
3163
3164 DAG.getTargetLoweringInfo().markLibCallAttributes(
3165 &(DAG.getMachineFunction()), CC, Args);
3166 return *this;
3167 }
3168
3169 CallLoweringInfo &setCallee(CallingConv::ID CC, Type *ResultType,
3170 SDValue Target, ArgListTy &&ArgsList) {
3171 RetTy = ResultType;
3172 Callee = Target;
3173 CallConv = CC;
3174 NumFixedArgs = ArgsList.size();
3175 Args = std::move(ArgsList);
3176 return *this;
3177 }
3178
3179 CallLoweringInfo &setCallee(Type *ResultType, FunctionType *FTy,
3180 SDValue Target, ArgListTy &&ArgsList,
3181 ImmutableCallSite Call) {
3182 RetTy = ResultType;
3183
3184 IsInReg = Call.hasRetAttr(Attribute::InReg);
3185 DoesNotReturn =
3186 Call.doesNotReturn() ||
3187 (!Call.isInvoke() &&
3188 isa<UnreachableInst>(Call.getInstruction()->getNextNode()));
3189 IsVarArg = FTy->isVarArg();
3190 IsReturnValueUsed = !Call.getInstruction()->use_empty();
3191 RetSExt = Call.hasRetAttr(Attribute::SExt);
3192 RetZExt = Call.hasRetAttr(Attribute::ZExt);
3193
3194 Callee = Target;
3195
3196 CallConv = Call.getCallingConv();
3197 NumFixedArgs = FTy->getNumParams();
3198 Args = std::move(ArgsList);
3199
3200 CS = Call;
3201
3202 return *this;
3203 }
3204
3205 CallLoweringInfo &setInRegister(bool Value = true) {
3206 IsInReg = Value;
3207 return *this;
3208 }
3209
3210 CallLoweringInfo &setNoReturn(bool Value = true) {
3211 DoesNotReturn = Value;
3212 return *this;
3213 }
3214
3215 CallLoweringInfo &setVarArg(bool Value = true) {
3216 IsVarArg = Value;
3217 return *this;
3218 }
3219
3220 CallLoweringInfo &setTailCall(bool Value = true) {
3221 IsTailCall = Value;
3222 return *this;
3223 }
3224
3225 CallLoweringInfo &setDiscardResult(bool Value = true) {
3226 IsReturnValueUsed = !Value;
3227 return *this;
3228 }
3229
3230 CallLoweringInfo &setConvergent(bool Value = true) {
3231 IsConvergent = Value;
3232 return *this;
3233 }
3234
3235 CallLoweringInfo &setSExtResult(bool Value = true) {
3236 RetSExt = Value;
3237 return *this;
3238 }
3239
3240 CallLoweringInfo &setZExtResult(bool Value = true) {
3241 RetZExt = Value;
3242 return *this;
3243 }
3244
3245 CallLoweringInfo &setIsPatchPoint(bool Value = true) {
3246 IsPatchPoint = Value;
3247 return *this;
3248 }
3249
3250 CallLoweringInfo &setIsPostTypeLegalization(bool Value=true) {
3251 IsPostTypeLegalization = Value;
3252 return *this;
3253 }
3254
3255 ArgListTy &getArgs() {
3256 return Args;
3257 }
3258 };
3259
3260 /// This function lowers an abstract call to a function into an actual call.
3261 /// This returns a pair of operands. The first element is the return value
3262 /// for the function (if RetTy is not VoidTy). The second element is the
3263 /// outgoing token chain. It calls LowerCall to do the actual lowering.
3264 std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
3265
3266 /// This hook must be implemented to lower calls into the specified
3267 /// DAG. The outgoing arguments to the call are described by the Outs array,
3268 /// and the values to be returned by the call are described by the Ins
3269 /// array. The implementation should fill in the InVals array with legal-type
3270 /// return values from the call, and return the resulting token chain value.
3271 virtual SDValue
3272 LowerCall(CallLoweringInfo &/*CLI*/,
3273 SmallVectorImpl<SDValue> &/*InVals*/) const {
3274 llvm_unreachable("Not Implemented")::llvm::llvm_unreachable_internal("Not Implemented", "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 3274)
;
3275 }
3276
3277 /// Target-specific cleanup for formal ByVal parameters.
3278 virtual void HandleByVal(CCState *, unsigned &, unsigned) const {}
3279
3280 /// This hook should be implemented to check whether the return values
3281 /// described by the Outs array can fit into the return registers. If false
3282 /// is returned, an sret-demotion is performed.
3283 virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
3284 MachineFunction &/*MF*/, bool /*isVarArg*/,
3285 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
3286 LLVMContext &/*Context*/) const
3287 {
3288 // Return true by default to get preexisting behavior.
3289 return true;
3290 }
3291
3292 /// This hook must be implemented to lower outgoing return values, described
3293 /// by the Outs array, into the specified DAG. The implementation should
3294 /// return the resulting token chain value.
3295 virtual SDValue LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
3296 bool /*isVarArg*/,
3297 const SmallVectorImpl<ISD::OutputArg> & /*Outs*/,
3298 const SmallVectorImpl<SDValue> & /*OutVals*/,
3299 const SDLoc & /*dl*/,
3300 SelectionDAG & /*DAG*/) const {
3301 llvm_unreachable("Not Implemented")::llvm::llvm_unreachable_internal("Not Implemented", "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 3301)
;
3302 }
3303
3304 /// Return true if result of the specified node is used by a return node
3305 /// only. It also compute and return the input chain for the tail call.
3306 ///
3307 /// This is used to determine whether it is possible to codegen a libcall as
3308 /// tail call at legalization time.
3309 virtual bool isUsedByReturnOnly(SDNode *, SDValue &/*Chain*/) const {
3310 return false;
3311 }
3312
3313 /// Return true if the target may be able emit the call instruction as a tail
3314 /// call. This is used by optimization passes to determine if it's profitable
3315 /// to duplicate return instructions to enable tailcall optimization.
3316 virtual bool mayBeEmittedAsTailCall(const CallInst *) const {
3317 return false;
3318 }
3319
3320 /// Return the builtin name for the __builtin___clear_cache intrinsic
3321 /// Default is to invoke the clear cache library call
3322 virtual const char * getClearCacheBuiltinName() const {
3323 return "__clear_cache";
3324 }
3325
3326 /// Return the register ID of the name passed in. Used by named register
3327 /// global variables extension. There is no target-independent behaviour
3328 /// so the default action is to bail.
3329 virtual unsigned getRegisterByName(const char* RegName, EVT VT,
3330 SelectionDAG &DAG) const {
3331 report_fatal_error("Named registers not implemented for this target");
3332 }
3333
3334 /// Return the type that should be used to zero or sign extend a
3335 /// zeroext/signext integer return value. FIXME: Some C calling conventions
3336 /// require the return type to be promoted, but this is not true all the time,
3337 /// e.g. i1/i8/i16 on x86/x86_64. It is also not necessary for non-C calling
3338 /// conventions. The frontend should handle this and include all of the
3339 /// necessary information.
3340 virtual EVT getTypeForExtReturn(LLVMContext &Context, EVT VT,
3341 ISD::NodeType /*ExtendKind*/) const {
3342 EVT MinVT = getRegisterType(Context, MVT::i32);
3343 return VT.bitsLT(MinVT) ? MinVT : VT;
3344 }
3345
3346 /// For some targets, an LLVM struct type must be broken down into multiple
3347 /// simple types, but the calling convention specifies that the entire struct
3348 /// must be passed in a block of consecutive registers.
3349 virtual bool
3350 functionArgumentNeedsConsecutiveRegisters(Type *Ty, CallingConv::ID CallConv,
3351 bool isVarArg) const {
3352 return false;
3353 }
3354
3355 /// Returns a 0 terminated array of registers that can be safely used as
3356 /// scratch registers.
3357 virtual const MCPhysReg *getScratchRegisters(CallingConv::ID CC) const {
3358 return nullptr;
3359 }
3360
3361 /// This callback is used to prepare for a volatile or atomic load.
3362 /// It takes a chain node as input and returns the chain for the load itself.
3363 ///
3364 /// Having a callback like this is necessary for targets like SystemZ,
3365 /// which allows a CPU to reuse the result of a previous load indefinitely,
3366 /// even if a cache-coherent store is performed by another CPU. The default
3367 /// implementation does nothing.
3368 virtual SDValue prepareVolatileOrAtomicLoad(SDValue Chain, const SDLoc &DL,
3369 SelectionDAG &DAG) const {
3370 return Chain;
3371 }
3372
3373 /// This callback is used to inspect load/store instructions and add
3374 /// target-specific MachineMemOperand flags to them. The default
3375 /// implementation does nothing.
3376 virtual MachineMemOperand::Flags getMMOFlags(const Instruction &I) const {
3377 return MachineMemOperand::MONone;
3378 }
3379
3380 /// This callback is invoked by the type legalizer to legalize nodes with an
3381 /// illegal operand type but legal result types. It replaces the
3382 /// LowerOperation callback in the type Legalizer. The reason we can not do
3383 /// away with LowerOperation entirely is that LegalizeDAG isn't yet ready to
3384 /// use this callback.
3385 ///
3386 /// TODO: Consider merging with ReplaceNodeResults.
3387 ///
3388 /// The target places new result values for the node in Results (their number
3389 /// and types must exactly match those of the original return values of
3390 /// the node), or leaves Results empty, which indicates that the node is not
3391 /// to be custom lowered after all.
3392 /// The default implementation calls LowerOperation.
3393 virtual void LowerOperationWrapper(SDNode *N,
3394 SmallVectorImpl<SDValue> &Results,
3395 SelectionDAG &DAG) const;
3396
3397 /// This callback is invoked for operations that are unsupported by the
3398 /// target, which are registered to use 'custom' lowering, and whose defined
3399 /// values are all legal. If the target has no operations that require custom
3400 /// lowering, it need not implement this. The default implementation of this
3401 /// aborts.
3402 virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
3403
3404 /// This callback is invoked when a node result type is illegal for the
3405 /// target, and the operation was registered to use 'custom' lowering for that
3406 /// result type. The target places new result values for the node in Results
3407 /// (their number and types must exactly match those of the original return
3408 /// values of the node), or leaves Results empty, which indicates that the
3409 /// node is not to be custom lowered after all.
3410 ///
3411 /// If the target has no operations that require custom lowering, it need not
3412 /// implement this. The default implementation aborts.
3413 virtual void ReplaceNodeResults(SDNode * /*N*/,
3414 SmallVectorImpl<SDValue> &/*Results*/,
3415 SelectionDAG &/*DAG*/) const {
3416 llvm_unreachable("ReplaceNodeResults not implemented for this target!")::llvm::llvm_unreachable_internal("ReplaceNodeResults not implemented for this target!"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/CodeGen/TargetLowering.h"
, 3416)
;
3417 }
3418
3419 /// This method returns the name of a target specific DAG node.
3420 virtual const char *getTargetNodeName(unsigned Opcode) const;
3421
3422 /// This method returns a target specific FastISel object, or null if the
3423 /// target does not support "fast" ISel.
3424 virtual FastISel *createFastISel(FunctionLoweringInfo &,
3425 const TargetLibraryInfo *) const {
3426 return nullptr;
3427 }
3428
3429 bool verifyReturnAddressArgumentIsConstant(SDValue Op,
3430 SelectionDAG &DAG) const;
3431
3432 //===--------------------------------------------------------------------===//
3433 // Inline Asm Support hooks
3434 //
3435
3436 /// This hook allows the target to expand an inline asm call to be explicit
3437 /// llvm code if it wants to. This is useful for turning simple inline asms
3438 /// into LLVM intrinsics, which gives the compiler more information about the
3439 /// behavior of the code.
3440 virtual bool ExpandInlineAsm(CallInst *) const {
3441 return false;
3442 }
3443
3444 enum ConstraintType {
3445 C_Register, // Constraint represents specific register(s).
3446 C_RegisterClass, // Constraint represents any of register(s) in class.
3447 C_Memory, // Memory constraint.
3448 C_Other, // Something else.
3449 C_Unknown // Unsupported constraint.
3450 };
3451
3452 enum ConstraintWeight {
3453 // Generic weights.
3454 CW_Invalid = -1, // No match.
3455 CW_Okay = 0, // Acceptable.
3456 CW_Good = 1, // Good weight.
3457 CW_Better = 2, // Better weight.
3458 CW_Best = 3, // Best weight.
3459
3460 // Well-known weights.
3461 CW_SpecificReg = CW_Okay, // Specific register operands.
3462 CW_Register = CW_Good, // Register operands.
3463 CW_Memory = CW_Better, // Memory operands.
3464 CW_Constant = CW_Best, // Constant operand.
3465 CW_Default = CW_Okay // Default or don't know type.
3466 };
3467
3468 /// This contains information for each constraint that we are lowering.
3469 struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
3470 /// This contains the actual string for the code, like "m". TargetLowering
3471 /// picks the 'best' code from ConstraintInfo::Codes that most closely
3472 /// matches the operand.
3473 std::string ConstraintCode;
3474
3475 /// Information about the constraint code, e.g. Register, RegisterClass,
3476 /// Memory, Other, Unknown.
3477 TargetLowering::ConstraintType ConstraintType = TargetLowering::C_Unknown;
3478
3479 /// If this is the result output operand or a clobber, this is null,
3480 /// otherwise it is the incoming operand to the CallInst. This gets
3481 /// modified as the asm is processed.
3482 Value *CallOperandVal = nullptr;
3483
3484 /// The ValueType for the operand value.
3485 MVT ConstraintVT = MVT::Other;
3486
3487 /// Copy constructor for copying from a ConstraintInfo.
3488 AsmOperandInfo(InlineAsm::ConstraintInfo Info)
3489 : InlineAsm::ConstraintInfo(std::move(Info)) {}
3490
3491 /// Return true of this is an input operand that is a matching constraint
3492 /// like "4".
3493 bool isMatchingInputConstraint() const;
3494
3495 /// If this is an input matching constraint, this method returns the output
3496 /// operand it matches.
3497 unsigned getMatchedOperand() const;
3498 };
3499
3500 using AsmOperandInfoVector = std::vector<AsmOperandInfo>;
3501
3502 /// Split up the constraint string from the inline assembly value into the
3503 /// specific constraints and their prefixes, and also tie in the associated
3504 /// operand values. If this returns an empty vector, and if the constraint
3505 /// string itself isn't empty, there was an error parsing.
3506 virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL,
3507 const TargetRegisterInfo *TRI,
3508 ImmutableCallSite CS) const;
3509
3510 /// Examine constraint type and operand type and determine a weight value.
3511 /// The operand object must already have been set up with the operand type.
3512 virtual ConstraintWeight getMultipleConstraintMatchWeight(
3513 AsmOperandInfo &info, int maIndex) const;
3514
3515 /// Examine constraint string and operand type and determine a weight value.
3516 /// The operand object must already have been set up with the operand type.
3517 virtual ConstraintWeight getSingleConstraintMatchWeight(
3518 AsmOperandInfo &info, const char *constraint) const;
3519
3520 /// Determines the constraint code and constraint type to use for the specific
3521 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
3522 /// If the actual operand being passed in is available, it can be passed in as
3523 /// Op, otherwise an empty SDValue can be passed.
3524 virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
3525 SDValue Op,
3526 SelectionDAG *DAG = nullptr) const;
3527
3528 /// Given a constraint, return the type of constraint it is for this target.
3529 virtual ConstraintType getConstraintType(StringRef Constraint) const;
3530
3531 /// Given a physical register constraint (e.g. {edx}), return the register
3532 /// number and the register class for the register.
3533 ///
3534 /// Given a register class constraint, like 'r', if this corresponds directly
3535 /// to an LLVM register class, return a register of 0 and the register class
3536 /// pointer.
3537 ///
3538 /// This should only be used for C_Register constraints. On error, this
3539 /// returns a register number of 0 and a null register class pointer.
3540 virtual std::pair<unsigned, const TargetRegisterClass *>
3541 getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
3542 StringRef Constraint, MVT VT) const;
3543
3544 virtual unsigned getInlineAsmMemConstraint(StringRef ConstraintCode) const {
3545 if (ConstraintCode == "i")
3546 return InlineAsm::Constraint_i;
3547 else if (ConstraintCode == "m")
3548 return InlineAsm::Constraint_m;
3549 return InlineAsm::Constraint_Unknown;
3550 }
3551
3552 /// Try to replace an X constraint, which matches anything, with another that
3553 /// has more specific requirements based on the type of the corresponding
3554 /// operand. This returns null if there is no replacement to make.
3555 virtual const char *LowerXConstraint(EVT ConstraintVT) const;
3556
3557 /// Lower the specified operand into the Ops vector. If it is invalid, don't
3558 /// add anything to Ops.
3559 virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
3560 std::vector<SDValue> &Ops,
3561 SelectionDAG &DAG) const;
3562
3563 //===--------------------------------------------------------------------===//
3564 // Div utility functions
3565 //
3566 SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
3567 SmallVectorImpl<SDNode *> &Created) const;
3568 SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
3569 SmallVectorImpl<SDNode *> &Created) const;
3570
3571 /// Targets may override this function to provide custom SDIV lowering for
3572 /// power-of-2 denominators. If the target returns an empty SDValue, LLVM
3573 /// assumes SDIV is expensive and replaces it with a series of other integer
3574 /// operations.
3575 virtual SDValue BuildSDIVPow2(SDNode *N, const APInt &Divisor,
3576 SelectionDAG &DAG,
3577 SmallVectorImpl<SDNode *> &Created) const;
3578
3579 /// Indicate whether this target prefers to combine FDIVs with the same
3580 /// divisor. If the transform should never be done, return zero. If the
3581 /// transform should be done, return the minimum number of divisor uses
3582 /// that must exist.
3583 virtual unsigned combineRepeatedFPDivisors() const {
3584 return 0;