[llvm-objdump] - Remove one overload of reportError. NFCI.
[llvm-complete.git] / lib / CodeGen / TargetLoweringBase.cpp
blob40ecef5855df7403a0717e9b15fc8ec3e33149b0
1 //===- TargetLoweringBase.cpp - Implement the TargetLoweringBase class ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements the TargetLoweringBase class.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/ADT/BitVector.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/CodeGen/Analysis.h"
21 #include "llvm/CodeGen/ISDOpcodes.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineMemOperand.h"
28 #include "llvm/CodeGen/MachineOperand.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/RuntimeLibcalls.h"
31 #include "llvm/CodeGen/StackMaps.h"
32 #include "llvm/CodeGen/TargetLowering.h"
33 #include "llvm/CodeGen/TargetOpcodes.h"
34 #include "llvm/CodeGen/TargetRegisterInfo.h"
35 #include "llvm/CodeGen/ValueTypes.h"
36 #include "llvm/IR/Attributes.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/DataLayout.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalValue.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/IRBuilder.h"
44 #include "llvm/IR/Module.h"
45 #include "llvm/IR/Type.h"
46 #include "llvm/Support/BranchProbability.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Compiler.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MachineValueType.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetMachine.h"
54 #include <algorithm>
55 #include <cassert>
56 #include <cstddef>
57 #include <cstdint>
58 #include <cstring>
59 #include <iterator>
60 #include <string>
61 #include <tuple>
62 #include <utility>
64 using namespace llvm;
66 static cl::opt<bool> JumpIsExpensiveOverride(
67 "jump-is-expensive", cl::init(false),
68 cl::desc("Do not create extra branches to split comparison logic."),
69 cl::Hidden);
71 static cl::opt<unsigned> MinimumJumpTableEntries
72 ("min-jump-table-entries", cl::init(4), cl::Hidden,
73 cl::desc("Set minimum number of entries to use a jump table."));
75 static cl::opt<unsigned> MaximumJumpTableSize
76 ("max-jump-table-size", cl::init(UINT_MAX), cl::Hidden,
77 cl::desc("Set maximum size of jump tables."));
79 /// Minimum jump table density for normal functions.
80 static cl::opt<unsigned>
81 JumpTableDensity("jump-table-density", cl::init(10), cl::Hidden,
82 cl::desc("Minimum density for building a jump table in "
83 "a normal function"));
85 /// Minimum jump table density for -Os or -Oz functions.
86 static cl::opt<unsigned> OptsizeJumpTableDensity(
87 "optsize-jump-table-density", cl::init(40), cl::Hidden,
88 cl::desc("Minimum density for building a jump table in "
89 "an optsize function"));
91 static bool darwinHasSinCos(const Triple &TT) {
92 assert(TT.isOSDarwin() && "should be called with darwin triple");
93 // Don't bother with 32 bit x86.
94 if (TT.getArch() == Triple::x86)
95 return false;
96 // Macos < 10.9 has no sincos_stret.
97 if (TT.isMacOSX())
98 return !TT.isMacOSXVersionLT(10, 9) && TT.isArch64Bit();
99 // iOS < 7.0 has no sincos_stret.
100 if (TT.isiOS())
101 return !TT.isOSVersionLT(7, 0);
102 // Any other darwin such as WatchOS/TvOS is new enough.
103 return true;
106 // Although this default value is arbitrary, it is not random. It is assumed
107 // that a condition that evaluates the same way by a higher percentage than this
108 // is best represented as control flow. Therefore, the default value N should be
109 // set such that the win from N% correct executions is greater than the loss
110 // from (100 - N)% mispredicted executions for the majority of intended targets.
111 static cl::opt<int> MinPercentageForPredictableBranch(
112 "min-predictable-branch", cl::init(99),
113 cl::desc("Minimum percentage (0-100) that a condition must be either true "
114 "or false to assume that the condition is predictable"),
115 cl::Hidden);
117 void TargetLoweringBase::InitLibcalls(const Triple &TT) {
118 #define HANDLE_LIBCALL(code, name) \
119 setLibcallName(RTLIB::code, name);
120 #include "llvm/IR/RuntimeLibcalls.def"
121 #undef HANDLE_LIBCALL
122 // Initialize calling conventions to their default.
123 for (int LC = 0; LC < RTLIB::UNKNOWN_LIBCALL; ++LC)
124 setLibcallCallingConv((RTLIB::Libcall)LC, CallingConv::C);
126 // For IEEE quad-precision libcall names, PPC uses "kf" instead of "tf".
127 if (TT.getArch() == Triple::ppc || TT.isPPC64()) {
128 setLibcallName(RTLIB::ADD_F128, "__addkf3");
129 setLibcallName(RTLIB::SUB_F128, "__subkf3");
130 setLibcallName(RTLIB::MUL_F128, "__mulkf3");
131 setLibcallName(RTLIB::DIV_F128, "__divkf3");
132 setLibcallName(RTLIB::FPEXT_F32_F128, "__extendsfkf2");
133 setLibcallName(RTLIB::FPEXT_F64_F128, "__extenddfkf2");
134 setLibcallName(RTLIB::FPROUND_F128_F32, "__trunckfsf2");
135 setLibcallName(RTLIB::FPROUND_F128_F64, "__trunckfdf2");
136 setLibcallName(RTLIB::FPTOSINT_F128_I32, "__fixkfsi");
137 setLibcallName(RTLIB::FPTOSINT_F128_I64, "__fixkfdi");
138 setLibcallName(RTLIB::FPTOUINT_F128_I32, "__fixunskfsi");
139 setLibcallName(RTLIB::FPTOUINT_F128_I64, "__fixunskfdi");
140 setLibcallName(RTLIB::SINTTOFP_I32_F128, "__floatsikf");
141 setLibcallName(RTLIB::SINTTOFP_I64_F128, "__floatdikf");
142 setLibcallName(RTLIB::UINTTOFP_I32_F128, "__floatunsikf");
143 setLibcallName(RTLIB::UINTTOFP_I64_F128, "__floatundikf");
144 setLibcallName(RTLIB::OEQ_F128, "__eqkf2");
145 setLibcallName(RTLIB::UNE_F128, "__nekf2");
146 setLibcallName(RTLIB::OGE_F128, "__gekf2");
147 setLibcallName(RTLIB::OLT_F128, "__ltkf2");
148 setLibcallName(RTLIB::OLE_F128, "__lekf2");
149 setLibcallName(RTLIB::OGT_F128, "__gtkf2");
150 setLibcallName(RTLIB::UO_F128, "__unordkf2");
151 setLibcallName(RTLIB::O_F128, "__unordkf2");
154 // A few names are different on particular architectures or environments.
155 if (TT.isOSDarwin()) {
156 // For f16/f32 conversions, Darwin uses the standard naming scheme, instead
157 // of the gnueabi-style __gnu_*_ieee.
158 // FIXME: What about other targets?
159 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
160 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
162 // Some darwins have an optimized __bzero/bzero function.
163 switch (TT.getArch()) {
164 case Triple::x86:
165 case Triple::x86_64:
166 if (TT.isMacOSX() && !TT.isMacOSXVersionLT(10, 6))
167 setLibcallName(RTLIB::BZERO, "__bzero");
168 break;
169 case Triple::aarch64:
170 setLibcallName(RTLIB::BZERO, "bzero");
171 break;
172 default:
173 break;
176 if (darwinHasSinCos(TT)) {
177 setLibcallName(RTLIB::SINCOS_STRET_F32, "__sincosf_stret");
178 setLibcallName(RTLIB::SINCOS_STRET_F64, "__sincos_stret");
179 if (TT.isWatchABI()) {
180 setLibcallCallingConv(RTLIB::SINCOS_STRET_F32,
181 CallingConv::ARM_AAPCS_VFP);
182 setLibcallCallingConv(RTLIB::SINCOS_STRET_F64,
183 CallingConv::ARM_AAPCS_VFP);
186 } else {
187 setLibcallName(RTLIB::FPEXT_F16_F32, "__gnu_h2f_ieee");
188 setLibcallName(RTLIB::FPROUND_F32_F16, "__gnu_f2h_ieee");
191 if (TT.isGNUEnvironment() || TT.isOSFuchsia() ||
192 (TT.isAndroid() && !TT.isAndroidVersionLT(9))) {
193 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
194 setLibcallName(RTLIB::SINCOS_F64, "sincos");
195 setLibcallName(RTLIB::SINCOS_F80, "sincosl");
196 setLibcallName(RTLIB::SINCOS_F128, "sincosl");
197 setLibcallName(RTLIB::SINCOS_PPCF128, "sincosl");
200 if (TT.isOSOpenBSD()) {
201 setLibcallName(RTLIB::STACKPROTECTOR_CHECK_FAIL, nullptr);
205 /// getFPEXT - Return the FPEXT_*_* value for the given types, or
206 /// UNKNOWN_LIBCALL if there is none.
207 RTLIB::Libcall RTLIB::getFPEXT(EVT OpVT, EVT RetVT) {
208 if (OpVT == MVT::f16) {
209 if (RetVT == MVT::f32)
210 return FPEXT_F16_F32;
211 } else if (OpVT == MVT::f32) {
212 if (RetVT == MVT::f64)
213 return FPEXT_F32_F64;
214 if (RetVT == MVT::f128)
215 return FPEXT_F32_F128;
216 if (RetVT == MVT::ppcf128)
217 return FPEXT_F32_PPCF128;
218 } else if (OpVT == MVT::f64) {
219 if (RetVT == MVT::f128)
220 return FPEXT_F64_F128;
221 else if (RetVT == MVT::ppcf128)
222 return FPEXT_F64_PPCF128;
223 } else if (OpVT == MVT::f80) {
224 if (RetVT == MVT::f128)
225 return FPEXT_F80_F128;
228 return UNKNOWN_LIBCALL;
231 /// getFPROUND - Return the FPROUND_*_* value for the given types, or
232 /// UNKNOWN_LIBCALL if there is none.
233 RTLIB::Libcall RTLIB::getFPROUND(EVT OpVT, EVT RetVT) {
234 if (RetVT == MVT::f16) {
235 if (OpVT == MVT::f32)
236 return FPROUND_F32_F16;
237 if (OpVT == MVT::f64)
238 return FPROUND_F64_F16;
239 if (OpVT == MVT::f80)
240 return FPROUND_F80_F16;
241 if (OpVT == MVT::f128)
242 return FPROUND_F128_F16;
243 if (OpVT == MVT::ppcf128)
244 return FPROUND_PPCF128_F16;
245 } else if (RetVT == MVT::f32) {
246 if (OpVT == MVT::f64)
247 return FPROUND_F64_F32;
248 if (OpVT == MVT::f80)
249 return FPROUND_F80_F32;
250 if (OpVT == MVT::f128)
251 return FPROUND_F128_F32;
252 if (OpVT == MVT::ppcf128)
253 return FPROUND_PPCF128_F32;
254 } else if (RetVT == MVT::f64) {
255 if (OpVT == MVT::f80)
256 return FPROUND_F80_F64;
257 if (OpVT == MVT::f128)
258 return FPROUND_F128_F64;
259 if (OpVT == MVT::ppcf128)
260 return FPROUND_PPCF128_F64;
261 } else if (RetVT == MVT::f80) {
262 if (OpVT == MVT::f128)
263 return FPROUND_F128_F80;
266 return UNKNOWN_LIBCALL;
269 /// getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or
270 /// UNKNOWN_LIBCALL if there is none.
271 RTLIB::Libcall RTLIB::getFPTOSINT(EVT OpVT, EVT RetVT) {
272 if (OpVT == MVT::f32) {
273 if (RetVT == MVT::i32)
274 return FPTOSINT_F32_I32;
275 if (RetVT == MVT::i64)
276 return FPTOSINT_F32_I64;
277 if (RetVT == MVT::i128)
278 return FPTOSINT_F32_I128;
279 } else if (OpVT == MVT::f64) {
280 if (RetVT == MVT::i32)
281 return FPTOSINT_F64_I32;
282 if (RetVT == MVT::i64)
283 return FPTOSINT_F64_I64;
284 if (RetVT == MVT::i128)
285 return FPTOSINT_F64_I128;
286 } else if (OpVT == MVT::f80) {
287 if (RetVT == MVT::i32)
288 return FPTOSINT_F80_I32;
289 if (RetVT == MVT::i64)
290 return FPTOSINT_F80_I64;
291 if (RetVT == MVT::i128)
292 return FPTOSINT_F80_I128;
293 } else if (OpVT == MVT::f128) {
294 if (RetVT == MVT::i32)
295 return FPTOSINT_F128_I32;
296 if (RetVT == MVT::i64)
297 return FPTOSINT_F128_I64;
298 if (RetVT == MVT::i128)
299 return FPTOSINT_F128_I128;
300 } else if (OpVT == MVT::ppcf128) {
301 if (RetVT == MVT::i32)
302 return FPTOSINT_PPCF128_I32;
303 if (RetVT == MVT::i64)
304 return FPTOSINT_PPCF128_I64;
305 if (RetVT == MVT::i128)
306 return FPTOSINT_PPCF128_I128;
308 return UNKNOWN_LIBCALL;
311 /// getFPTOUINT - Return the FPTOUINT_*_* value for the given types, or
312 /// UNKNOWN_LIBCALL if there is none.
313 RTLIB::Libcall RTLIB::getFPTOUINT(EVT OpVT, EVT RetVT) {
314 if (OpVT == MVT::f32) {
315 if (RetVT == MVT::i32)
316 return FPTOUINT_F32_I32;
317 if (RetVT == MVT::i64)
318 return FPTOUINT_F32_I64;
319 if (RetVT == MVT::i128)
320 return FPTOUINT_F32_I128;
321 } else if (OpVT == MVT::f64) {
322 if (RetVT == MVT::i32)
323 return FPTOUINT_F64_I32;
324 if (RetVT == MVT::i64)
325 return FPTOUINT_F64_I64;
326 if (RetVT == MVT::i128)
327 return FPTOUINT_F64_I128;
328 } else if (OpVT == MVT::f80) {
329 if (RetVT == MVT::i32)
330 return FPTOUINT_F80_I32;
331 if (RetVT == MVT::i64)
332 return FPTOUINT_F80_I64;
333 if (RetVT == MVT::i128)
334 return FPTOUINT_F80_I128;
335 } else if (OpVT == MVT::f128) {
336 if (RetVT == MVT::i32)
337 return FPTOUINT_F128_I32;
338 if (RetVT == MVT::i64)
339 return FPTOUINT_F128_I64;
340 if (RetVT == MVT::i128)
341 return FPTOUINT_F128_I128;
342 } else if (OpVT == MVT::ppcf128) {
343 if (RetVT == MVT::i32)
344 return FPTOUINT_PPCF128_I32;
345 if (RetVT == MVT::i64)
346 return FPTOUINT_PPCF128_I64;
347 if (RetVT == MVT::i128)
348 return FPTOUINT_PPCF128_I128;
350 return UNKNOWN_LIBCALL;
353 /// getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or
354 /// UNKNOWN_LIBCALL if there is none.
355 RTLIB::Libcall RTLIB::getSINTTOFP(EVT OpVT, EVT RetVT) {
356 if (OpVT == MVT::i32) {
357 if (RetVT == MVT::f32)
358 return SINTTOFP_I32_F32;
359 if (RetVT == MVT::f64)
360 return SINTTOFP_I32_F64;
361 if (RetVT == MVT::f80)
362 return SINTTOFP_I32_F80;
363 if (RetVT == MVT::f128)
364 return SINTTOFP_I32_F128;
365 if (RetVT == MVT::ppcf128)
366 return SINTTOFP_I32_PPCF128;
367 } else if (OpVT == MVT::i64) {
368 if (RetVT == MVT::f32)
369 return SINTTOFP_I64_F32;
370 if (RetVT == MVT::f64)
371 return SINTTOFP_I64_F64;
372 if (RetVT == MVT::f80)
373 return SINTTOFP_I64_F80;
374 if (RetVT == MVT::f128)
375 return SINTTOFP_I64_F128;
376 if (RetVT == MVT::ppcf128)
377 return SINTTOFP_I64_PPCF128;
378 } else if (OpVT == MVT::i128) {
379 if (RetVT == MVT::f32)
380 return SINTTOFP_I128_F32;
381 if (RetVT == MVT::f64)
382 return SINTTOFP_I128_F64;
383 if (RetVT == MVT::f80)
384 return SINTTOFP_I128_F80;
385 if (RetVT == MVT::f128)
386 return SINTTOFP_I128_F128;
387 if (RetVT == MVT::ppcf128)
388 return SINTTOFP_I128_PPCF128;
390 return UNKNOWN_LIBCALL;
393 /// getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or
394 /// UNKNOWN_LIBCALL if there is none.
395 RTLIB::Libcall RTLIB::getUINTTOFP(EVT OpVT, EVT RetVT) {
396 if (OpVT == MVT::i32) {
397 if (RetVT == MVT::f32)
398 return UINTTOFP_I32_F32;
399 if (RetVT == MVT::f64)
400 return UINTTOFP_I32_F64;
401 if (RetVT == MVT::f80)
402 return UINTTOFP_I32_F80;
403 if (RetVT == MVT::f128)
404 return UINTTOFP_I32_F128;
405 if (RetVT == MVT::ppcf128)
406 return UINTTOFP_I32_PPCF128;
407 } else if (OpVT == MVT::i64) {
408 if (RetVT == MVT::f32)
409 return UINTTOFP_I64_F32;
410 if (RetVT == MVT::f64)
411 return UINTTOFP_I64_F64;
412 if (RetVT == MVT::f80)
413 return UINTTOFP_I64_F80;
414 if (RetVT == MVT::f128)
415 return UINTTOFP_I64_F128;
416 if (RetVT == MVT::ppcf128)
417 return UINTTOFP_I64_PPCF128;
418 } else if (OpVT == MVT::i128) {
419 if (RetVT == MVT::f32)
420 return UINTTOFP_I128_F32;
421 if (RetVT == MVT::f64)
422 return UINTTOFP_I128_F64;
423 if (RetVT == MVT::f80)
424 return UINTTOFP_I128_F80;
425 if (RetVT == MVT::f128)
426 return UINTTOFP_I128_F128;
427 if (RetVT == MVT::ppcf128)
428 return UINTTOFP_I128_PPCF128;
430 return UNKNOWN_LIBCALL;
433 RTLIB::Libcall RTLIB::getSYNC(unsigned Opc, MVT VT) {
434 #define OP_TO_LIBCALL(Name, Enum) \
435 case Name: \
436 switch (VT.SimpleTy) { \
437 default: \
438 return UNKNOWN_LIBCALL; \
439 case MVT::i8: \
440 return Enum##_1; \
441 case MVT::i16: \
442 return Enum##_2; \
443 case MVT::i32: \
444 return Enum##_4; \
445 case MVT::i64: \
446 return Enum##_8; \
447 case MVT::i128: \
448 return Enum##_16; \
451 switch (Opc) {
452 OP_TO_LIBCALL(ISD::ATOMIC_SWAP, SYNC_LOCK_TEST_AND_SET)
453 OP_TO_LIBCALL(ISD::ATOMIC_CMP_SWAP, SYNC_VAL_COMPARE_AND_SWAP)
454 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_ADD, SYNC_FETCH_AND_ADD)
455 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_SUB, SYNC_FETCH_AND_SUB)
456 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_AND, SYNC_FETCH_AND_AND)
457 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_OR, SYNC_FETCH_AND_OR)
458 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_XOR, SYNC_FETCH_AND_XOR)
459 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_NAND, SYNC_FETCH_AND_NAND)
460 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_MAX, SYNC_FETCH_AND_MAX)
461 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_UMAX, SYNC_FETCH_AND_UMAX)
462 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_MIN, SYNC_FETCH_AND_MIN)
463 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_UMIN, SYNC_FETCH_AND_UMIN)
466 #undef OP_TO_LIBCALL
468 return UNKNOWN_LIBCALL;
471 RTLIB::Libcall RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) {
472 switch (ElementSize) {
473 case 1:
474 return MEMCPY_ELEMENT_UNORDERED_ATOMIC_1;
475 case 2:
476 return MEMCPY_ELEMENT_UNORDERED_ATOMIC_2;
477 case 4:
478 return MEMCPY_ELEMENT_UNORDERED_ATOMIC_4;
479 case 8:
480 return MEMCPY_ELEMENT_UNORDERED_ATOMIC_8;
481 case 16:
482 return MEMCPY_ELEMENT_UNORDERED_ATOMIC_16;
483 default:
484 return UNKNOWN_LIBCALL;
488 RTLIB::Libcall RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) {
489 switch (ElementSize) {
490 case 1:
491 return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_1;
492 case 2:
493 return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_2;
494 case 4:
495 return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_4;
496 case 8:
497 return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_8;
498 case 16:
499 return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_16;
500 default:
501 return UNKNOWN_LIBCALL;
505 RTLIB::Libcall RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) {
506 switch (ElementSize) {
507 case 1:
508 return MEMSET_ELEMENT_UNORDERED_ATOMIC_1;
509 case 2:
510 return MEMSET_ELEMENT_UNORDERED_ATOMIC_2;
511 case 4:
512 return MEMSET_ELEMENT_UNORDERED_ATOMIC_4;
513 case 8:
514 return MEMSET_ELEMENT_UNORDERED_ATOMIC_8;
515 case 16:
516 return MEMSET_ELEMENT_UNORDERED_ATOMIC_16;
517 default:
518 return UNKNOWN_LIBCALL;
522 /// InitCmpLibcallCCs - Set default comparison libcall CC.
523 static void InitCmpLibcallCCs(ISD::CondCode *CCs) {
524 memset(CCs, ISD::SETCC_INVALID, sizeof(ISD::CondCode)*RTLIB::UNKNOWN_LIBCALL);
525 CCs[RTLIB::OEQ_F32] = ISD::SETEQ;
526 CCs[RTLIB::OEQ_F64] = ISD::SETEQ;
527 CCs[RTLIB::OEQ_F128] = ISD::SETEQ;
528 CCs[RTLIB::OEQ_PPCF128] = ISD::SETEQ;
529 CCs[RTLIB::UNE_F32] = ISD::SETNE;
530 CCs[RTLIB::UNE_F64] = ISD::SETNE;
531 CCs[RTLIB::UNE_F128] = ISD::SETNE;
532 CCs[RTLIB::UNE_PPCF128] = ISD::SETNE;
533 CCs[RTLIB::OGE_F32] = ISD::SETGE;
534 CCs[RTLIB::OGE_F64] = ISD::SETGE;
535 CCs[RTLIB::OGE_F128] = ISD::SETGE;
536 CCs[RTLIB::OGE_PPCF128] = ISD::SETGE;
537 CCs[RTLIB::OLT_F32] = ISD::SETLT;
538 CCs[RTLIB::OLT_F64] = ISD::SETLT;
539 CCs[RTLIB::OLT_F128] = ISD::SETLT;
540 CCs[RTLIB::OLT_PPCF128] = ISD::SETLT;
541 CCs[RTLIB::OLE_F32] = ISD::SETLE;
542 CCs[RTLIB::OLE_F64] = ISD::SETLE;
543 CCs[RTLIB::OLE_F128] = ISD::SETLE;
544 CCs[RTLIB::OLE_PPCF128] = ISD::SETLE;
545 CCs[RTLIB::OGT_F32] = ISD::SETGT;
546 CCs[RTLIB::OGT_F64] = ISD::SETGT;
547 CCs[RTLIB::OGT_F128] = ISD::SETGT;
548 CCs[RTLIB::OGT_PPCF128] = ISD::SETGT;
549 CCs[RTLIB::UO_F32] = ISD::SETNE;
550 CCs[RTLIB::UO_F64] = ISD::SETNE;
551 CCs[RTLIB::UO_F128] = ISD::SETNE;
552 CCs[RTLIB::UO_PPCF128] = ISD::SETNE;
553 CCs[RTLIB::O_F32] = ISD::SETEQ;
554 CCs[RTLIB::O_F64] = ISD::SETEQ;
555 CCs[RTLIB::O_F128] = ISD::SETEQ;
556 CCs[RTLIB::O_PPCF128] = ISD::SETEQ;
559 /// NOTE: The TargetMachine owns TLOF.
560 TargetLoweringBase::TargetLoweringBase(const TargetMachine &tm) : TM(tm) {
561 initActions();
563 // Perform these initializations only once.
564 MaxStoresPerMemset = MaxStoresPerMemcpy = MaxStoresPerMemmove =
565 MaxLoadsPerMemcmp = 8;
566 MaxGluedStoresPerMemcpy = 0;
567 MaxStoresPerMemsetOptSize = MaxStoresPerMemcpyOptSize =
568 MaxStoresPerMemmoveOptSize = MaxLoadsPerMemcmpOptSize = 4;
569 UseUnderscoreSetJmp = false;
570 UseUnderscoreLongJmp = false;
571 HasMultipleConditionRegisters = false;
572 HasExtractBitsInsn = false;
573 JumpIsExpensive = JumpIsExpensiveOverride;
574 PredictableSelectIsExpensive = false;
575 EnableExtLdPromotion = false;
576 StackPointerRegisterToSaveRestore = 0;
577 BooleanContents = UndefinedBooleanContent;
578 BooleanFloatContents = UndefinedBooleanContent;
579 BooleanVectorContents = UndefinedBooleanContent;
580 SchedPreferenceInfo = Sched::ILP;
581 MinFunctionAlignment = 0;
582 PrefFunctionAlignment = 0;
583 PrefLoopAlignment = 0;
584 GatherAllAliasesMaxDepth = 18;
585 MinStackArgumentAlignment = 1;
586 // TODO: the default will be switched to 0 in the next commit, along
587 // with the Target-specific changes necessary.
588 MaxAtomicSizeInBitsSupported = 1024;
590 MinCmpXchgSizeInBits = 0;
591 SupportsUnalignedAtomics = false;
593 std::fill(std::begin(LibcallRoutineNames), std::end(LibcallRoutineNames), nullptr);
595 InitLibcalls(TM.getTargetTriple());
596 InitCmpLibcallCCs(CmpLibcallCCs);
599 void TargetLoweringBase::initActions() {
600 // All operations default to being supported.
601 memset(OpActions, 0, sizeof(OpActions));
602 memset(LoadExtActions, 0, sizeof(LoadExtActions));
603 memset(TruncStoreActions, 0, sizeof(TruncStoreActions));
604 memset(IndexedModeActions, 0, sizeof(IndexedModeActions));
605 memset(CondCodeActions, 0, sizeof(CondCodeActions));
606 std::fill(std::begin(RegClassForVT), std::end(RegClassForVT), nullptr);
607 std::fill(std::begin(TargetDAGCombineArray),
608 std::end(TargetDAGCombineArray), 0);
610 for (MVT VT : MVT::fp_valuetypes()) {
611 MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
612 if (IntVT.isValid()) {
613 setOperationAction(ISD::ATOMIC_SWAP, VT, Promote);
614 AddPromotedToType(ISD::ATOMIC_SWAP, VT, IntVT);
618 // Set default actions for various operations.
619 for (MVT VT : MVT::all_valuetypes()) {
620 // Default all indexed load / store to expand.
621 for (unsigned IM = (unsigned)ISD::PRE_INC;
622 IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) {
623 setIndexedLoadAction(IM, VT, Expand);
624 setIndexedStoreAction(IM, VT, Expand);
627 // Most backends expect to see the node which just returns the value loaded.
628 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Expand);
630 // These operations default to expand.
631 setOperationAction(ISD::FGETSIGN, VT, Expand);
632 setOperationAction(ISD::CONCAT_VECTORS, VT, Expand);
633 setOperationAction(ISD::FMINNUM, VT, Expand);
634 setOperationAction(ISD::FMAXNUM, VT, Expand);
635 setOperationAction(ISD::FMINNUM_IEEE, VT, Expand);
636 setOperationAction(ISD::FMAXNUM_IEEE, VT, Expand);
637 setOperationAction(ISD::FMINIMUM, VT, Expand);
638 setOperationAction(ISD::FMAXIMUM, VT, Expand);
639 setOperationAction(ISD::FMAD, VT, Expand);
640 setOperationAction(ISD::SMIN, VT, Expand);
641 setOperationAction(ISD::SMAX, VT, Expand);
642 setOperationAction(ISD::UMIN, VT, Expand);
643 setOperationAction(ISD::UMAX, VT, Expand);
644 setOperationAction(ISD::ABS, VT, Expand);
645 setOperationAction(ISD::FSHL, VT, Expand);
646 setOperationAction(ISD::FSHR, VT, Expand);
647 setOperationAction(ISD::SADDSAT, VT, Expand);
648 setOperationAction(ISD::UADDSAT, VT, Expand);
649 setOperationAction(ISD::SSUBSAT, VT, Expand);
650 setOperationAction(ISD::USUBSAT, VT, Expand);
651 setOperationAction(ISD::SMULFIX, VT, Expand);
652 setOperationAction(ISD::SMULFIXSAT, VT, Expand);
653 setOperationAction(ISD::UMULFIX, VT, Expand);
655 // Overflow operations default to expand
656 setOperationAction(ISD::SADDO, VT, Expand);
657 setOperationAction(ISD::SSUBO, VT, Expand);
658 setOperationAction(ISD::UADDO, VT, Expand);
659 setOperationAction(ISD::USUBO, VT, Expand);
660 setOperationAction(ISD::SMULO, VT, Expand);
661 setOperationAction(ISD::UMULO, VT, Expand);
663 // ADDCARRY operations default to expand
664 setOperationAction(ISD::ADDCARRY, VT, Expand);
665 setOperationAction(ISD::SUBCARRY, VT, Expand);
666 setOperationAction(ISD::SETCCCARRY, VT, Expand);
668 // ADDC/ADDE/SUBC/SUBE default to expand.
669 setOperationAction(ISD::ADDC, VT, Expand);
670 setOperationAction(ISD::ADDE, VT, Expand);
671 setOperationAction(ISD::SUBC, VT, Expand);
672 setOperationAction(ISD::SUBE, VT, Expand);
674 // These default to Expand so they will be expanded to CTLZ/CTTZ by default.
675 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
676 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
678 setOperationAction(ISD::BITREVERSE, VT, Expand);
680 // These library functions default to expand.
681 setOperationAction(ISD::FROUND, VT, Expand);
682 setOperationAction(ISD::FPOWI, VT, Expand);
684 // These operations default to expand for vector types.
685 if (VT.isVector()) {
686 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
687 setOperationAction(ISD::ANY_EXTEND_VECTOR_INREG, VT, Expand);
688 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Expand);
689 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Expand);
692 // Constrained floating-point operations default to expand.
693 setOperationAction(ISD::STRICT_FADD, VT, Expand);
694 setOperationAction(ISD::STRICT_FSUB, VT, Expand);
695 setOperationAction(ISD::STRICT_FMUL, VT, Expand);
696 setOperationAction(ISD::STRICT_FDIV, VT, Expand);
697 setOperationAction(ISD::STRICT_FREM, VT, Expand);
698 setOperationAction(ISD::STRICT_FMA, VT, Expand);
699 setOperationAction(ISD::STRICT_FSQRT, VT, Expand);
700 setOperationAction(ISD::STRICT_FPOW, VT, Expand);
701 setOperationAction(ISD::STRICT_FPOWI, VT, Expand);
702 setOperationAction(ISD::STRICT_FSIN, VT, Expand);
703 setOperationAction(ISD::STRICT_FCOS, VT, Expand);
704 setOperationAction(ISD::STRICT_FEXP, VT, Expand);
705 setOperationAction(ISD::STRICT_FEXP2, VT, Expand);
706 setOperationAction(ISD::STRICT_FLOG, VT, Expand);
707 setOperationAction(ISD::STRICT_FLOG10, VT, Expand);
708 setOperationAction(ISD::STRICT_FLOG2, VT, Expand);
709 setOperationAction(ISD::STRICT_FRINT, VT, Expand);
710 setOperationAction(ISD::STRICT_FNEARBYINT, VT, Expand);
711 setOperationAction(ISD::STRICT_FCEIL, VT, Expand);
712 setOperationAction(ISD::STRICT_FFLOOR, VT, Expand);
713 setOperationAction(ISD::STRICT_FROUND, VT, Expand);
714 setOperationAction(ISD::STRICT_FTRUNC, VT, Expand);
715 setOperationAction(ISD::STRICT_FMAXNUM, VT, Expand);
716 setOperationAction(ISD::STRICT_FMINNUM, VT, Expand);
717 setOperationAction(ISD::STRICT_FP_ROUND, VT, Expand);
718 setOperationAction(ISD::STRICT_FP_EXTEND, VT, Expand);
720 // For most targets @llvm.get.dynamic.area.offset just returns 0.
721 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, VT, Expand);
723 // Vector reduction default to expand.
724 setOperationAction(ISD::VECREDUCE_FADD, VT, Expand);
725 setOperationAction(ISD::VECREDUCE_FMUL, VT, Expand);
726 setOperationAction(ISD::VECREDUCE_ADD, VT, Expand);
727 setOperationAction(ISD::VECREDUCE_MUL, VT, Expand);
728 setOperationAction(ISD::VECREDUCE_AND, VT, Expand);
729 setOperationAction(ISD::VECREDUCE_OR, VT, Expand);
730 setOperationAction(ISD::VECREDUCE_XOR, VT, Expand);
731 setOperationAction(ISD::VECREDUCE_SMAX, VT, Expand);
732 setOperationAction(ISD::VECREDUCE_SMIN, VT, Expand);
733 setOperationAction(ISD::VECREDUCE_UMAX, VT, Expand);
734 setOperationAction(ISD::VECREDUCE_UMIN, VT, Expand);
735 setOperationAction(ISD::VECREDUCE_FMAX, VT, Expand);
736 setOperationAction(ISD::VECREDUCE_FMIN, VT, Expand);
739 // Most targets ignore the @llvm.prefetch intrinsic.
740 setOperationAction(ISD::PREFETCH, MVT::Other, Expand);
742 // Most targets also ignore the @llvm.readcyclecounter intrinsic.
743 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Expand);
745 // ConstantFP nodes default to expand. Targets can either change this to
746 // Legal, in which case all fp constants are legal, or use isFPImmLegal()
747 // to optimize expansions for certain constants.
748 setOperationAction(ISD::ConstantFP, MVT::f16, Expand);
749 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
750 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
751 setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
752 setOperationAction(ISD::ConstantFP, MVT::f128, Expand);
754 // These library functions default to expand.
755 for (MVT VT : {MVT::f32, MVT::f64, MVT::f128}) {
756 setOperationAction(ISD::FCBRT, VT, Expand);
757 setOperationAction(ISD::FLOG , VT, Expand);
758 setOperationAction(ISD::FLOG2, VT, Expand);
759 setOperationAction(ISD::FLOG10, VT, Expand);
760 setOperationAction(ISD::FEXP , VT, Expand);
761 setOperationAction(ISD::FEXP2, VT, Expand);
762 setOperationAction(ISD::FFLOOR, VT, Expand);
763 setOperationAction(ISD::FNEARBYINT, VT, Expand);
764 setOperationAction(ISD::FCEIL, VT, Expand);
765 setOperationAction(ISD::FRINT, VT, Expand);
766 setOperationAction(ISD::FTRUNC, VT, Expand);
767 setOperationAction(ISD::FROUND, VT, Expand);
768 setOperationAction(ISD::LROUND, VT, Expand);
769 setOperationAction(ISD::LLROUND, VT, Expand);
770 setOperationAction(ISD::LRINT, VT, Expand);
771 setOperationAction(ISD::LLRINT, VT, Expand);
774 // Default ISD::TRAP to expand (which turns it into abort).
775 setOperationAction(ISD::TRAP, MVT::Other, Expand);
777 // On most systems, DEBUGTRAP and TRAP have no difference. The "Expand"
778 // here is to inform DAG Legalizer to replace DEBUGTRAP with TRAP.
779 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Expand);
782 MVT TargetLoweringBase::getScalarShiftAmountTy(const DataLayout &DL,
783 EVT) const {
784 return MVT::getIntegerVT(DL.getPointerSizeInBits(0));
787 EVT TargetLoweringBase::getShiftAmountTy(EVT LHSTy, const DataLayout &DL,
788 bool LegalTypes) const {
789 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
790 if (LHSTy.isVector())
791 return LHSTy;
792 return LegalTypes ? getScalarShiftAmountTy(DL, LHSTy)
793 : getPointerTy(DL);
796 bool TargetLoweringBase::canOpTrap(unsigned Op, EVT VT) const {
797 assert(isTypeLegal(VT));
798 switch (Op) {
799 default:
800 return false;
801 case ISD::SDIV:
802 case ISD::UDIV:
803 case ISD::SREM:
804 case ISD::UREM:
805 return true;
809 void TargetLoweringBase::setJumpIsExpensive(bool isExpensive) {
810 // If the command-line option was specified, ignore this request.
811 if (!JumpIsExpensiveOverride.getNumOccurrences())
812 JumpIsExpensive = isExpensive;
815 TargetLoweringBase::LegalizeKind
816 TargetLoweringBase::getTypeConversion(LLVMContext &Context, EVT VT) const {
817 // If this is a simple type, use the ComputeRegisterProp mechanism.
818 if (VT.isSimple()) {
819 MVT SVT = VT.getSimpleVT();
820 assert((unsigned)SVT.SimpleTy < array_lengthof(TransformToType));
821 MVT NVT = TransformToType[SVT.SimpleTy];
822 LegalizeTypeAction LA = ValueTypeActions.getTypeAction(SVT);
824 assert((LA == TypeLegal || LA == TypeSoftenFloat ||
825 (NVT.isVector() ||
826 ValueTypeActions.getTypeAction(NVT) != TypePromoteInteger)) &&
827 "Promote may not follow Expand or Promote");
829 if (LA == TypeSplitVector)
830 return LegalizeKind(LA,
831 EVT::getVectorVT(Context, SVT.getVectorElementType(),
832 SVT.getVectorNumElements() / 2));
833 if (LA == TypeScalarizeVector)
834 return LegalizeKind(LA, SVT.getVectorElementType());
835 return LegalizeKind(LA, NVT);
838 // Handle Extended Scalar Types.
839 if (!VT.isVector()) {
840 assert(VT.isInteger() && "Float types must be simple");
841 unsigned BitSize = VT.getSizeInBits();
842 // First promote to a power-of-two size, then expand if necessary.
843 if (BitSize < 8 || !isPowerOf2_32(BitSize)) {
844 EVT NVT = VT.getRoundIntegerType(Context);
845 assert(NVT != VT && "Unable to round integer VT");
846 LegalizeKind NextStep = getTypeConversion(Context, NVT);
847 // Avoid multi-step promotion.
848 if (NextStep.first == TypePromoteInteger)
849 return NextStep;
850 // Return rounded integer type.
851 return LegalizeKind(TypePromoteInteger, NVT);
854 return LegalizeKind(TypeExpandInteger,
855 EVT::getIntegerVT(Context, VT.getSizeInBits() / 2));
858 // Handle vector types.
859 unsigned NumElts = VT.getVectorNumElements();
860 EVT EltVT = VT.getVectorElementType();
862 // Vectors with only one element are always scalarized.
863 if (NumElts == 1)
864 return LegalizeKind(TypeScalarizeVector, EltVT);
866 // Try to widen vector elements until the element type is a power of two and
867 // promote it to a legal type later on, for example:
868 // <3 x i8> -> <4 x i8> -> <4 x i32>
869 if (EltVT.isInteger()) {
870 // Vectors with a number of elements that is not a power of two are always
871 // widened, for example <3 x i8> -> <4 x i8>.
872 if (!VT.isPow2VectorType()) {
873 NumElts = (unsigned)NextPowerOf2(NumElts);
874 EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts);
875 return LegalizeKind(TypeWidenVector, NVT);
878 // Examine the element type.
879 LegalizeKind LK = getTypeConversion(Context, EltVT);
881 // If type is to be expanded, split the vector.
882 // <4 x i140> -> <2 x i140>
883 if (LK.first == TypeExpandInteger)
884 return LegalizeKind(TypeSplitVector,
885 EVT::getVectorVT(Context, EltVT, NumElts / 2));
887 // Promote the integer element types until a legal vector type is found
888 // or until the element integer type is too big. If a legal type was not
889 // found, fallback to the usual mechanism of widening/splitting the
890 // vector.
891 EVT OldEltVT = EltVT;
892 while (true) {
893 // Increase the bitwidth of the element to the next pow-of-two
894 // (which is greater than 8 bits).
895 EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits())
896 .getRoundIntegerType(Context);
898 // Stop trying when getting a non-simple element type.
899 // Note that vector elements may be greater than legal vector element
900 // types. Example: X86 XMM registers hold 64bit element on 32bit
901 // systems.
902 if (!EltVT.isSimple())
903 break;
905 // Build a new vector type and check if it is legal.
906 MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
907 // Found a legal promoted vector type.
908 if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal)
909 return LegalizeKind(TypePromoteInteger,
910 EVT::getVectorVT(Context, EltVT, NumElts));
913 // Reset the type to the unexpanded type if we did not find a legal vector
914 // type with a promoted vector element type.
915 EltVT = OldEltVT;
918 // Try to widen the vector until a legal type is found.
919 // If there is no wider legal type, split the vector.
920 while (true) {
921 // Round up to the next power of 2.
922 NumElts = (unsigned)NextPowerOf2(NumElts);
924 // If there is no simple vector type with this many elements then there
925 // cannot be a larger legal vector type. Note that this assumes that
926 // there are no skipped intermediate vector types in the simple types.
927 if (!EltVT.isSimple())
928 break;
929 MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
930 if (LargerVector == MVT())
931 break;
933 // If this type is legal then widen the vector.
934 if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal)
935 return LegalizeKind(TypeWidenVector, LargerVector);
938 // Widen odd vectors to next power of two.
939 if (!VT.isPow2VectorType()) {
940 EVT NVT = VT.getPow2VectorType(Context);
941 return LegalizeKind(TypeWidenVector, NVT);
944 // Vectors with illegal element types are expanded.
945 EVT NVT = EVT::getVectorVT(Context, EltVT, VT.getVectorNumElements() / 2);
946 return LegalizeKind(TypeSplitVector, NVT);
949 static unsigned getVectorTypeBreakdownMVT(MVT VT, MVT &IntermediateVT,
950 unsigned &NumIntermediates,
951 MVT &RegisterVT,
952 TargetLoweringBase *TLI) {
953 // Figure out the right, legal destination reg to copy into.
954 unsigned NumElts = VT.getVectorNumElements();
955 MVT EltTy = VT.getVectorElementType();
957 unsigned NumVectorRegs = 1;
959 // FIXME: We don't support non-power-of-2-sized vectors for now. Ideally we
960 // could break down into LHS/RHS like LegalizeDAG does.
961 if (!isPowerOf2_32(NumElts)) {
962 NumVectorRegs = NumElts;
963 NumElts = 1;
966 // Divide the input until we get to a supported size. This will always
967 // end with a scalar if the target doesn't support vectors.
968 while (NumElts > 1 && !TLI->isTypeLegal(MVT::getVectorVT(EltTy, NumElts))) {
969 NumElts >>= 1;
970 NumVectorRegs <<= 1;
973 NumIntermediates = NumVectorRegs;
975 MVT NewVT = MVT::getVectorVT(EltTy, NumElts);
976 if (!TLI->isTypeLegal(NewVT))
977 NewVT = EltTy;
978 IntermediateVT = NewVT;
980 unsigned NewVTSize = NewVT.getSizeInBits();
982 // Convert sizes such as i33 to i64.
983 if (!isPowerOf2_32(NewVTSize))
984 NewVTSize = NextPowerOf2(NewVTSize);
986 MVT DestVT = TLI->getRegisterType(NewVT);
987 RegisterVT = DestVT;
988 if (EVT(DestVT).bitsLT(NewVT)) // Value is expanded, e.g. i64 -> i16.
989 return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits());
991 // Otherwise, promotion or legal types use the same number of registers as
992 // the vector decimated to the appropriate level.
993 return NumVectorRegs;
996 /// isLegalRC - Return true if the value types that can be represented by the
997 /// specified register class are all legal.
998 bool TargetLoweringBase::isLegalRC(const TargetRegisterInfo &TRI,
999 const TargetRegisterClass &RC) const {
1000 for (auto I = TRI.legalclasstypes_begin(RC); *I != MVT::Other; ++I)
1001 if (isTypeLegal(*I))
1002 return true;
1003 return false;
1006 /// Replace/modify any TargetFrameIndex operands with a targte-dependent
1007 /// sequence of memory operands that is recognized by PrologEpilogInserter.
1008 MachineBasicBlock *
1009 TargetLoweringBase::emitPatchPoint(MachineInstr &InitialMI,
1010 MachineBasicBlock *MBB) const {
1011 MachineInstr *MI = &InitialMI;
1012 MachineFunction &MF = *MI->getMF();
1013 MachineFrameInfo &MFI = MF.getFrameInfo();
1015 // We're handling multiple types of operands here:
1016 // PATCHPOINT MetaArgs - live-in, read only, direct
1017 // STATEPOINT Deopt Spill - live-through, read only, indirect
1018 // STATEPOINT Deopt Alloca - live-through, read only, direct
1019 // (We're currently conservative and mark the deopt slots read/write in
1020 // practice.)
1021 // STATEPOINT GC Spill - live-through, read/write, indirect
1022 // STATEPOINT GC Alloca - live-through, read/write, direct
1023 // The live-in vs live-through is handled already (the live through ones are
1024 // all stack slots), but we need to handle the different type of stackmap
1025 // operands and memory effects here.
1027 // MI changes inside this loop as we grow operands.
1028 for(unsigned OperIdx = 0; OperIdx != MI->getNumOperands(); ++OperIdx) {
1029 MachineOperand &MO = MI->getOperand(OperIdx);
1030 if (!MO.isFI())
1031 continue;
1033 // foldMemoryOperand builds a new MI after replacing a single FI operand
1034 // with the canonical set of five x86 addressing-mode operands.
1035 int FI = MO.getIndex();
1036 MachineInstrBuilder MIB = BuildMI(MF, MI->getDebugLoc(), MI->getDesc());
1038 // Copy operands before the frame-index.
1039 for (unsigned i = 0; i < OperIdx; ++i)
1040 MIB.add(MI->getOperand(i));
1041 // Add frame index operands recognized by stackmaps.cpp
1042 if (MFI.isStatepointSpillSlotObjectIndex(FI)) {
1043 // indirect-mem-ref tag, size, #FI, offset.
1044 // Used for spills inserted by StatepointLowering. This codepath is not
1045 // used for patchpoints/stackmaps at all, for these spilling is done via
1046 // foldMemoryOperand callback only.
1047 assert(MI->getOpcode() == TargetOpcode::STATEPOINT && "sanity");
1048 MIB.addImm(StackMaps::IndirectMemRefOp);
1049 MIB.addImm(MFI.getObjectSize(FI));
1050 MIB.add(MI->getOperand(OperIdx));
1051 MIB.addImm(0);
1052 } else {
1053 // direct-mem-ref tag, #FI, offset.
1054 // Used by patchpoint, and direct alloca arguments to statepoints
1055 MIB.addImm(StackMaps::DirectMemRefOp);
1056 MIB.add(MI->getOperand(OperIdx));
1057 MIB.addImm(0);
1059 // Copy the operands after the frame index.
1060 for (unsigned i = OperIdx + 1; i != MI->getNumOperands(); ++i)
1061 MIB.add(MI->getOperand(i));
1063 // Inherit previous memory operands.
1064 MIB.cloneMemRefs(*MI);
1065 assert(MIB->mayLoad() && "Folded a stackmap use to a non-load!");
1067 // Add a new memory operand for this FI.
1068 assert(MFI.getObjectOffset(FI) != -1);
1070 // Note: STATEPOINT MMOs are added during SelectionDAG. STACKMAP, and
1071 // PATCHPOINT should be updated to do the same. (TODO)
1072 if (MI->getOpcode() != TargetOpcode::STATEPOINT) {
1073 auto Flags = MachineMemOperand::MOLoad;
1074 MachineMemOperand *MMO = MF.getMachineMemOperand(
1075 MachinePointerInfo::getFixedStack(MF, FI), Flags,
1076 MF.getDataLayout().getPointerSize(), MFI.getObjectAlignment(FI));
1077 MIB->addMemOperand(MF, MMO);
1080 // Replace the instruction and update the operand index.
1081 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
1082 OperIdx += (MIB->getNumOperands() - MI->getNumOperands()) - 1;
1083 MI->eraseFromParent();
1084 MI = MIB;
1086 return MBB;
1089 MachineBasicBlock *
1090 TargetLoweringBase::emitXRayCustomEvent(MachineInstr &MI,
1091 MachineBasicBlock *MBB) const {
1092 assert(MI.getOpcode() == TargetOpcode::PATCHABLE_EVENT_CALL &&
1093 "Called emitXRayCustomEvent on the wrong MI!");
1094 auto &MF = *MI.getMF();
1095 auto MIB = BuildMI(MF, MI.getDebugLoc(), MI.getDesc());
1096 for (unsigned OpIdx = 0; OpIdx != MI.getNumOperands(); ++OpIdx)
1097 MIB.add(MI.getOperand(OpIdx));
1099 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
1100 MI.eraseFromParent();
1101 return MBB;
1104 MachineBasicBlock *
1105 TargetLoweringBase::emitXRayTypedEvent(MachineInstr &MI,
1106 MachineBasicBlock *MBB) const {
1107 assert(MI.getOpcode() == TargetOpcode::PATCHABLE_TYPED_EVENT_CALL &&
1108 "Called emitXRayTypedEvent on the wrong MI!");
1109 auto &MF = *MI.getMF();
1110 auto MIB = BuildMI(MF, MI.getDebugLoc(), MI.getDesc());
1111 for (unsigned OpIdx = 0; OpIdx != MI.getNumOperands(); ++OpIdx)
1112 MIB.add(MI.getOperand(OpIdx));
1114 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
1115 MI.eraseFromParent();
1116 return MBB;
1119 /// findRepresentativeClass - Return the largest legal super-reg register class
1120 /// of the register class for the specified type and its associated "cost".
1121 // This function is in TargetLowering because it uses RegClassForVT which would
1122 // need to be moved to TargetRegisterInfo and would necessitate moving
1123 // isTypeLegal over as well - a massive change that would just require
1124 // TargetLowering having a TargetRegisterInfo class member that it would use.
1125 std::pair<const TargetRegisterClass *, uint8_t>
1126 TargetLoweringBase::findRepresentativeClass(const TargetRegisterInfo *TRI,
1127 MVT VT) const {
1128 const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
1129 if (!RC)
1130 return std::make_pair(RC, 0);
1132 // Compute the set of all super-register classes.
1133 BitVector SuperRegRC(TRI->getNumRegClasses());
1134 for (SuperRegClassIterator RCI(RC, TRI); RCI.isValid(); ++RCI)
1135 SuperRegRC.setBitsInMask(RCI.getMask());
1137 // Find the first legal register class with the largest spill size.
1138 const TargetRegisterClass *BestRC = RC;
1139 for (unsigned i : SuperRegRC.set_bits()) {
1140 const TargetRegisterClass *SuperRC = TRI->getRegClass(i);
1141 // We want the largest possible spill size.
1142 if (TRI->getSpillSize(*SuperRC) <= TRI->getSpillSize(*BestRC))
1143 continue;
1144 if (!isLegalRC(*TRI, *SuperRC))
1145 continue;
1146 BestRC = SuperRC;
1148 return std::make_pair(BestRC, 1);
1151 /// computeRegisterProperties - Once all of the register classes are added,
1152 /// this allows us to compute derived properties we expose.
1153 void TargetLoweringBase::computeRegisterProperties(
1154 const TargetRegisterInfo *TRI) {
1155 static_assert(MVT::LAST_VALUETYPE <= MVT::MAX_ALLOWED_VALUETYPE,
1156 "Too many value types for ValueTypeActions to hold!");
1158 // Everything defaults to needing one register.
1159 for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
1160 NumRegistersForVT[i] = 1;
1161 RegisterTypeForVT[i] = TransformToType[i] = (MVT::SimpleValueType)i;
1163 // ...except isVoid, which doesn't need any registers.
1164 NumRegistersForVT[MVT::isVoid] = 0;
1166 // Find the largest integer register class.
1167 unsigned LargestIntReg = MVT::LAST_INTEGER_VALUETYPE;
1168 for (; RegClassForVT[LargestIntReg] == nullptr; --LargestIntReg)
1169 assert(LargestIntReg != MVT::i1 && "No integer registers defined!");
1171 // Every integer value type larger than this largest register takes twice as
1172 // many registers to represent as the previous ValueType.
1173 for (unsigned ExpandedReg = LargestIntReg + 1;
1174 ExpandedReg <= MVT::LAST_INTEGER_VALUETYPE; ++ExpandedReg) {
1175 NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1];
1176 RegisterTypeForVT[ExpandedReg] = (MVT::SimpleValueType)LargestIntReg;
1177 TransformToType[ExpandedReg] = (MVT::SimpleValueType)(ExpandedReg - 1);
1178 ValueTypeActions.setTypeAction((MVT::SimpleValueType)ExpandedReg,
1179 TypeExpandInteger);
1182 // Inspect all of the ValueType's smaller than the largest integer
1183 // register to see which ones need promotion.
1184 unsigned LegalIntReg = LargestIntReg;
1185 for (unsigned IntReg = LargestIntReg - 1;
1186 IntReg >= (unsigned)MVT::i1; --IntReg) {
1187 MVT IVT = (MVT::SimpleValueType)IntReg;
1188 if (isTypeLegal(IVT)) {
1189 LegalIntReg = IntReg;
1190 } else {
1191 RegisterTypeForVT[IntReg] = TransformToType[IntReg] =
1192 (MVT::SimpleValueType)LegalIntReg;
1193 ValueTypeActions.setTypeAction(IVT, TypePromoteInteger);
1197 // ppcf128 type is really two f64's.
1198 if (!isTypeLegal(MVT::ppcf128)) {
1199 if (isTypeLegal(MVT::f64)) {
1200 NumRegistersForVT[MVT::ppcf128] = 2*NumRegistersForVT[MVT::f64];
1201 RegisterTypeForVT[MVT::ppcf128] = MVT::f64;
1202 TransformToType[MVT::ppcf128] = MVT::f64;
1203 ValueTypeActions.setTypeAction(MVT::ppcf128, TypeExpandFloat);
1204 } else {
1205 NumRegistersForVT[MVT::ppcf128] = NumRegistersForVT[MVT::i128];
1206 RegisterTypeForVT[MVT::ppcf128] = RegisterTypeForVT[MVT::i128];
1207 TransformToType[MVT::ppcf128] = MVT::i128;
1208 ValueTypeActions.setTypeAction(MVT::ppcf128, TypeSoftenFloat);
1212 // Decide how to handle f128. If the target does not have native f128 support,
1213 // expand it to i128 and we will be generating soft float library calls.
1214 if (!isTypeLegal(MVT::f128)) {
1215 NumRegistersForVT[MVT::f128] = NumRegistersForVT[MVT::i128];
1216 RegisterTypeForVT[MVT::f128] = RegisterTypeForVT[MVT::i128];
1217 TransformToType[MVT::f128] = MVT::i128;
1218 ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
1221 // Decide how to handle f64. If the target does not have native f64 support,
1222 // expand it to i64 and we will be generating soft float library calls.
1223 if (!isTypeLegal(MVT::f64)) {
1224 NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64];
1225 RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64];
1226 TransformToType[MVT::f64] = MVT::i64;
1227 ValueTypeActions.setTypeAction(MVT::f64, TypeSoftenFloat);
1230 // Decide how to handle f32. If the target does not have native f32 support,
1231 // expand it to i32 and we will be generating soft float library calls.
1232 if (!isTypeLegal(MVT::f32)) {
1233 NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32];
1234 RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32];
1235 TransformToType[MVT::f32] = MVT::i32;
1236 ValueTypeActions.setTypeAction(MVT::f32, TypeSoftenFloat);
1239 // Decide how to handle f16. If the target does not have native f16 support,
1240 // promote it to f32, because there are no f16 library calls (except for
1241 // conversions).
1242 if (!isTypeLegal(MVT::f16)) {
1243 NumRegistersForVT[MVT::f16] = NumRegistersForVT[MVT::f32];
1244 RegisterTypeForVT[MVT::f16] = RegisterTypeForVT[MVT::f32];
1245 TransformToType[MVT::f16] = MVT::f32;
1246 ValueTypeActions.setTypeAction(MVT::f16, TypePromoteFloat);
1249 // Loop over all of the vector value types to see which need transformations.
1250 for (unsigned i = MVT::FIRST_VECTOR_VALUETYPE;
1251 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1252 MVT VT = (MVT::SimpleValueType) i;
1253 if (isTypeLegal(VT))
1254 continue;
1256 MVT EltVT = VT.getVectorElementType();
1257 unsigned NElts = VT.getVectorNumElements();
1258 bool IsLegalWiderType = false;
1259 LegalizeTypeAction PreferredAction = getPreferredVectorAction(VT);
1260 switch (PreferredAction) {
1261 case TypePromoteInteger:
1262 // Try to promote the elements of integer vectors. If no legal
1263 // promotion was found, fall through to the widen-vector method.
1264 for (unsigned nVT = i + 1; nVT <= MVT::LAST_INTEGER_VECTOR_VALUETYPE; ++nVT) {
1265 MVT SVT = (MVT::SimpleValueType) nVT;
1266 // Promote vectors of integers to vectors with the same number
1267 // of elements, with a wider element type.
1268 if (SVT.getScalarSizeInBits() > EltVT.getSizeInBits() &&
1269 SVT.getVectorNumElements() == NElts && isTypeLegal(SVT)) {
1270 TransformToType[i] = SVT;
1271 RegisterTypeForVT[i] = SVT;
1272 NumRegistersForVT[i] = 1;
1273 ValueTypeActions.setTypeAction(VT, TypePromoteInteger);
1274 IsLegalWiderType = true;
1275 break;
1278 if (IsLegalWiderType)
1279 break;
1280 LLVM_FALLTHROUGH;
1282 case TypeWidenVector:
1283 if (isPowerOf2_32(NElts)) {
1284 // Try to widen the vector.
1285 for (unsigned nVT = i + 1; nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
1286 MVT SVT = (MVT::SimpleValueType) nVT;
1287 if (SVT.getVectorElementType() == EltVT
1288 && SVT.getVectorNumElements() > NElts && isTypeLegal(SVT)) {
1289 TransformToType[i] = SVT;
1290 RegisterTypeForVT[i] = SVT;
1291 NumRegistersForVT[i] = 1;
1292 ValueTypeActions.setTypeAction(VT, TypeWidenVector);
1293 IsLegalWiderType = true;
1294 break;
1297 if (IsLegalWiderType)
1298 break;
1299 } else {
1300 // Only widen to the next power of 2 to keep consistency with EVT.
1301 MVT NVT = VT.getPow2VectorType();
1302 if (isTypeLegal(NVT)) {
1303 TransformToType[i] = NVT;
1304 ValueTypeActions.setTypeAction(VT, TypeWidenVector);
1305 RegisterTypeForVT[i] = NVT;
1306 NumRegistersForVT[i] = 1;
1307 break;
1310 LLVM_FALLTHROUGH;
1312 case TypeSplitVector:
1313 case TypeScalarizeVector: {
1314 MVT IntermediateVT;
1315 MVT RegisterVT;
1316 unsigned NumIntermediates;
1317 NumRegistersForVT[i] = getVectorTypeBreakdownMVT(VT, IntermediateVT,
1318 NumIntermediates, RegisterVT, this);
1319 RegisterTypeForVT[i] = RegisterVT;
1321 MVT NVT = VT.getPow2VectorType();
1322 if (NVT == VT) {
1323 // Type is already a power of 2. The default action is to split.
1324 TransformToType[i] = MVT::Other;
1325 if (PreferredAction == TypeScalarizeVector)
1326 ValueTypeActions.setTypeAction(VT, TypeScalarizeVector);
1327 else if (PreferredAction == TypeSplitVector)
1328 ValueTypeActions.setTypeAction(VT, TypeSplitVector);
1329 else
1330 // Set type action according to the number of elements.
1331 ValueTypeActions.setTypeAction(VT, NElts == 1 ? TypeScalarizeVector
1332 : TypeSplitVector);
1333 } else {
1334 TransformToType[i] = NVT;
1335 ValueTypeActions.setTypeAction(VT, TypeWidenVector);
1337 break;
1339 default:
1340 llvm_unreachable("Unknown vector legalization action!");
1344 // Determine the 'representative' register class for each value type.
1345 // An representative register class is the largest (meaning one which is
1346 // not a sub-register class / subreg register class) legal register class for
1347 // a group of value types. For example, on i386, i8, i16, and i32
1348 // representative would be GR32; while on x86_64 it's GR64.
1349 for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
1350 const TargetRegisterClass* RRC;
1351 uint8_t Cost;
1352 std::tie(RRC, Cost) = findRepresentativeClass(TRI, (MVT::SimpleValueType)i);
1353 RepRegClassForVT[i] = RRC;
1354 RepRegClassCostForVT[i] = Cost;
1358 EVT TargetLoweringBase::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1359 EVT VT) const {
1360 assert(!VT.isVector() && "No default SetCC type for vectors!");
1361 return getPointerTy(DL).SimpleTy;
1364 MVT::SimpleValueType TargetLoweringBase::getCmpLibcallReturnType() const {
1365 return MVT::i32; // return the default value
1368 /// getVectorTypeBreakdown - Vector types are broken down into some number of
1369 /// legal first class types. For example, MVT::v8f32 maps to 2 MVT::v4f32
1370 /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
1371 /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
1373 /// This method returns the number of registers needed, and the VT for each
1374 /// register. It also returns the VT and quantity of the intermediate values
1375 /// before they are promoted/expanded.
1376 unsigned TargetLoweringBase::getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
1377 EVT &IntermediateVT,
1378 unsigned &NumIntermediates,
1379 MVT &RegisterVT) const {
1380 unsigned NumElts = VT.getVectorNumElements();
1382 // If there is a wider vector type with the same element type as this one,
1383 // or a promoted vector type that has the same number of elements which
1384 // are wider, then we should convert to that legal vector type.
1385 // This handles things like <2 x float> -> <4 x float> and
1386 // <4 x i1> -> <4 x i32>.
1387 LegalizeTypeAction TA = getTypeAction(Context, VT);
1388 if (NumElts != 1 && (TA == TypeWidenVector || TA == TypePromoteInteger)) {
1389 EVT RegisterEVT = getTypeToTransformTo(Context, VT);
1390 if (isTypeLegal(RegisterEVT)) {
1391 IntermediateVT = RegisterEVT;
1392 RegisterVT = RegisterEVT.getSimpleVT();
1393 NumIntermediates = 1;
1394 return 1;
1398 // Figure out the right, legal destination reg to copy into.
1399 EVT EltTy = VT.getVectorElementType();
1401 unsigned NumVectorRegs = 1;
1403 // FIXME: We don't support non-power-of-2-sized vectors for now. Ideally we
1404 // could break down into LHS/RHS like LegalizeDAG does.
1405 if (!isPowerOf2_32(NumElts)) {
1406 NumVectorRegs = NumElts;
1407 NumElts = 1;
1410 // Divide the input until we get to a supported size. This will always
1411 // end with a scalar if the target doesn't support vectors.
1412 while (NumElts > 1 && !isTypeLegal(
1413 EVT::getVectorVT(Context, EltTy, NumElts))) {
1414 NumElts >>= 1;
1415 NumVectorRegs <<= 1;
1418 NumIntermediates = NumVectorRegs;
1420 EVT NewVT = EVT::getVectorVT(Context, EltTy, NumElts);
1421 if (!isTypeLegal(NewVT))
1422 NewVT = EltTy;
1423 IntermediateVT = NewVT;
1425 MVT DestVT = getRegisterType(Context, NewVT);
1426 RegisterVT = DestVT;
1427 unsigned NewVTSize = NewVT.getSizeInBits();
1429 // Convert sizes such as i33 to i64.
1430 if (!isPowerOf2_32(NewVTSize))
1431 NewVTSize = NextPowerOf2(NewVTSize);
1433 if (EVT(DestVT).bitsLT(NewVT)) // Value is expanded, e.g. i64 -> i16.
1434 return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits());
1436 // Otherwise, promotion or legal types use the same number of registers as
1437 // the vector decimated to the appropriate level.
1438 return NumVectorRegs;
1441 /// Get the EVTs and ArgFlags collections that represent the legalized return
1442 /// type of the given function. This does not require a DAG or a return value,
1443 /// and is suitable for use before any DAGs for the function are constructed.
1444 /// TODO: Move this out of TargetLowering.cpp.
1445 void llvm::GetReturnInfo(CallingConv::ID CC, Type *ReturnType,
1446 AttributeList attr,
1447 SmallVectorImpl<ISD::OutputArg> &Outs,
1448 const TargetLowering &TLI, const DataLayout &DL) {
1449 SmallVector<EVT, 4> ValueVTs;
1450 ComputeValueVTs(TLI, DL, ReturnType, ValueVTs);
1451 unsigned NumValues = ValueVTs.size();
1452 if (NumValues == 0) return;
1454 for (unsigned j = 0, f = NumValues; j != f; ++j) {
1455 EVT VT = ValueVTs[j];
1456 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1458 if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt))
1459 ExtendKind = ISD::SIGN_EXTEND;
1460 else if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt))
1461 ExtendKind = ISD::ZERO_EXTEND;
1463 // FIXME: C calling convention requires the return type to be promoted to
1464 // at least 32-bit. But this is not necessary for non-C calling
1465 // conventions. The frontend should mark functions whose return values
1466 // require promoting with signext or zeroext attributes.
1467 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
1468 MVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
1469 if (VT.bitsLT(MinVT))
1470 VT = MinVT;
1473 unsigned NumParts =
1474 TLI.getNumRegistersForCallingConv(ReturnType->getContext(), CC, VT);
1475 MVT PartVT =
1476 TLI.getRegisterTypeForCallingConv(ReturnType->getContext(), CC, VT);
1478 // 'inreg' on function refers to return value
1479 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1480 if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::InReg))
1481 Flags.setInReg();
1483 // Propagate extension type if any
1484 if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt))
1485 Flags.setSExt();
1486 else if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt))
1487 Flags.setZExt();
1489 for (unsigned i = 0; i < NumParts; ++i)
1490 Outs.push_back(ISD::OutputArg(Flags, PartVT, VT, /*isfixed=*/true, 0, 0));
1494 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1495 /// function arguments in the caller parameter area. This is the actual
1496 /// alignment, not its logarithm.
1497 unsigned TargetLoweringBase::getByValTypeAlignment(Type *Ty,
1498 const DataLayout &DL) const {
1499 return DL.getABITypeAlignment(Ty);
1502 bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context,
1503 const DataLayout &DL, EVT VT,
1504 unsigned AddrSpace,
1505 unsigned Alignment,
1506 MachineMemOperand::Flags Flags,
1507 bool *Fast) const {
1508 // Check if the specified alignment is sufficient based on the data layout.
1509 // TODO: While using the data layout works in practice, a better solution
1510 // would be to implement this check directly (make this a virtual function).
1511 // For example, the ABI alignment may change based on software platform while
1512 // this function should only be affected by hardware implementation.
1513 Type *Ty = VT.getTypeForEVT(Context);
1514 if (Alignment >= DL.getABITypeAlignment(Ty)) {
1515 // Assume that an access that meets the ABI-specified alignment is fast.
1516 if (Fast != nullptr)
1517 *Fast = true;
1518 return true;
1521 // This is a misaligned access.
1522 return allowsMisalignedMemoryAccesses(VT, AddrSpace, Alignment, Flags, Fast);
1525 bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context,
1526 const DataLayout &DL, EVT VT,
1527 const MachineMemOperand &MMO,
1528 bool *Fast) const {
1529 return allowsMemoryAccess(Context, DL, VT, MMO.getAddrSpace(),
1530 MMO.getAlignment(), MMO.getFlags(), Fast);
1533 BranchProbability TargetLoweringBase::getPredictableBranchThreshold() const {
1534 return BranchProbability(MinPercentageForPredictableBranch, 100);
1537 //===----------------------------------------------------------------------===//
1538 // TargetTransformInfo Helpers
1539 //===----------------------------------------------------------------------===//
1541 int TargetLoweringBase::InstructionOpcodeToISD(unsigned Opcode) const {
1542 enum InstructionOpcodes {
1543 #define HANDLE_INST(NUM, OPCODE, CLASS) OPCODE = NUM,
1544 #define LAST_OTHER_INST(NUM) InstructionOpcodesCount = NUM
1545 #include "llvm/IR/Instruction.def"
1547 switch (static_cast<InstructionOpcodes>(Opcode)) {
1548 case Ret: return 0;
1549 case Br: return 0;
1550 case Switch: return 0;
1551 case IndirectBr: return 0;
1552 case Invoke: return 0;
1553 case CallBr: return 0;
1554 case Resume: return 0;
1555 case Unreachable: return 0;
1556 case CleanupRet: return 0;
1557 case CatchRet: return 0;
1558 case CatchPad: return 0;
1559 case CatchSwitch: return 0;
1560 case CleanupPad: return 0;
1561 case FNeg: return ISD::FNEG;
1562 case Add: return ISD::ADD;
1563 case FAdd: return ISD::FADD;
1564 case Sub: return ISD::SUB;
1565 case FSub: return ISD::FSUB;
1566 case Mul: return ISD::MUL;
1567 case FMul: return ISD::FMUL;
1568 case UDiv: return ISD::UDIV;
1569 case SDiv: return ISD::SDIV;
1570 case FDiv: return ISD::FDIV;
1571 case URem: return ISD::UREM;
1572 case SRem: return ISD::SREM;
1573 case FRem: return ISD::FREM;
1574 case Shl: return ISD::SHL;
1575 case LShr: return ISD::SRL;
1576 case AShr: return ISD::SRA;
1577 case And: return ISD::AND;
1578 case Or: return ISD::OR;
1579 case Xor: return ISD::XOR;
1580 case Alloca: return 0;
1581 case Load: return ISD::LOAD;
1582 case Store: return ISD::STORE;
1583 case GetElementPtr: return 0;
1584 case Fence: return 0;
1585 case AtomicCmpXchg: return 0;
1586 case AtomicRMW: return 0;
1587 case Trunc: return ISD::TRUNCATE;
1588 case ZExt: return ISD::ZERO_EXTEND;
1589 case SExt: return ISD::SIGN_EXTEND;
1590 case FPToUI: return ISD::FP_TO_UINT;
1591 case FPToSI: return ISD::FP_TO_SINT;
1592 case UIToFP: return ISD::UINT_TO_FP;
1593 case SIToFP: return ISD::SINT_TO_FP;
1594 case FPTrunc: return ISD::FP_ROUND;
1595 case FPExt: return ISD::FP_EXTEND;
1596 case PtrToInt: return ISD::BITCAST;
1597 case IntToPtr: return ISD::BITCAST;
1598 case BitCast: return ISD::BITCAST;
1599 case AddrSpaceCast: return ISD::ADDRSPACECAST;
1600 case ICmp: return ISD::SETCC;
1601 case FCmp: return ISD::SETCC;
1602 case PHI: return 0;
1603 case Call: return 0;
1604 case Select: return ISD::SELECT;
1605 case UserOp1: return 0;
1606 case UserOp2: return 0;
1607 case VAArg: return 0;
1608 case ExtractElement: return ISD::EXTRACT_VECTOR_ELT;
1609 case InsertElement: return ISD::INSERT_VECTOR_ELT;
1610 case ShuffleVector: return ISD::VECTOR_SHUFFLE;
1611 case ExtractValue: return ISD::MERGE_VALUES;
1612 case InsertValue: return ISD::MERGE_VALUES;
1613 case LandingPad: return 0;
1616 llvm_unreachable("Unknown instruction type encountered!");
1619 std::pair<int, MVT>
1620 TargetLoweringBase::getTypeLegalizationCost(const DataLayout &DL,
1621 Type *Ty) const {
1622 LLVMContext &C = Ty->getContext();
1623 EVT MTy = getValueType(DL, Ty);
1625 int Cost = 1;
1626 // We keep legalizing the type until we find a legal kind. We assume that
1627 // the only operation that costs anything is the split. After splitting
1628 // we need to handle two types.
1629 while (true) {
1630 LegalizeKind LK = getTypeConversion(C, MTy);
1632 if (LK.first == TypeLegal)
1633 return std::make_pair(Cost, MTy.getSimpleVT());
1635 if (LK.first == TypeSplitVector || LK.first == TypeExpandInteger)
1636 Cost *= 2;
1638 // Do not loop with f128 type.
1639 if (MTy == LK.second)
1640 return std::make_pair(Cost, MTy.getSimpleVT());
1642 // Keep legalizing the type.
1643 MTy = LK.second;
1647 Value *TargetLoweringBase::getDefaultSafeStackPointerLocation(IRBuilder<> &IRB,
1648 bool UseTLS) const {
1649 // compiler-rt provides a variable with a magic name. Targets that do not
1650 // link with compiler-rt may also provide such a variable.
1651 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
1652 const char *UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr";
1653 auto UnsafeStackPtr =
1654 dyn_cast_or_null<GlobalVariable>(M->getNamedValue(UnsafeStackPtrVar));
1656 Type *StackPtrTy = Type::getInt8PtrTy(M->getContext());
1658 if (!UnsafeStackPtr) {
1659 auto TLSModel = UseTLS ?
1660 GlobalValue::InitialExecTLSModel :
1661 GlobalValue::NotThreadLocal;
1662 // The global variable is not defined yet, define it ourselves.
1663 // We use the initial-exec TLS model because we do not support the
1664 // variable living anywhere other than in the main executable.
1665 UnsafeStackPtr = new GlobalVariable(
1666 *M, StackPtrTy, false, GlobalValue::ExternalLinkage, nullptr,
1667 UnsafeStackPtrVar, nullptr, TLSModel);
1668 } else {
1669 // The variable exists, check its type and attributes.
1670 if (UnsafeStackPtr->getValueType() != StackPtrTy)
1671 report_fatal_error(Twine(UnsafeStackPtrVar) + " must have void* type");
1672 if (UseTLS != UnsafeStackPtr->isThreadLocal())
1673 report_fatal_error(Twine(UnsafeStackPtrVar) + " must " +
1674 (UseTLS ? "" : "not ") + "be thread-local");
1676 return UnsafeStackPtr;
1679 Value *TargetLoweringBase::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
1680 if (!TM.getTargetTriple().isAndroid())
1681 return getDefaultSafeStackPointerLocation(IRB, true);
1683 // Android provides a libc function to retrieve the address of the current
1684 // thread's unsafe stack pointer.
1685 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
1686 Type *StackPtrTy = Type::getInt8PtrTy(M->getContext());
1687 FunctionCallee Fn = M->getOrInsertFunction("__safestack_pointer_address",
1688 StackPtrTy->getPointerTo(0));
1689 return IRB.CreateCall(Fn);
1692 //===----------------------------------------------------------------------===//
1693 // Loop Strength Reduction hooks
1694 //===----------------------------------------------------------------------===//
1696 /// isLegalAddressingMode - Return true if the addressing mode represented
1697 /// by AM is legal for this target, for a load/store of the specified type.
1698 bool TargetLoweringBase::isLegalAddressingMode(const DataLayout &DL,
1699 const AddrMode &AM, Type *Ty,
1700 unsigned AS, Instruction *I) const {
1701 // The default implementation of this implements a conservative RISCy, r+r and
1702 // r+i addr mode.
1704 // Allows a sign-extended 16-bit immediate field.
1705 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
1706 return false;
1708 // No global is ever allowed as a base.
1709 if (AM.BaseGV)
1710 return false;
1712 // Only support r+r,
1713 switch (AM.Scale) {
1714 case 0: // "r+i" or just "i", depending on HasBaseReg.
1715 break;
1716 case 1:
1717 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
1718 return false;
1719 // Otherwise we have r+r or r+i.
1720 break;
1721 case 2:
1722 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
1723 return false;
1724 // Allow 2*r as r+r.
1725 break;
1726 default: // Don't allow n * r
1727 return false;
1730 return true;
1733 //===----------------------------------------------------------------------===//
1734 // Stack Protector
1735 //===----------------------------------------------------------------------===//
1737 // For OpenBSD return its special guard variable. Otherwise return nullptr,
1738 // so that SelectionDAG handle SSP.
1739 Value *TargetLoweringBase::getIRStackGuard(IRBuilder<> &IRB) const {
1740 if (getTargetMachine().getTargetTriple().isOSOpenBSD()) {
1741 Module &M = *IRB.GetInsertBlock()->getParent()->getParent();
1742 PointerType *PtrTy = Type::getInt8PtrTy(M.getContext());
1743 return M.getOrInsertGlobal("__guard_local", PtrTy);
1745 return nullptr;
1748 // Currently only support "standard" __stack_chk_guard.
1749 // TODO: add LOAD_STACK_GUARD support.
1750 void TargetLoweringBase::insertSSPDeclarations(Module &M) const {
1751 if (!M.getNamedValue("__stack_chk_guard"))
1752 new GlobalVariable(M, Type::getInt8PtrTy(M.getContext()), false,
1753 GlobalVariable::ExternalLinkage,
1754 nullptr, "__stack_chk_guard");
1757 // Currently only support "standard" __stack_chk_guard.
1758 // TODO: add LOAD_STACK_GUARD support.
1759 Value *TargetLoweringBase::getSDagStackGuard(const Module &M) const {
1760 return M.getNamedValue("__stack_chk_guard");
1763 Function *TargetLoweringBase::getSSPStackGuardCheck(const Module &M) const {
1764 return nullptr;
1767 unsigned TargetLoweringBase::getMinimumJumpTableEntries() const {
1768 return MinimumJumpTableEntries;
1771 void TargetLoweringBase::setMinimumJumpTableEntries(unsigned Val) {
1772 MinimumJumpTableEntries = Val;
1775 unsigned TargetLoweringBase::getMinimumJumpTableDensity(bool OptForSize) const {
1776 return OptForSize ? OptsizeJumpTableDensity : JumpTableDensity;
1779 unsigned TargetLoweringBase::getMaximumJumpTableSize() const {
1780 return MaximumJumpTableSize;
1783 void TargetLoweringBase::setMaximumJumpTableSize(unsigned Val) {
1784 MaximumJumpTableSize = Val;
1787 //===----------------------------------------------------------------------===//
1788 // Reciprocal Estimates
1789 //===----------------------------------------------------------------------===//
1791 /// Get the reciprocal estimate attribute string for a function that will
1792 /// override the target defaults.
1793 static StringRef getRecipEstimateForFunc(MachineFunction &MF) {
1794 const Function &F = MF.getFunction();
1795 return F.getFnAttribute("reciprocal-estimates").getValueAsString();
1798 /// Construct a string for the given reciprocal operation of the given type.
1799 /// This string should match the corresponding option to the front-end's
1800 /// "-mrecip" flag assuming those strings have been passed through in an
1801 /// attribute string. For example, "vec-divf" for a division of a vXf32.
1802 static std::string getReciprocalOpName(bool IsSqrt, EVT VT) {
1803 std::string Name = VT.isVector() ? "vec-" : "";
1805 Name += IsSqrt ? "sqrt" : "div";
1807 // TODO: Handle "half" or other float types?
1808 if (VT.getScalarType() == MVT::f64) {
1809 Name += "d";
1810 } else {
1811 assert(VT.getScalarType() == MVT::f32 &&
1812 "Unexpected FP type for reciprocal estimate");
1813 Name += "f";
1816 return Name;
1819 /// Return the character position and value (a single numeric character) of a
1820 /// customized refinement operation in the input string if it exists. Return
1821 /// false if there is no customized refinement step count.
1822 static bool parseRefinementStep(StringRef In, size_t &Position,
1823 uint8_t &Value) {
1824 const char RefStepToken = ':';
1825 Position = In.find(RefStepToken);
1826 if (Position == StringRef::npos)
1827 return false;
1829 StringRef RefStepString = In.substr(Position + 1);
1830 // Allow exactly one numeric character for the additional refinement
1831 // step parameter.
1832 if (RefStepString.size() == 1) {
1833 char RefStepChar = RefStepString[0];
1834 if (RefStepChar >= '0' && RefStepChar <= '9') {
1835 Value = RefStepChar - '0';
1836 return true;
1839 report_fatal_error("Invalid refinement step for -recip.");
1842 /// For the input attribute string, return one of the ReciprocalEstimate enum
1843 /// status values (enabled, disabled, or not specified) for this operation on
1844 /// the specified data type.
1845 static int getOpEnabled(bool IsSqrt, EVT VT, StringRef Override) {
1846 if (Override.empty())
1847 return TargetLoweringBase::ReciprocalEstimate::Unspecified;
1849 SmallVector<StringRef, 4> OverrideVector;
1850 Override.split(OverrideVector, ',');
1851 unsigned NumArgs = OverrideVector.size();
1853 // Check if "all", "none", or "default" was specified.
1854 if (NumArgs == 1) {
1855 // Look for an optional setting of the number of refinement steps needed
1856 // for this type of reciprocal operation.
1857 size_t RefPos;
1858 uint8_t RefSteps;
1859 if (parseRefinementStep(Override, RefPos, RefSteps)) {
1860 // Split the string for further processing.
1861 Override = Override.substr(0, RefPos);
1864 // All reciprocal types are enabled.
1865 if (Override == "all")
1866 return TargetLoweringBase::ReciprocalEstimate::Enabled;
1868 // All reciprocal types are disabled.
1869 if (Override == "none")
1870 return TargetLoweringBase::ReciprocalEstimate::Disabled;
1872 // Target defaults for enablement are used.
1873 if (Override == "default")
1874 return TargetLoweringBase::ReciprocalEstimate::Unspecified;
1877 // The attribute string may omit the size suffix ('f'/'d').
1878 std::string VTName = getReciprocalOpName(IsSqrt, VT);
1879 std::string VTNameNoSize = VTName;
1880 VTNameNoSize.pop_back();
1881 static const char DisabledPrefix = '!';
1883 for (StringRef RecipType : OverrideVector) {
1884 size_t RefPos;
1885 uint8_t RefSteps;
1886 if (parseRefinementStep(RecipType, RefPos, RefSteps))
1887 RecipType = RecipType.substr(0, RefPos);
1889 // Ignore the disablement token for string matching.
1890 bool IsDisabled = RecipType[0] == DisabledPrefix;
1891 if (IsDisabled)
1892 RecipType = RecipType.substr(1);
1894 if (RecipType.equals(VTName) || RecipType.equals(VTNameNoSize))
1895 return IsDisabled ? TargetLoweringBase::ReciprocalEstimate::Disabled
1896 : TargetLoweringBase::ReciprocalEstimate::Enabled;
1899 return TargetLoweringBase::ReciprocalEstimate::Unspecified;
1902 /// For the input attribute string, return the customized refinement step count
1903 /// for this operation on the specified data type. If the step count does not
1904 /// exist, return the ReciprocalEstimate enum value for unspecified.
1905 static int getOpRefinementSteps(bool IsSqrt, EVT VT, StringRef Override) {
1906 if (Override.empty())
1907 return TargetLoweringBase::ReciprocalEstimate::Unspecified;
1909 SmallVector<StringRef, 4> OverrideVector;
1910 Override.split(OverrideVector, ',');
1911 unsigned NumArgs = OverrideVector.size();
1913 // Check if "all", "default", or "none" was specified.
1914 if (NumArgs == 1) {
1915 // Look for an optional setting of the number of refinement steps needed
1916 // for this type of reciprocal operation.
1917 size_t RefPos;
1918 uint8_t RefSteps;
1919 if (!parseRefinementStep(Override, RefPos, RefSteps))
1920 return TargetLoweringBase::ReciprocalEstimate::Unspecified;
1922 // Split the string for further processing.
1923 Override = Override.substr(0, RefPos);
1924 assert(Override != "none" &&
1925 "Disabled reciprocals, but specifed refinement steps?");
1927 // If this is a general override, return the specified number of steps.
1928 if (Override == "all" || Override == "default")
1929 return RefSteps;
1932 // The attribute string may omit the size suffix ('f'/'d').
1933 std::string VTName = getReciprocalOpName(IsSqrt, VT);
1934 std::string VTNameNoSize = VTName;
1935 VTNameNoSize.pop_back();
1937 for (StringRef RecipType : OverrideVector) {
1938 size_t RefPos;
1939 uint8_t RefSteps;
1940 if (!parseRefinementStep(RecipType, RefPos, RefSteps))
1941 continue;
1943 RecipType = RecipType.substr(0, RefPos);
1944 if (RecipType.equals(VTName) || RecipType.equals(VTNameNoSize))
1945 return RefSteps;
1948 return TargetLoweringBase::ReciprocalEstimate::Unspecified;
1951 int TargetLoweringBase::getRecipEstimateSqrtEnabled(EVT VT,
1952 MachineFunction &MF) const {
1953 return getOpEnabled(true, VT, getRecipEstimateForFunc(MF));
1956 int TargetLoweringBase::getRecipEstimateDivEnabled(EVT VT,
1957 MachineFunction &MF) const {
1958 return getOpEnabled(false, VT, getRecipEstimateForFunc(MF));
1961 int TargetLoweringBase::getSqrtRefinementSteps(EVT VT,
1962 MachineFunction &MF) const {
1963 return getOpRefinementSteps(true, VT, getRecipEstimateForFunc(MF));
1966 int TargetLoweringBase::getDivRefinementSteps(EVT VT,
1967 MachineFunction &MF) const {
1968 return getOpRefinementSteps(false, VT, getRecipEstimateForFunc(MF));
1971 void TargetLoweringBase::finalizeLowering(MachineFunction &MF) const {
1972 MF.getRegInfo().freezeReservedRegs(MF);