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.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/ADT/BitVector.h"
14#include "llvm/ADT/DenseMap.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/SmallVector.h"
17#include "llvm/ADT/StringExtras.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/ADT/Twine.h"
20#include "llvm/Analysis/Loads.h"
21#include "llvm/Analysis/TargetTransformInfo.h"
22#include "llvm/CodeGen/Analysis.h"
23#include "llvm/CodeGen/ISDOpcodes.h"
24#include "llvm/CodeGen/MachineBasicBlock.h"
25#include "llvm/CodeGen/MachineFrameInfo.h"
26#include "llvm/CodeGen/MachineFunction.h"
27#include "llvm/CodeGen/MachineInstr.h"
28#include "llvm/CodeGen/MachineInstrBuilder.h"
29#include "llvm/CodeGen/MachineMemOperand.h"
30#include "llvm/CodeGen/MachineOperand.h"
31#include "llvm/CodeGen/MachineRegisterInfo.h"
32#include "llvm/CodeGen/RuntimeLibcallUtil.h"
33#include "llvm/CodeGen/StackMaps.h"
34#include "llvm/CodeGen/TargetLowering.h"
35#include "llvm/CodeGen/TargetOpcodes.h"
36#include "llvm/CodeGen/TargetRegisterInfo.h"
37#include "llvm/CodeGen/ValueTypes.h"
38#include "llvm/CodeGenTypes/MachineValueType.h"
39#include "llvm/IR/Attributes.h"
40#include "llvm/IR/CallingConv.h"
41#include "llvm/IR/DataLayout.h"
42#include "llvm/IR/DerivedTypes.h"
43#include "llvm/IR/Function.h"
44#include "llvm/IR/GlobalValue.h"
45#include "llvm/IR/GlobalVariable.h"
46#include "llvm/IR/IRBuilder.h"
47#include "llvm/IR/Module.h"
48#include "llvm/IR/Type.h"
49#include "llvm/Support/Casting.h"
50#include "llvm/Support/CommandLine.h"
51#include "llvm/Support/Compiler.h"
52#include "llvm/Support/ErrorHandling.h"
53#include "llvm/Support/MathExtras.h"
54#include "llvm/Target/TargetMachine.h"
55#include "llvm/Target/TargetOptions.h"
56#include "llvm/TargetParser/Triple.h"
57#include "llvm/Transforms/Utils/SizeOpts.h"
58#include <algorithm>
59#include <cassert>
60#include <cstdint>
61#include <cstring>
62#include <string>
63#include <tuple>
64#include <utility>
65
66using namespace llvm;
67
68static cl::opt<bool> JumpIsExpensiveOverride(
69 "jump-is-expensive", cl::init(Val: false),
70 cl::desc("Do not create extra branches to split comparison logic."),
71 cl::Hidden);
72
73static cl::opt<unsigned> MinimumJumpTableEntries
74 ("min-jump-table-entries", cl::init(Val: 4), cl::Hidden,
75 cl::desc("Set minimum number of entries to use a jump table."));
76
77static cl::opt<unsigned> MaximumJumpTableSize
78 ("max-jump-table-size", cl::init(UINT_MAX), cl::Hidden,
79 cl::desc("Set maximum size of jump tables."));
80
81/// Minimum jump table density for normal functions.
82static cl::opt<unsigned>
83 JumpTableDensity("jump-table-density", cl::init(Val: 10), cl::Hidden,
84 cl::desc("Minimum density for building a jump table in "
85 "a normal function"));
86
87/// Minimum jump table density for -Os or -Oz functions.
88static cl::opt<unsigned> OptsizeJumpTableDensity(
89 "optsize-jump-table-density", cl::init(Val: 40), cl::Hidden,
90 cl::desc("Minimum density for building a jump table in "
91 "an optsize function"));
92
93static cl::opt<unsigned> MinimumBitTestCmpsOverride(
94 "min-bit-test-cmps", cl::init(Val: 2), cl::Hidden,
95 cl::desc("Set minimum of largest number of comparisons "
96 "to use bit test for switch."));
97
98static cl::opt<unsigned> MaxStoresPerMemsetOverride(
99 "max-store-memset", cl::init(Val: 0), cl::Hidden,
100 cl::desc("Override target's MaxStoresPerMemset and "
101 "MaxStoresPerMemsetOptSize. "
102 "Set to 0 to use the target default."));
103
104static cl::opt<unsigned> MaxStoresPerMemcpyOverride(
105 "max-store-memcpy", cl::init(Val: 0), cl::Hidden,
106 cl::desc("Override target's MaxStoresPerMemcpy and "
107 "MaxStoresPerMemcpyOptSize. "
108 "Set to 0 to use the target default."));
109
110static cl::opt<unsigned> MaxStoresPerMemmoveOverride(
111 "max-store-memmove", cl::init(Val: 0), cl::Hidden,
112 cl::desc("Override target's MaxStoresPerMemmove and "
113 "MaxStoresPerMemmoveOptSize. "
114 "Set to 0 to use the target default."));
115
116// FIXME: This option is only to test if the strict fp operation processed
117// correctly by preventing mutating strict fp operation to normal fp operation
118// during development. When the backend supports strict float operation, this
119// option will be meaningless.
120static cl::opt<bool> DisableStrictNodeMutation("disable-strictnode-mutation",
121 cl::desc("Don't mutate strict-float node to a legalize node"),
122 cl::init(Val: false), cl::Hidden);
123
124LLVM_ABI RTLIB::Libcall RTLIB::getSHL(EVT VT) {
125 if (VT == MVT::i16)
126 return RTLIB::SHL_I16;
127 if (VT == MVT::i32)
128 return RTLIB::SHL_I32;
129 if (VT == MVT::i64)
130 return RTLIB::SHL_I64;
131 if (VT == MVT::i128)
132 return RTLIB::SHL_I128;
133
134 return RTLIB::UNKNOWN_LIBCALL;
135}
136
137LLVM_ABI RTLIB::Libcall RTLIB::getSRL(EVT VT) {
138 if (VT == MVT::i16)
139 return RTLIB::SRL_I16;
140 if (VT == MVT::i32)
141 return RTLIB::SRL_I32;
142 if (VT == MVT::i64)
143 return RTLIB::SRL_I64;
144 if (VT == MVT::i128)
145 return RTLIB::SRL_I128;
146
147 return RTLIB::UNKNOWN_LIBCALL;
148}
149
150LLVM_ABI RTLIB::Libcall RTLIB::getSRA(EVT VT) {
151 if (VT == MVT::i16)
152 return RTLIB::SRA_I16;
153 if (VT == MVT::i32)
154 return RTLIB::SRA_I32;
155 if (VT == MVT::i64)
156 return RTLIB::SRA_I64;
157 if (VT == MVT::i128)
158 return RTLIB::SRA_I128;
159
160 return RTLIB::UNKNOWN_LIBCALL;
161}
162
163LLVM_ABI RTLIB::Libcall RTLIB::getMUL(EVT VT) {
164 if (VT == MVT::i16)
165 return RTLIB::MUL_I16;
166 if (VT == MVT::i32)
167 return RTLIB::MUL_I32;
168 if (VT == MVT::i64)
169 return RTLIB::MUL_I64;
170 if (VT == MVT::i128)
171 return RTLIB::MUL_I128;
172 return RTLIB::UNKNOWN_LIBCALL;
173}
174
175LLVM_ABI RTLIB::Libcall RTLIB::getMULO(EVT VT) {
176 if (VT == MVT::i32)
177 return RTLIB::MULO_I32;
178 if (VT == MVT::i64)
179 return RTLIB::MULO_I64;
180 if (VT == MVT::i128)
181 return RTLIB::MULO_I128;
182 return RTLIB::UNKNOWN_LIBCALL;
183}
184
185LLVM_ABI RTLIB::Libcall RTLIB::getSDIV(EVT VT) {
186 if (VT == MVT::i16)
187 return RTLIB::SDIV_I16;
188 if (VT == MVT::i32)
189 return RTLIB::SDIV_I32;
190 if (VT == MVT::i64)
191 return RTLIB::SDIV_I64;
192 if (VT == MVT::i128)
193 return RTLIB::SDIV_I128;
194 return RTLIB::UNKNOWN_LIBCALL;
195}
196
197LLVM_ABI RTLIB::Libcall RTLIB::getUDIV(EVT VT) {
198 if (VT == MVT::i16)
199 return RTLIB::UDIV_I16;
200 if (VT == MVT::i32)
201 return RTLIB::UDIV_I32;
202 if (VT == MVT::i64)
203 return RTLIB::UDIV_I64;
204 if (VT == MVT::i128)
205 return RTLIB::UDIV_I128;
206 return RTLIB::UNKNOWN_LIBCALL;
207}
208
209LLVM_ABI RTLIB::Libcall RTLIB::getSREM(EVT VT) {
210 if (VT == MVT::i16)
211 return RTLIB::SREM_I16;
212 if (VT == MVT::i32)
213 return RTLIB::SREM_I32;
214 if (VT == MVT::i64)
215 return RTLIB::SREM_I64;
216 if (VT == MVT::i128)
217 return RTLIB::SREM_I128;
218 return RTLIB::UNKNOWN_LIBCALL;
219}
220
221LLVM_ABI RTLIB::Libcall RTLIB::getUREM(EVT VT) {
222 if (VT == MVT::i16)
223 return RTLIB::UREM_I16;
224 if (VT == MVT::i32)
225 return RTLIB::UREM_I32;
226 if (VT == MVT::i64)
227 return RTLIB::UREM_I64;
228 if (VT == MVT::i128)
229 return RTLIB::UREM_I128;
230 return RTLIB::UNKNOWN_LIBCALL;
231}
232
233LLVM_ABI RTLIB::Libcall RTLIB::getCTPOP(EVT VT) {
234 if (VT == MVT::i32)
235 return RTLIB::CTPOP_I32;
236 if (VT == MVT::i64)
237 return RTLIB::CTPOP_I64;
238 if (VT == MVT::i128)
239 return RTLIB::CTPOP_I128;
240 return RTLIB::UNKNOWN_LIBCALL;
241}
242
243/// GetFPLibCall - Helper to return the right libcall for the given floating
244/// point type, or UNKNOWN_LIBCALL if there is none.
245RTLIB::Libcall RTLIB::getFPLibCall(EVT VT,
246 RTLIB::Libcall Call_F32,
247 RTLIB::Libcall Call_F64,
248 RTLIB::Libcall Call_F80,
249 RTLIB::Libcall Call_F128,
250 RTLIB::Libcall Call_PPCF128) {
251 return
252 VT == MVT::f32 ? Call_F32 :
253 VT == MVT::f64 ? Call_F64 :
254 VT == MVT::f80 ? Call_F80 :
255 VT == MVT::f128 ? Call_F128 :
256 VT == MVT::ppcf128 ? Call_PPCF128 :
257 RTLIB::UNKNOWN_LIBCALL;
258}
259
260/// getFPEXT - Return the FPEXT_*_* value for the given types, or
261/// UNKNOWN_LIBCALL if there is none.
262RTLIB::Libcall RTLIB::getFPEXT(EVT OpVT, EVT RetVT) {
263 if (OpVT == MVT::f16) {
264 if (RetVT == MVT::f32)
265 return FPEXT_F16_F32;
266 if (RetVT == MVT::f64)
267 return FPEXT_F16_F64;
268 if (RetVT == MVT::f80)
269 return FPEXT_F16_F80;
270 if (RetVT == MVT::f128)
271 return FPEXT_F16_F128;
272 } else if (OpVT == MVT::f32) {
273 if (RetVT == MVT::f64)
274 return FPEXT_F32_F64;
275 if (RetVT == MVT::f128)
276 return FPEXT_F32_F128;
277 if (RetVT == MVT::ppcf128)
278 return FPEXT_F32_PPCF128;
279 } else if (OpVT == MVT::f64) {
280 if (RetVT == MVT::f128)
281 return FPEXT_F64_F128;
282 else if (RetVT == MVT::ppcf128)
283 return FPEXT_F64_PPCF128;
284 } else if (OpVT == MVT::f80) {
285 if (RetVT == MVT::f128)
286 return FPEXT_F80_F128;
287 } else if (OpVT == MVT::bf16) {
288 if (RetVT == MVT::f32)
289 return FPEXT_BF16_F32;
290 }
291
292 return UNKNOWN_LIBCALL;
293}
294
295/// getFPROUND - Return the FPROUND_*_* value for the given types, or
296/// UNKNOWN_LIBCALL if there is none.
297RTLIB::Libcall RTLIB::getFPROUND(EVT OpVT, EVT RetVT) {
298 if (RetVT == MVT::f16) {
299 if (OpVT == MVT::f32)
300 return FPROUND_F32_F16;
301 if (OpVT == MVT::f64)
302 return FPROUND_F64_F16;
303 if (OpVT == MVT::f80)
304 return FPROUND_F80_F16;
305 if (OpVT == MVT::f128)
306 return FPROUND_F128_F16;
307 if (OpVT == MVT::ppcf128)
308 return FPROUND_PPCF128_F16;
309 } else if (RetVT == MVT::bf16) {
310 if (OpVT == MVT::f32)
311 return FPROUND_F32_BF16;
312 if (OpVT == MVT::f64)
313 return FPROUND_F64_BF16;
314 if (OpVT == MVT::f80)
315 return FPROUND_F80_BF16;
316 if (OpVT == MVT::f128)
317 return FPROUND_F128_BF16;
318 } else if (RetVT == MVT::f32) {
319 if (OpVT == MVT::f64)
320 return FPROUND_F64_F32;
321 if (OpVT == MVT::f80)
322 return FPROUND_F80_F32;
323 if (OpVT == MVT::f128)
324 return FPROUND_F128_F32;
325 if (OpVT == MVT::ppcf128)
326 return FPROUND_PPCF128_F32;
327 } else if (RetVT == MVT::f64) {
328 if (OpVT == MVT::f80)
329 return FPROUND_F80_F64;
330 if (OpVT == MVT::f128)
331 return FPROUND_F128_F64;
332 if (OpVT == MVT::ppcf128)
333 return FPROUND_PPCF128_F64;
334 } else if (RetVT == MVT::f80) {
335 if (OpVT == MVT::f128)
336 return FPROUND_F128_F80;
337 }
338
339 return UNKNOWN_LIBCALL;
340}
341
342/// getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or
343/// UNKNOWN_LIBCALL if there is none.
344RTLIB::Libcall RTLIB::getFPTOSINT(EVT OpVT, EVT RetVT) {
345 if (OpVT == MVT::f16) {
346 if (RetVT == MVT::i32)
347 return FPTOSINT_F16_I32;
348 if (RetVT == MVT::i64)
349 return FPTOSINT_F16_I64;
350 if (RetVT == MVT::i128)
351 return FPTOSINT_F16_I128;
352 } else if (OpVT == MVT::f32) {
353 if (RetVT == MVT::i32)
354 return FPTOSINT_F32_I32;
355 if (RetVT == MVT::i64)
356 return FPTOSINT_F32_I64;
357 if (RetVT == MVT::i128)
358 return FPTOSINT_F32_I128;
359 } else if (OpVT == MVT::f64) {
360 if (RetVT == MVT::i32)
361 return FPTOSINT_F64_I32;
362 if (RetVT == MVT::i64)
363 return FPTOSINT_F64_I64;
364 if (RetVT == MVT::i128)
365 return FPTOSINT_F64_I128;
366 } else if (OpVT == MVT::f80) {
367 if (RetVT == MVT::i32)
368 return FPTOSINT_F80_I32;
369 if (RetVT == MVT::i64)
370 return FPTOSINT_F80_I64;
371 if (RetVT == MVT::i128)
372 return FPTOSINT_F80_I128;
373 } else if (OpVT == MVT::f128) {
374 if (RetVT == MVT::i32)
375 return FPTOSINT_F128_I32;
376 if (RetVT == MVT::i64)
377 return FPTOSINT_F128_I64;
378 if (RetVT == MVT::i128)
379 return FPTOSINT_F128_I128;
380 } else if (OpVT == MVT::ppcf128) {
381 if (RetVT == MVT::i32)
382 return FPTOSINT_PPCF128_I32;
383 if (RetVT == MVT::i64)
384 return FPTOSINT_PPCF128_I64;
385 if (RetVT == MVT::i128)
386 return FPTOSINT_PPCF128_I128;
387 }
388 return UNKNOWN_LIBCALL;
389}
390
391/// getFPTOUINT - Return the FPTOUINT_*_* value for the given types, or
392/// UNKNOWN_LIBCALL if there is none.
393RTLIB::Libcall RTLIB::getFPTOUINT(EVT OpVT, EVT RetVT) {
394 if (OpVT == MVT::f16) {
395 if (RetVT == MVT::i32)
396 return FPTOUINT_F16_I32;
397 if (RetVT == MVT::i64)
398 return FPTOUINT_F16_I64;
399 if (RetVT == MVT::i128)
400 return FPTOUINT_F16_I128;
401 } else if (OpVT == MVT::f32) {
402 if (RetVT == MVT::i32)
403 return FPTOUINT_F32_I32;
404 if (RetVT == MVT::i64)
405 return FPTOUINT_F32_I64;
406 if (RetVT == MVT::i128)
407 return FPTOUINT_F32_I128;
408 } else if (OpVT == MVT::f64) {
409 if (RetVT == MVT::i32)
410 return FPTOUINT_F64_I32;
411 if (RetVT == MVT::i64)
412 return FPTOUINT_F64_I64;
413 if (RetVT == MVT::i128)
414 return FPTOUINT_F64_I128;
415 } else if (OpVT == MVT::f80) {
416 if (RetVT == MVT::i32)
417 return FPTOUINT_F80_I32;
418 if (RetVT == MVT::i64)
419 return FPTOUINT_F80_I64;
420 if (RetVT == MVT::i128)
421 return FPTOUINT_F80_I128;
422 } else if (OpVT == MVT::f128) {
423 if (RetVT == MVT::i32)
424 return FPTOUINT_F128_I32;
425 if (RetVT == MVT::i64)
426 return FPTOUINT_F128_I64;
427 if (RetVT == MVT::i128)
428 return FPTOUINT_F128_I128;
429 } else if (OpVT == MVT::ppcf128) {
430 if (RetVT == MVT::i32)
431 return FPTOUINT_PPCF128_I32;
432 if (RetVT == MVT::i64)
433 return FPTOUINT_PPCF128_I64;
434 if (RetVT == MVT::i128)
435 return FPTOUINT_PPCF128_I128;
436 }
437 return UNKNOWN_LIBCALL;
438}
439
440/// getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or
441/// UNKNOWN_LIBCALL if there is none.
442RTLIB::Libcall RTLIB::getSINTTOFP(EVT OpVT, EVT RetVT) {
443 if (OpVT == MVT::i32) {
444 if (RetVT == MVT::f16)
445 return SINTTOFP_I32_F16;
446 if (RetVT == MVT::f32)
447 return SINTTOFP_I32_F32;
448 if (RetVT == MVT::f64)
449 return SINTTOFP_I32_F64;
450 if (RetVT == MVT::f80)
451 return SINTTOFP_I32_F80;
452 if (RetVT == MVT::f128)
453 return SINTTOFP_I32_F128;
454 if (RetVT == MVT::ppcf128)
455 return SINTTOFP_I32_PPCF128;
456 } else if (OpVT == MVT::i64) {
457 if (RetVT == MVT::bf16)
458 return SINTTOFP_I64_BF16;
459 if (RetVT == MVT::f16)
460 return SINTTOFP_I64_F16;
461 if (RetVT == MVT::f32)
462 return SINTTOFP_I64_F32;
463 if (RetVT == MVT::f64)
464 return SINTTOFP_I64_F64;
465 if (RetVT == MVT::f80)
466 return SINTTOFP_I64_F80;
467 if (RetVT == MVT::f128)
468 return SINTTOFP_I64_F128;
469 if (RetVT == MVT::ppcf128)
470 return SINTTOFP_I64_PPCF128;
471 } else if (OpVT == MVT::i128) {
472 if (RetVT == MVT::f16)
473 return SINTTOFP_I128_F16;
474 if (RetVT == MVT::f32)
475 return SINTTOFP_I128_F32;
476 if (RetVT == MVT::f64)
477 return SINTTOFP_I128_F64;
478 if (RetVT == MVT::f80)
479 return SINTTOFP_I128_F80;
480 if (RetVT == MVT::f128)
481 return SINTTOFP_I128_F128;
482 if (RetVT == MVT::ppcf128)
483 return SINTTOFP_I128_PPCF128;
484 }
485 return UNKNOWN_LIBCALL;
486}
487
488/// getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or
489/// UNKNOWN_LIBCALL if there is none.
490RTLIB::Libcall RTLIB::getUINTTOFP(EVT OpVT, EVT RetVT) {
491 if (OpVT == MVT::i32) {
492 if (RetVT == MVT::f16)
493 return UINTTOFP_I32_F16;
494 if (RetVT == MVT::f32)
495 return UINTTOFP_I32_F32;
496 if (RetVT == MVT::f64)
497 return UINTTOFP_I32_F64;
498 if (RetVT == MVT::f80)
499 return UINTTOFP_I32_F80;
500 if (RetVT == MVT::f128)
501 return UINTTOFP_I32_F128;
502 if (RetVT == MVT::ppcf128)
503 return UINTTOFP_I32_PPCF128;
504 } else if (OpVT == MVT::i64) {
505 if (RetVT == MVT::bf16)
506 return UINTTOFP_I64_BF16;
507 if (RetVT == MVT::f16)
508 return UINTTOFP_I64_F16;
509 if (RetVT == MVT::f32)
510 return UINTTOFP_I64_F32;
511 if (RetVT == MVT::f64)
512 return UINTTOFP_I64_F64;
513 if (RetVT == MVT::f80)
514 return UINTTOFP_I64_F80;
515 if (RetVT == MVT::f128)
516 return UINTTOFP_I64_F128;
517 if (RetVT == MVT::ppcf128)
518 return UINTTOFP_I64_PPCF128;
519 } else if (OpVT == MVT::i128) {
520 if (RetVT == MVT::f16)
521 return UINTTOFP_I128_F16;
522 if (RetVT == MVT::f32)
523 return UINTTOFP_I128_F32;
524 if (RetVT == MVT::f64)
525 return UINTTOFP_I128_F64;
526 if (RetVT == MVT::f80)
527 return UINTTOFP_I128_F80;
528 if (RetVT == MVT::f128)
529 return UINTTOFP_I128_F128;
530 if (RetVT == MVT::ppcf128)
531 return UINTTOFP_I128_PPCF128;
532 }
533 return UNKNOWN_LIBCALL;
534}
535
536RTLIB::Libcall RTLIB::getPOWI(EVT RetVT) {
537 return getFPLibCall(VT: RetVT, Call_F32: POWI_F32, Call_F64: POWI_F64, Call_F80: POWI_F80, Call_F128: POWI_F128,
538 Call_PPCF128: POWI_PPCF128);
539}
540
541RTLIB::Libcall RTLIB::getPOW(EVT RetVT) {
542 return getFPLibCall(VT: RetVT, Call_F32: POW_F32, Call_F64: POW_F64, Call_F80: POW_F80, Call_F128: POW_F128, Call_PPCF128: POW_PPCF128);
543}
544
545RTLIB::Libcall RTLIB::getLDEXP(EVT RetVT) {
546 return getFPLibCall(VT: RetVT, Call_F32: LDEXP_F32, Call_F64: LDEXP_F64, Call_F80: LDEXP_F80, Call_F128: LDEXP_F128,
547 Call_PPCF128: LDEXP_PPCF128);
548}
549
550RTLIB::Libcall RTLIB::getFREXP(EVT RetVT) {
551 return getFPLibCall(VT: RetVT, Call_F32: FREXP_F32, Call_F64: FREXP_F64, Call_F80: FREXP_F80, Call_F128: FREXP_F128,
552 Call_PPCF128: FREXP_PPCF128);
553}
554
555RTLIB::Libcall RTLIB::getSIN(EVT RetVT) {
556 return getFPLibCall(VT: RetVT, Call_F32: SIN_F32, Call_F64: SIN_F64, Call_F80: SIN_F80, Call_F128: SIN_F128, Call_PPCF128: SIN_PPCF128);
557}
558
559RTLIB::Libcall RTLIB::getCOS(EVT RetVT) {
560 return getFPLibCall(VT: RetVT, Call_F32: COS_F32, Call_F64: COS_F64, Call_F80: COS_F80, Call_F128: COS_F128, Call_PPCF128: COS_PPCF128);
561}
562
563RTLIB::Libcall RTLIB::getSINCOS(EVT RetVT) {
564 // TODO: Tablegen should generate this function
565 if (RetVT.isVector()) {
566 if (!RetVT.isSimple())
567 return RTLIB::UNKNOWN_LIBCALL;
568 switch (RetVT.getSimpleVT().SimpleTy) {
569 case MVT::v4f32:
570 return RTLIB::SINCOS_V4F32;
571 case MVT::v2f64:
572 return RTLIB::SINCOS_V2F64;
573 case MVT::nxv4f32:
574 return RTLIB::SINCOS_NXV4F32;
575 case MVT::nxv2f64:
576 return RTLIB::SINCOS_NXV2F64;
577 default:
578 return RTLIB::UNKNOWN_LIBCALL;
579 }
580 }
581
582 return getFPLibCall(VT: RetVT, Call_F32: SINCOS_F32, Call_F64: SINCOS_F64, Call_F80: SINCOS_F80, Call_F128: SINCOS_F128,
583 Call_PPCF128: SINCOS_PPCF128);
584}
585
586RTLIB::Libcall RTLIB::getSINCOSPI(EVT RetVT) {
587 // TODO: Tablegen should generate this function
588 if (RetVT.isVector()) {
589 if (!RetVT.isSimple())
590 return RTLIB::UNKNOWN_LIBCALL;
591 switch (RetVT.getSimpleVT().SimpleTy) {
592 case MVT::v4f32:
593 return RTLIB::SINCOSPI_V4F32;
594 case MVT::v2f64:
595 return RTLIB::SINCOSPI_V2F64;
596 case MVT::nxv4f32:
597 return RTLIB::SINCOSPI_NXV4F32;
598 case MVT::nxv2f64:
599 return RTLIB::SINCOSPI_NXV2F64;
600 default:
601 return RTLIB::UNKNOWN_LIBCALL;
602 }
603 }
604
605 return getFPLibCall(VT: RetVT, Call_F32: SINCOSPI_F32, Call_F64: SINCOSPI_F64, Call_F80: SINCOSPI_F80,
606 Call_F128: SINCOSPI_F128, Call_PPCF128: SINCOSPI_PPCF128);
607}
608
609RTLIB::Libcall RTLIB::getSINCOS_STRET(EVT RetVT) {
610 return getFPLibCall(VT: RetVT, Call_F32: SINCOS_STRET_F32, Call_F64: SINCOS_STRET_F64,
611 Call_F80: UNKNOWN_LIBCALL, Call_F128: UNKNOWN_LIBCALL, Call_PPCF128: UNKNOWN_LIBCALL);
612}
613
614RTLIB::Libcall RTLIB::getREM(EVT VT) {
615 // TODO: Tablegen should generate this function
616 if (VT.isVector()) {
617 if (!VT.isSimple())
618 return RTLIB::UNKNOWN_LIBCALL;
619 switch (VT.getSimpleVT().SimpleTy) {
620 case MVT::v4f32:
621 return RTLIB::REM_V4F32;
622 case MVT::v2f64:
623 return RTLIB::REM_V2F64;
624 case MVT::nxv4f32:
625 return RTLIB::REM_NXV4F32;
626 case MVT::nxv2f64:
627 return RTLIB::REM_NXV2F64;
628 default:
629 return RTLIB::UNKNOWN_LIBCALL;
630 }
631 }
632
633 return getFPLibCall(VT, Call_F32: REM_F32, Call_F64: REM_F64, Call_F80: REM_F80, Call_F128: REM_F128, Call_PPCF128: REM_PPCF128);
634}
635
636RTLIB::Libcall RTLIB::getMODF(EVT RetVT) {
637 // TODO: Tablegen should generate this function
638 if (RetVT.isVector()) {
639 if (!RetVT.isSimple())
640 return RTLIB::UNKNOWN_LIBCALL;
641 switch (RetVT.getSimpleVT().SimpleTy) {
642 case MVT::v4f32:
643 return RTLIB::MODF_V4F32;
644 case MVT::v2f64:
645 return RTLIB::MODF_V2F64;
646 case MVT::nxv4f32:
647 return RTLIB::MODF_NXV4F32;
648 case MVT::nxv2f64:
649 return RTLIB::MODF_NXV2F64;
650 default:
651 return RTLIB::UNKNOWN_LIBCALL;
652 }
653 }
654
655 return getFPLibCall(VT: RetVT, Call_F32: MODF_F32, Call_F64: MODF_F64, Call_F80: MODF_F80, Call_F128: MODF_F128,
656 Call_PPCF128: MODF_PPCF128);
657}
658
659RTLIB::Libcall RTLIB::getLROUND(EVT VT) {
660 if (VT == MVT::f32)
661 return RTLIB::LROUND_F32;
662 if (VT == MVT::f64)
663 return RTLIB::LROUND_F64;
664 if (VT == MVT::f80)
665 return RTLIB::LROUND_F80;
666 if (VT == MVT::f128)
667 return RTLIB::LROUND_F128;
668 if (VT == MVT::ppcf128)
669 return RTLIB::LROUND_PPCF128;
670
671 return RTLIB::UNKNOWN_LIBCALL;
672}
673
674RTLIB::Libcall RTLIB::getLLROUND(EVT VT) {
675 if (VT == MVT::f32)
676 return RTLIB::LLROUND_F32;
677 if (VT == MVT::f64)
678 return RTLIB::LLROUND_F64;
679 if (VT == MVT::f80)
680 return RTLIB::LLROUND_F80;
681 if (VT == MVT::f128)
682 return RTLIB::LLROUND_F128;
683 if (VT == MVT::ppcf128)
684 return RTLIB::LLROUND_PPCF128;
685
686 return RTLIB::UNKNOWN_LIBCALL;
687}
688
689RTLIB::Libcall RTLIB::getLRINT(EVT VT) {
690 if (VT == MVT::f32)
691 return RTLIB::LRINT_F32;
692 if (VT == MVT::f64)
693 return RTLIB::LRINT_F64;
694 if (VT == MVT::f80)
695 return RTLIB::LRINT_F80;
696 if (VT == MVT::f128)
697 return RTLIB::LRINT_F128;
698 if (VT == MVT::ppcf128)
699 return RTLIB::LRINT_PPCF128;
700 return RTLIB::UNKNOWN_LIBCALL;
701}
702
703RTLIB::Libcall RTLIB::getLLRINT(EVT VT) {
704 if (VT == MVT::f32)
705 return RTLIB::LLRINT_F32;
706 if (VT == MVT::f64)
707 return RTLIB::LLRINT_F64;
708 if (VT == MVT::f80)
709 return RTLIB::LLRINT_F80;
710 if (VT == MVT::f128)
711 return RTLIB::LLRINT_F128;
712 if (VT == MVT::ppcf128)
713 return RTLIB::LLRINT_PPCF128;
714 return RTLIB::UNKNOWN_LIBCALL;
715}
716
717RTLIB::Libcall RTLIB::getOutlineAtomicHelper(const Libcall (&LC)[5][4],
718 AtomicOrdering Order,
719 uint64_t MemSize) {
720 unsigned ModeN, ModelN;
721 switch (MemSize) {
722 case 1:
723 ModeN = 0;
724 break;
725 case 2:
726 ModeN = 1;
727 break;
728 case 4:
729 ModeN = 2;
730 break;
731 case 8:
732 ModeN = 3;
733 break;
734 case 16:
735 ModeN = 4;
736 break;
737 default:
738 return RTLIB::UNKNOWN_LIBCALL;
739 }
740
741 switch (Order) {
742 case AtomicOrdering::Monotonic:
743 ModelN = 0;
744 break;
745 case AtomicOrdering::Acquire:
746 ModelN = 1;
747 break;
748 case AtomicOrdering::Release:
749 ModelN = 2;
750 break;
751 case AtomicOrdering::AcquireRelease:
752 case AtomicOrdering::SequentiallyConsistent:
753 ModelN = 3;
754 break;
755 default:
756 return UNKNOWN_LIBCALL;
757 }
758
759 return LC[ModeN][ModelN];
760}
761
762RTLIB::Libcall RTLIB::getOUTLINE_ATOMIC(unsigned Opc, AtomicOrdering Order,
763 MVT VT) {
764 if (!VT.isScalarInteger())
765 return UNKNOWN_LIBCALL;
766 uint64_t MemSize = VT.getScalarSizeInBits() / 8;
767
768#define LCALLS(A, B) \
769 { A##B##_RELAX, A##B##_ACQ, A##B##_REL, A##B##_ACQ_REL }
770#define LCALL5(A) \
771 LCALLS(A, 1), LCALLS(A, 2), LCALLS(A, 4), LCALLS(A, 8), LCALLS(A, 16)
772 switch (Opc) {
773 case ISD::ATOMIC_CMP_SWAP: {
774 const Libcall LC[5][4] = {LCALL5(OUTLINE_ATOMIC_CAS)};
775 return getOutlineAtomicHelper(LC, Order, MemSize);
776 }
777 case ISD::ATOMIC_SWAP: {
778 const Libcall LC[5][4] = {LCALL5(OUTLINE_ATOMIC_SWP)};
779 return getOutlineAtomicHelper(LC, Order, MemSize);
780 }
781 case ISD::ATOMIC_LOAD_ADD: {
782 const Libcall LC[5][4] = {LCALL5(OUTLINE_ATOMIC_LDADD)};
783 return getOutlineAtomicHelper(LC, Order, MemSize);
784 }
785 case ISD::ATOMIC_LOAD_OR: {
786 const Libcall LC[5][4] = {LCALL5(OUTLINE_ATOMIC_LDSET)};
787 return getOutlineAtomicHelper(LC, Order, MemSize);
788 }
789 case ISD::ATOMIC_LOAD_CLR: {
790 const Libcall LC[5][4] = {LCALL5(OUTLINE_ATOMIC_LDCLR)};
791 return getOutlineAtomicHelper(LC, Order, MemSize);
792 }
793 case ISD::ATOMIC_LOAD_XOR: {
794 const Libcall LC[5][4] = {LCALL5(OUTLINE_ATOMIC_LDEOR)};
795 return getOutlineAtomicHelper(LC, Order, MemSize);
796 }
797 default:
798 return UNKNOWN_LIBCALL;
799 }
800#undef LCALLS
801#undef LCALL5
802}
803
804RTLIB::Libcall RTLIB::getSYNC(unsigned Opc, MVT VT) {
805#define OP_TO_LIBCALL(Name, Enum) \
806 case Name: \
807 switch (VT.SimpleTy) { \
808 default: \
809 return UNKNOWN_LIBCALL; \
810 case MVT::i8: \
811 return Enum##_1; \
812 case MVT::i16: \
813 return Enum##_2; \
814 case MVT::i32: \
815 return Enum##_4; \
816 case MVT::i64: \
817 return Enum##_8; \
818 case MVT::i128: \
819 return Enum##_16; \
820 }
821
822 switch (Opc) {
823 OP_TO_LIBCALL(ISD::ATOMIC_SWAP, SYNC_LOCK_TEST_AND_SET)
824 OP_TO_LIBCALL(ISD::ATOMIC_CMP_SWAP, SYNC_VAL_COMPARE_AND_SWAP)
825 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_ADD, SYNC_FETCH_AND_ADD)
826 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_SUB, SYNC_FETCH_AND_SUB)
827 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_AND, SYNC_FETCH_AND_AND)
828 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_OR, SYNC_FETCH_AND_OR)
829 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_XOR, SYNC_FETCH_AND_XOR)
830 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_NAND, SYNC_FETCH_AND_NAND)
831 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_MAX, SYNC_FETCH_AND_MAX)
832 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_UMAX, SYNC_FETCH_AND_UMAX)
833 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_MIN, SYNC_FETCH_AND_MIN)
834 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_UMIN, SYNC_FETCH_AND_UMIN)
835 }
836
837#undef OP_TO_LIBCALL
838
839 return UNKNOWN_LIBCALL;
840}
841
842RTLIB::Libcall RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) {
843 switch (ElementSize) {
844 case 1:
845 return MEMCPY_ELEMENT_UNORDERED_ATOMIC_1;
846 case 2:
847 return MEMCPY_ELEMENT_UNORDERED_ATOMIC_2;
848 case 4:
849 return MEMCPY_ELEMENT_UNORDERED_ATOMIC_4;
850 case 8:
851 return MEMCPY_ELEMENT_UNORDERED_ATOMIC_8;
852 case 16:
853 return MEMCPY_ELEMENT_UNORDERED_ATOMIC_16;
854 default:
855 return UNKNOWN_LIBCALL;
856 }
857}
858
859RTLIB::Libcall RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) {
860 switch (ElementSize) {
861 case 1:
862 return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_1;
863 case 2:
864 return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_2;
865 case 4:
866 return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_4;
867 case 8:
868 return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_8;
869 case 16:
870 return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_16;
871 default:
872 return UNKNOWN_LIBCALL;
873 }
874}
875
876RTLIB::Libcall RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) {
877 switch (ElementSize) {
878 case 1:
879 return MEMSET_ELEMENT_UNORDERED_ATOMIC_1;
880 case 2:
881 return MEMSET_ELEMENT_UNORDERED_ATOMIC_2;
882 case 4:
883 return MEMSET_ELEMENT_UNORDERED_ATOMIC_4;
884 case 8:
885 return MEMSET_ELEMENT_UNORDERED_ATOMIC_8;
886 case 16:
887 return MEMSET_ELEMENT_UNORDERED_ATOMIC_16;
888 default:
889 return UNKNOWN_LIBCALL;
890 }
891}
892
893ISD::CondCode TargetLoweringBase::getSoftFloatCmpLibcallPredicate(
894 RTLIB::LibcallImpl Impl) const {
895 switch (Impl) {
896 case RTLIB::impl___aeabi_dcmpeq__une:
897 case RTLIB::impl___aeabi_fcmpeq__une:
898 // Usage in the eq case, so we have to invert the comparison.
899 return ISD::SETEQ;
900 case RTLIB::impl___aeabi_dcmpeq__oeq:
901 case RTLIB::impl___aeabi_fcmpeq__oeq:
902 // Normal comparison to boolean value.
903 return ISD::SETNE;
904 case RTLIB::impl___aeabi_dcmplt:
905 case RTLIB::impl___aeabi_dcmple:
906 case RTLIB::impl___aeabi_dcmpge:
907 case RTLIB::impl___aeabi_dcmpgt:
908 case RTLIB::impl___aeabi_dcmpun:
909 case RTLIB::impl___aeabi_fcmplt:
910 case RTLIB::impl___aeabi_fcmple:
911 case RTLIB::impl___aeabi_fcmpge:
912 case RTLIB::impl___aeabi_fcmpgt:
913 /// The AEABI versions return a typical boolean value, so we can compare
914 /// against the integer result as simply != 0.
915 return ISD::SETNE;
916 default:
917 break;
918 }
919
920 // Assume libgcc/compiler-rt behavior. Most of the cases are really aliases of
921 // each other, and return a 3-way comparison style result of -1, 0, or 1
922 // depending on lt/eq/gt.
923 //
924 // FIXME: It would be cleaner to directly express this as a 3-way comparison
925 // soft FP libcall instead of individual compares.
926 RTLIB::Libcall LC = RTLIB::RuntimeLibcallsInfo::getLibcallFromImpl(Impl);
927 switch (LC) {
928 case RTLIB::OEQ_F32:
929 case RTLIB::OEQ_F64:
930 case RTLIB::OEQ_F128:
931 case RTLIB::OEQ_PPCF128:
932 return ISD::SETEQ;
933 case RTLIB::UNE_F32:
934 case RTLIB::UNE_F64:
935 case RTLIB::UNE_F128:
936 case RTLIB::UNE_PPCF128:
937 return ISD::SETNE;
938 case RTLIB::OGE_F32:
939 case RTLIB::OGE_F64:
940 case RTLIB::OGE_F128:
941 case RTLIB::OGE_PPCF128:
942 return ISD::SETGE;
943 case RTLIB::OLT_F32:
944 case RTLIB::OLT_F64:
945 case RTLIB::OLT_F128:
946 case RTLIB::OLT_PPCF128:
947 return ISD::SETLT;
948 case RTLIB::OLE_F32:
949 case RTLIB::OLE_F64:
950 case RTLIB::OLE_F128:
951 case RTLIB::OLE_PPCF128:
952 return ISD::SETLE;
953 case RTLIB::OGT_F32:
954 case RTLIB::OGT_F64:
955 case RTLIB::OGT_F128:
956 case RTLIB::OGT_PPCF128:
957 return ISD::SETGT;
958 case RTLIB::UO_F32:
959 case RTLIB::UO_F64:
960 case RTLIB::UO_F128:
961 case RTLIB::UO_PPCF128:
962 return ISD::SETNE;
963 default:
964 llvm_unreachable("not a compare libcall");
965 }
966}
967
968/// NOTE: The TargetMachine owns TLOF.
969TargetLoweringBase::TargetLoweringBase(const TargetMachine &tm,
970 const TargetSubtargetInfo &STI)
971 : TM(tm),
972 RuntimeLibcallInfo(TM.getTargetTriple(), TM.Options.ExceptionModel,
973 TM.Options.FloatABIType, TM.Options.EABIVersion,
974 TM.Options.MCOptions.getABIName(), TM.Options.VecLib),
975 Libcalls(RuntimeLibcallInfo, STI) {
976 initActions();
977
978 // Perform these initializations only once.
979 MaxStoresPerMemset = MaxStoresPerMemcpy = MaxStoresPerMemmove =
980 MaxLoadsPerMemcmp = 8;
981 MaxGluedStoresPerMemcpy = 0;
982 MaxStoresPerMemsetOptSize = MaxStoresPerMemcpyOptSize =
983 MaxStoresPerMemmoveOptSize = MaxLoadsPerMemcmpOptSize = 4;
984 HasExtractBitsInsn = false;
985 JumpIsExpensive = JumpIsExpensiveOverride;
986 PredictableSelectIsExpensive = false;
987 EnableExtLdPromotion = false;
988 StackPointerRegisterToSaveRestore = 0;
989 BooleanContents = UndefinedBooleanContent;
990 BooleanFloatContents = UndefinedBooleanContent;
991 BooleanVectorContents = UndefinedBooleanContent;
992 SchedPreferenceInfo = Sched::ILP;
993 GatherAllAliasesMaxDepth = 18;
994 IsStrictFPEnabled = DisableStrictNodeMutation;
995 MaxBytesForAlignment = 0;
996 MaxAtomicSizeInBitsSupported = 0;
997
998 // Assume that even with libcalls, no target supports wider than 128 bit
999 // division.
1000 MaxDivRemBitWidthSupported = 128;
1001
1002 MaxLargeFPConvertBitWidthSupported = 128;
1003
1004 MinCmpXchgSizeInBits = 0;
1005 SupportsUnalignedAtomics = false;
1006
1007 MinimumBitTestCmps = MinimumBitTestCmpsOverride;
1008}
1009
1010// Define the virtual destructor out-of-line to act as a key method to anchor
1011// debug info (see coding standards).
1012TargetLoweringBase::~TargetLoweringBase() = default;
1013
1014void TargetLoweringBase::initActions() {
1015 // All operations default to being supported.
1016 memset(s: OpActions, c: 0, n: sizeof(OpActions));
1017 memset(s: LoadExtActions, c: 0, n: sizeof(LoadExtActions));
1018 memset(s: TruncStoreActions, c: 0, n: sizeof(TruncStoreActions));
1019 memset(s: IndexedModeActions, c: 0, n: sizeof(IndexedModeActions));
1020 memset(s: CondCodeActions, c: 0, n: sizeof(CondCodeActions));
1021 llvm::fill(Range&: RegClassForVT, Value: nullptr);
1022 llvm::fill(Range&: TargetDAGCombineArray, Value: 0);
1023
1024 // Let extending atomic loads be unsupported by default.
1025 for (MVT ValVT : MVT::all_valuetypes())
1026 for (MVT MemVT : MVT::all_valuetypes())
1027 setAtomicLoadExtAction(ExtTypes: {ISD::SEXTLOAD, ISD::ZEXTLOAD}, ValVT, MemVT,
1028 Action: Expand);
1029
1030 // We're somewhat special casing MVT::i2 and MVT::i4. Ideally we want to
1031 // remove this and targets should individually set these types if not legal.
1032 for (ISD::NodeType NT : enum_seq(Begin: ISD::DELETED_NODE, End: ISD::BUILTIN_OP_END,
1033 force_iteration_on_noniterable_enum)) {
1034 for (MVT VT : {MVT::i2, MVT::i4})
1035 OpActions[(unsigned)VT.SimpleTy][NT] = Expand;
1036 }
1037 for (MVT AVT : MVT::all_valuetypes()) {
1038 for (MVT VT : {MVT::i2, MVT::i4, MVT::v128i2, MVT::v64i4}) {
1039 setTruncStoreAction(ValVT: AVT, MemVT: VT, Action: Expand);
1040 setLoadExtAction(ExtType: ISD::EXTLOAD, ValVT: AVT, MemVT: VT, Action: Expand);
1041 setLoadExtAction(ExtType: ISD::ZEXTLOAD, ValVT: AVT, MemVT: VT, Action: Expand);
1042 }
1043 }
1044 for (unsigned IM = (unsigned)ISD::PRE_INC;
1045 IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) {
1046 for (MVT VT : {MVT::i2, MVT::i4}) {
1047 setIndexedLoadAction(IdxModes: IM, VT, Action: Expand);
1048 setIndexedStoreAction(IdxModes: IM, VT, Action: Expand);
1049 setIndexedMaskedLoadAction(IdxMode: IM, VT, Action: Expand);
1050 setIndexedMaskedStoreAction(IdxMode: IM, VT, Action: Expand);
1051 }
1052 }
1053
1054 for (MVT VT : MVT::fp_valuetypes()) {
1055 MVT IntVT = MVT::getIntegerVT(BitWidth: VT.getFixedSizeInBits());
1056 if (IntVT.isValid()) {
1057 setOperationAction(Op: ISD::ATOMIC_SWAP, VT, Action: Promote);
1058 AddPromotedToType(Opc: ISD::ATOMIC_SWAP, OrigVT: VT, DestVT: IntVT);
1059 }
1060 }
1061
1062 // If f16 fma is not natively supported, the value must be promoted to an f64
1063 // (and not to f32!) to prevent double rounding issues.
1064 AddPromotedToType(Opc: ISD::FMA, OrigVT: MVT::f16, DestVT: MVT::f64);
1065 AddPromotedToType(Opc: ISD::STRICT_FMA, OrigVT: MVT::f16, DestVT: MVT::f64);
1066
1067 // Set default actions for various operations.
1068 for (MVT VT : MVT::all_valuetypes()) {
1069 // Default all indexed load / store to expand.
1070 for (unsigned IM = (unsigned)ISD::PRE_INC;
1071 IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) {
1072 setIndexedLoadAction(IdxModes: IM, VT, Action: Expand);
1073 setIndexedStoreAction(IdxModes: IM, VT, Action: Expand);
1074 setIndexedMaskedLoadAction(IdxMode: IM, VT, Action: Expand);
1075 setIndexedMaskedStoreAction(IdxMode: IM, VT, Action: Expand);
1076 }
1077
1078 // Most backends expect to see the node which just returns the value loaded.
1079 setOperationAction(Op: ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Action: Expand);
1080
1081 // These operations default to expand.
1082 setOperationAction(Ops: {ISD::FGETSIGN, ISD::CONCAT_VECTORS,
1083 ISD::FMINNUM, ISD::FMAXNUM,
1084 ISD::FMINNUM_IEEE, ISD::FMAXNUM_IEEE,
1085 ISD::FMINIMUM, ISD::FMAXIMUM,
1086 ISD::FMINIMUMNUM, ISD::FMAXIMUMNUM,
1087 ISD::FMAD, ISD::SMIN,
1088 ISD::SMAX, ISD::UMIN,
1089 ISD::UMAX, ISD::ABS,
1090 ISD::FSHL, ISD::FSHR,
1091 ISD::SADDSAT, ISD::UADDSAT,
1092 ISD::SSUBSAT, ISD::USUBSAT,
1093 ISD::SSHLSAT, ISD::USHLSAT,
1094 ISD::SMULFIX, ISD::SMULFIXSAT,
1095 ISD::UMULFIX, ISD::UMULFIXSAT,
1096 ISD::SDIVFIX, ISD::SDIVFIXSAT,
1097 ISD::UDIVFIX, ISD::UDIVFIXSAT,
1098 ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT,
1099 ISD::IS_FPCLASS, ISD::FCBRT,
1100 ISD::FLOG, ISD::FLOG2,
1101 ISD::FLOG10, ISD::FEXP,
1102 ISD::FEXP2, ISD::FEXP10,
1103 ISD::FFLOOR, ISD::FNEARBYINT,
1104 ISD::FCEIL, ISD::FRINT,
1105 ISD::FTRUNC, ISD::FROUNDEVEN,
1106 ISD::FTAN, ISD::FACOS,
1107 ISD::FASIN, ISD::FATAN,
1108 ISD::FCOSH, ISD::FSINH,
1109 ISD::FTANH, ISD::FATAN2,
1110 ISD::FMULADD},
1111 VT, Action: Expand);
1112
1113 // Overflow operations default to expand
1114 setOperationAction(Ops: {ISD::SADDO, ISD::SSUBO, ISD::UADDO, ISD::USUBO,
1115 ISD::SMULO, ISD::UMULO},
1116 VT, Action: Expand);
1117
1118 // Carry-using overflow operations default to expand.
1119 setOperationAction(Ops: {ISD::UADDO_CARRY, ISD::USUBO_CARRY, ISD::SETCCCARRY,
1120 ISD::SADDO_CARRY, ISD::SSUBO_CARRY},
1121 VT, Action: Expand);
1122
1123 // ADDC/ADDE/SUBC/SUBE default to expand.
1124 setOperationAction(Ops: {ISD::ADDC, ISD::ADDE, ISD::SUBC, ISD::SUBE}, VT,
1125 Action: Expand);
1126
1127 // [US]CMP default to expand
1128 setOperationAction(Ops: {ISD::UCMP, ISD::SCMP}, VT, Action: Expand);
1129
1130 // Halving adds
1131 setOperationAction(
1132 Ops: {ISD::AVGFLOORS, ISD::AVGFLOORU, ISD::AVGCEILS, ISD::AVGCEILU}, VT,
1133 Action: Expand);
1134
1135 // Absolute difference
1136 setOperationAction(Ops: {ISD::ABDS, ISD::ABDU}, VT, Action: Expand);
1137
1138 // Carry-less multiply
1139 setOperationAction(Ops: {ISD::CLMUL, ISD::CLMULR, ISD::CLMULH}, VT, Action: Expand);
1140
1141 // Saturated trunc
1142 setOperationAction(Op: ISD::TRUNCATE_SSAT_S, VT, Action: Expand);
1143 setOperationAction(Op: ISD::TRUNCATE_SSAT_U, VT, Action: Expand);
1144 setOperationAction(Op: ISD::TRUNCATE_USAT_U, VT, Action: Expand);
1145
1146 // These default to Expand so they will be expanded to CTLZ/CTTZ by default.
1147 setOperationAction(Ops: {ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
1148 Action: Expand);
1149 setOperationAction(Op: ISD::CTLS, VT, Action: Expand);
1150
1151 setOperationAction(Ops: {ISD::BITREVERSE, ISD::PARITY}, VT, Action: Expand);
1152
1153 // These library functions default to expand.
1154 setOperationAction(Ops: {ISD::FROUND, ISD::FPOWI, ISD::FLDEXP, ISD::FFREXP,
1155 ISD::FSINCOS, ISD::FSINCOSPI, ISD::FMODF},
1156 VT, Action: Expand);
1157
1158 // These operations default to expand for vector types.
1159 if (VT.isVector())
1160 setOperationAction(Ops: {ISD::FCOPYSIGN, ISD::SIGN_EXTEND_INREG,
1161 ISD::ANY_EXTEND_VECTOR_INREG,
1162 ISD::SIGN_EXTEND_VECTOR_INREG,
1163 ISD::ZERO_EXTEND_VECTOR_INREG, ISD::SPLAT_VECTOR,
1164 ISD::LRINT, ISD::LLRINT, ISD::LROUND, ISD::LLROUND},
1165 VT, Action: Expand);
1166
1167 // Constrained floating-point operations default to expand.
1168#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
1169 setOperationAction(ISD::STRICT_##DAGN, VT, Expand);
1170#include "llvm/IR/ConstrainedOps.def"
1171
1172 // For most targets @llvm.get.dynamic.area.offset just returns 0.
1173 setOperationAction(Op: ISD::GET_DYNAMIC_AREA_OFFSET, VT, Action: Expand);
1174
1175 // Vector reduction default to expand.
1176 setOperationAction(
1177 Ops: {ISD::VECREDUCE_FADD, ISD::VECREDUCE_FMUL, ISD::VECREDUCE_ADD,
1178 ISD::VECREDUCE_MUL, ISD::VECREDUCE_AND, ISD::VECREDUCE_OR,
1179 ISD::VECREDUCE_XOR, ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN,
1180 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN, ISD::VECREDUCE_FMAX,
1181 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAXIMUM, ISD::VECREDUCE_FMINIMUM,
1182 ISD::VECREDUCE_SEQ_FADD, ISD::VECREDUCE_SEQ_FMUL},
1183 VT, Action: Expand);
1184
1185 // Named vector shuffles default to expand.
1186 setOperationAction(Ops: {ISD::VECTOR_SPLICE_LEFT, ISD::VECTOR_SPLICE_RIGHT}, VT,
1187 Action: Expand);
1188
1189 // Only some target support this vector operation. Most need to expand it.
1190 setOperationAction(Op: ISD::VECTOR_COMPRESS, VT, Action: Expand);
1191
1192 // VP operations default to expand.
1193#define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...) \
1194 setOperationAction(ISD::SDOPC, VT, Expand);
1195#include "llvm/IR/VPIntrinsics.def"
1196
1197 // Masked vector extracts default to expand.
1198 setOperationAction(Op: ISD::VECTOR_FIND_LAST_ACTIVE, VT, Action: Expand);
1199
1200 setOperationAction(Op: ISD::LOOP_DEPENDENCE_RAW_MASK, VT, Action: Expand);
1201 setOperationAction(Op: ISD::LOOP_DEPENDENCE_WAR_MASK, VT, Action: Expand);
1202
1203 // FP environment operations default to expand.
1204 setOperationAction(Op: ISD::GET_FPENV, VT, Action: Expand);
1205 setOperationAction(Op: ISD::SET_FPENV, VT, Action: Expand);
1206 setOperationAction(Op: ISD::RESET_FPENV, VT, Action: Expand);
1207
1208 setOperationAction(Op: ISD::MSTORE, VT, Action: Expand);
1209 }
1210
1211 // Most targets ignore the @llvm.prefetch intrinsic.
1212 setOperationAction(Op: ISD::PREFETCH, VT: MVT::Other, Action: Expand);
1213
1214 // Most targets also ignore the @llvm.readcyclecounter intrinsic.
1215 setOperationAction(Op: ISD::READCYCLECOUNTER, VT: MVT::i64, Action: Expand);
1216
1217 // Most targets also ignore the @llvm.readsteadycounter intrinsic.
1218 setOperationAction(Op: ISD::READSTEADYCOUNTER, VT: MVT::i64, Action: Expand);
1219
1220 // ConstantFP nodes default to expand. Targets can either change this to
1221 // Legal, in which case all fp constants are legal, or use isFPImmLegal()
1222 // to optimize expansions for certain constants.
1223 setOperationAction(Ops: ISD::ConstantFP,
1224 VTs: {MVT::bf16, MVT::f16, MVT::f32, MVT::f64, MVT::f80, MVT::f128},
1225 Action: Expand);
1226
1227 // Insert custom handling default for llvm.canonicalize.*.
1228 setOperationAction(Ops: ISD::FCANONICALIZE,
1229 VTs: {MVT::f16, MVT::f32, MVT::f64, MVT::f128}, Action: Expand);
1230
1231 // FIXME: Query RuntimeLibCalls to make the decision.
1232 setOperationAction(Ops: {ISD::LRINT, ISD::LLRINT, ISD::LROUND, ISD::LLROUND},
1233 VTs: {MVT::f32, MVT::f64, MVT::f128}, Action: LibCall);
1234
1235 setOperationAction(Ops: {ISD::FTAN, ISD::FACOS, ISD::FASIN, ISD::FATAN, ISD::FCOSH,
1236 ISD::FSINH, ISD::FTANH, ISD::FATAN2},
1237 VT: MVT::f16, Action: Promote);
1238 // Default ISD::TRAP to expand (which turns it into abort).
1239 setOperationAction(Op: ISD::TRAP, VT: MVT::Other, Action: Expand);
1240
1241 // On most systems, DEBUGTRAP and TRAP have no difference. The "Expand"
1242 // here is to inform DAG Legalizer to replace DEBUGTRAP with TRAP.
1243 setOperationAction(Op: ISD::DEBUGTRAP, VT: MVT::Other, Action: Expand);
1244
1245 setOperationAction(Op: ISD::UBSANTRAP, VT: MVT::Other, Action: Expand);
1246
1247 setOperationAction(Op: ISD::GET_FPENV_MEM, VT: MVT::Other, Action: Expand);
1248 setOperationAction(Op: ISD::SET_FPENV_MEM, VT: MVT::Other, Action: Expand);
1249
1250 for (MVT VT : {MVT::i8, MVT::i16, MVT::i32, MVT::i64}) {
1251 setOperationAction(Op: ISD::GET_FPMODE, VT, Action: Expand);
1252 setOperationAction(Op: ISD::SET_FPMODE, VT, Action: Expand);
1253 }
1254 setOperationAction(Op: ISD::RESET_FPMODE, VT: MVT::Other, Action: Expand);
1255
1256 // This one by default will call __clear_cache unless the target
1257 // wants something different.
1258 setOperationAction(Op: ISD::CLEAR_CACHE, VT: MVT::Other, Action: LibCall);
1259
1260 // By default, STACKADDRESS nodes are expanded like STACKSAVE nodes.
1261 // On SPARC targets, custom lowering is required.
1262 setOperationAction(Op: ISD::STACKADDRESS, VT: MVT::Other, Action: Expand);
1263}
1264
1265MVT TargetLoweringBase::getScalarShiftAmountTy(const DataLayout &DL,
1266 EVT) const {
1267 return MVT::getIntegerVT(BitWidth: DL.getPointerSizeInBits(AS: 0));
1268}
1269
1270EVT TargetLoweringBase::getShiftAmountTy(EVT LHSTy,
1271 const DataLayout &DL) const {
1272 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
1273 if (LHSTy.isVector())
1274 return LHSTy;
1275 MVT ShiftVT = getScalarShiftAmountTy(DL, LHSTy);
1276 // If any possible shift value won't fit in the prefered type, just use
1277 // something safe. Assume it will be legalized when the shift is expanded.
1278 if (ShiftVT.getSizeInBits() < Log2_32_Ceil(Value: LHSTy.getSizeInBits()))
1279 ShiftVT = MVT::i32;
1280 assert(ShiftVT.getSizeInBits() >= Log2_32_Ceil(LHSTy.getSizeInBits()) &&
1281 "ShiftVT is still too small!");
1282 return ShiftVT;
1283}
1284
1285bool TargetLoweringBase::canOpTrap(unsigned Op, EVT VT) const {
1286 assert(isTypeLegal(VT));
1287 switch (Op) {
1288 default:
1289 return false;
1290 case ISD::SDIV:
1291 case ISD::UDIV:
1292 case ISD::SREM:
1293 case ISD::UREM:
1294 return true;
1295 }
1296}
1297
1298bool TargetLoweringBase::isFreeAddrSpaceCast(unsigned SrcAS,
1299 unsigned DestAS) const {
1300 return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1301}
1302
1303unsigned TargetLoweringBase::getBitWidthForCttzElements(
1304 Type *RetTy, ElementCount EC, bool ZeroIsPoison,
1305 const ConstantRange *VScaleRange) const {
1306 // Find the smallest "sensible" element type to use for the expansion.
1307 ConstantRange CR(APInt(64, EC.getKnownMinValue()));
1308 if (EC.isScalable())
1309 CR = CR.umul_sat(Other: *VScaleRange);
1310
1311 if (ZeroIsPoison)
1312 CR = CR.subtract(CI: APInt(64, 1));
1313
1314 unsigned EltWidth = RetTy->getScalarSizeInBits();
1315 EltWidth = std::min(a: EltWidth, b: CR.getActiveBits());
1316 EltWidth = std::max(a: llvm::bit_ceil(Value: EltWidth), b: (unsigned)8);
1317
1318 return EltWidth;
1319}
1320
1321void TargetLoweringBase::setJumpIsExpensive(bool isExpensive) {
1322 // If the command-line option was specified, ignore this request.
1323 if (!JumpIsExpensiveOverride.getNumOccurrences())
1324 JumpIsExpensive = isExpensive;
1325}
1326
1327TargetLoweringBase::LegalizeKind
1328TargetLoweringBase::getTypeConversion(LLVMContext &Context, EVT VT) const {
1329 // If this is a simple type, use the ComputeRegisterProp mechanism.
1330 if (VT.isSimple()) {
1331 MVT SVT = VT.getSimpleVT();
1332 assert((unsigned)SVT.SimpleTy < std::size(TransformToType));
1333 MVT NVT = TransformToType[SVT.SimpleTy];
1334 LegalizeTypeAction LA = ValueTypeActions.getTypeAction(VT: SVT);
1335
1336 assert((LA == TypeLegal || LA == TypeSoftenFloat ||
1337 LA == TypeSoftPromoteHalf ||
1338 (NVT.isVector() ||
1339 ValueTypeActions.getTypeAction(NVT) != TypePromoteInteger)) &&
1340 "Promote may not follow Expand or Promote");
1341
1342 if (LA == TypeSplitVector)
1343 return LegalizeKind(LA, EVT(SVT).getHalfNumVectorElementsVT(Context));
1344 if (LA == TypeScalarizeVector)
1345 return LegalizeKind(LA, SVT.getVectorElementType());
1346 return LegalizeKind(LA, NVT);
1347 }
1348
1349 // Handle Extended Scalar Types.
1350 if (!VT.isVector()) {
1351 assert(VT.isInteger() && "Float types must be simple");
1352 unsigned BitSize = VT.getSizeInBits();
1353 // First promote to a power-of-two size, then expand if necessary.
1354 if (BitSize < 8 || !isPowerOf2_32(Value: BitSize)) {
1355 EVT NVT = VT.getRoundIntegerType(Context);
1356 assert(NVT != VT && "Unable to round integer VT");
1357 LegalizeKind NextStep = getTypeConversion(Context, VT: NVT);
1358 // Avoid multi-step promotion.
1359 if (NextStep.first == TypePromoteInteger)
1360 return NextStep;
1361 // Return rounded integer type.
1362 return LegalizeKind(TypePromoteInteger, NVT);
1363 }
1364
1365 return LegalizeKind(TypeExpandInteger,
1366 EVT::getIntegerVT(Context, BitWidth: VT.getSizeInBits() / 2));
1367 }
1368
1369 // Handle vector types.
1370 ElementCount NumElts = VT.getVectorElementCount();
1371 EVT EltVT = VT.getVectorElementType();
1372
1373 // Vectors with only one element are always scalarized.
1374 if (NumElts.isScalar())
1375 return LegalizeKind(TypeScalarizeVector, EltVT);
1376
1377 // Try to widen vector elements until the element type is a power of two and
1378 // promote it to a legal type later on, for example:
1379 // <3 x i8> -> <4 x i8> -> <4 x i32>
1380 if (EltVT.isInteger()) {
1381 // Vectors with a number of elements that is not a power of two are always
1382 // widened, for example <3 x i8> -> <4 x i8>.
1383 if (!VT.isPow2VectorType()) {
1384 NumElts = NumElts.coefficientNextPowerOf2();
1385 EVT NVT = EVT::getVectorVT(Context, VT: EltVT, EC: NumElts);
1386 return LegalizeKind(TypeWidenVector, NVT);
1387 }
1388
1389 // Examine the element type.
1390 LegalizeKind LK = getTypeConversion(Context, VT: EltVT);
1391
1392 // If type is to be expanded, split the vector.
1393 // <4 x i140> -> <2 x i140>
1394 if (LK.first == TypeExpandInteger) {
1395 if (NumElts.isScalable() && NumElts.getKnownMinValue() == 1)
1396 return LegalizeKind(TypeScalarizeScalableVector, EltVT);
1397 return LegalizeKind(TypeSplitVector,
1398 VT.getHalfNumVectorElementsVT(Context));
1399 }
1400
1401 // Promote the integer element types until a legal vector type is found
1402 // or until the element integer type is too big. If a legal type was not
1403 // found, fallback to the usual mechanism of widening/splitting the
1404 // vector.
1405 EVT OldEltVT = EltVT;
1406 while (true) {
1407 // Increase the bitwidth of the element to the next pow-of-two
1408 // (which is greater than 8 bits).
1409 EltVT = EVT::getIntegerVT(Context, BitWidth: 1 + EltVT.getSizeInBits())
1410 .getRoundIntegerType(Context);
1411
1412 // Stop trying when getting a non-simple element type.
1413 // Note that vector elements may be greater than legal vector element
1414 // types. Example: X86 XMM registers hold 64bit element on 32bit
1415 // systems.
1416 if (!EltVT.isSimple())
1417 break;
1418
1419 // Build a new vector type and check if it is legal.
1420 MVT NVT = MVT::getVectorVT(VT: EltVT.getSimpleVT(), EC: NumElts);
1421 // Found a legal promoted vector type.
1422 if (NVT != MVT() && ValueTypeActions.getTypeAction(VT: NVT) == TypeLegal)
1423 return LegalizeKind(TypePromoteInteger,
1424 EVT::getVectorVT(Context, VT: EltVT, EC: NumElts));
1425 }
1426
1427 // Reset the type to the unexpanded type if we did not find a legal vector
1428 // type with a promoted vector element type.
1429 EltVT = OldEltVT;
1430 }
1431
1432 // Try to widen the vector until a legal type is found.
1433 // If there is no wider legal type, split the vector.
1434 while (true) {
1435 // Round up to the next power of 2.
1436 NumElts = NumElts.coefficientNextPowerOf2();
1437
1438 // If there is no simple vector type with this many elements then there
1439 // cannot be a larger legal vector type. Note that this assumes that
1440 // there are no skipped intermediate vector types in the simple types.
1441 if (!EltVT.isSimple())
1442 break;
1443 MVT LargerVector = MVT::getVectorVT(VT: EltVT.getSimpleVT(), EC: NumElts);
1444 if (LargerVector == MVT())
1445 break;
1446
1447 // If this type is legal then widen the vector.
1448 if (ValueTypeActions.getTypeAction(VT: LargerVector) == TypeLegal)
1449 return LegalizeKind(TypeWidenVector, LargerVector);
1450 }
1451
1452 // Widen odd vectors to next power of two.
1453 if (!VT.isPow2VectorType()) {
1454 EVT NVT = VT.getPow2VectorType(Context);
1455 return LegalizeKind(TypeWidenVector, NVT);
1456 }
1457
1458 if (VT.getVectorElementCount() == ElementCount::getScalable(MinVal: 1))
1459 return LegalizeKind(TypeScalarizeScalableVector, EltVT);
1460
1461 // Vectors with illegal element types are expanded.
1462 EVT NVT = EVT::getVectorVT(Context, VT: EltVT,
1463 EC: VT.getVectorElementCount().divideCoefficientBy(RHS: 2));
1464 return LegalizeKind(TypeSplitVector, NVT);
1465}
1466
1467static unsigned getVectorTypeBreakdownMVT(MVT VT, MVT &IntermediateVT,
1468 unsigned &NumIntermediates,
1469 MVT &RegisterVT,
1470 TargetLoweringBase *TLI) {
1471 // Figure out the right, legal destination reg to copy into.
1472 ElementCount EC = VT.getVectorElementCount();
1473 MVT EltTy = VT.getVectorElementType();
1474
1475 unsigned NumVectorRegs = 1;
1476
1477 // Scalable vectors cannot be scalarized, so splitting or widening is
1478 // required.
1479 if (VT.isScalableVector() && !isPowerOf2_32(Value: EC.getKnownMinValue()))
1480 llvm_unreachable(
1481 "Splitting or widening of non-power-of-2 MVTs is not implemented.");
1482
1483 // FIXME: We don't support non-power-of-2-sized vectors for now.
1484 // Ideally we could break down into LHS/RHS like LegalizeDAG does.
1485 if (!isPowerOf2_32(Value: EC.getKnownMinValue())) {
1486 // Split EC to unit size (scalable property is preserved).
1487 NumVectorRegs = EC.getKnownMinValue();
1488 EC = ElementCount::getFixed(MinVal: 1);
1489 }
1490
1491 // Divide the input until we get to a supported size. This will
1492 // always end up with an EC that represent a scalar or a scalable
1493 // scalar.
1494 while (EC.getKnownMinValue() > 1 &&
1495 !TLI->isTypeLegal(VT: MVT::getVectorVT(VT: EltTy, EC))) {
1496 EC = EC.divideCoefficientBy(RHS: 2);
1497 NumVectorRegs <<= 1;
1498 }
1499
1500 NumIntermediates = NumVectorRegs;
1501
1502 MVT NewVT = MVT::getVectorVT(VT: EltTy, EC);
1503 if (!TLI->isTypeLegal(VT: NewVT))
1504 NewVT = EltTy;
1505 IntermediateVT = NewVT;
1506
1507 unsigned LaneSizeInBits = NewVT.getScalarSizeInBits();
1508
1509 // Convert sizes such as i33 to i64.
1510 LaneSizeInBits = llvm::bit_ceil(Value: LaneSizeInBits);
1511
1512 MVT DestVT = TLI->getRegisterType(VT: NewVT);
1513 RegisterVT = DestVT;
1514 if (EVT(DestVT).bitsLT(VT: NewVT)) // Value is expanded, e.g. i64 -> i16.
1515 return NumVectorRegs * (LaneSizeInBits / DestVT.getScalarSizeInBits());
1516
1517 // Otherwise, promotion or legal types use the same number of registers as
1518 // the vector decimated to the appropriate level.
1519 return NumVectorRegs;
1520}
1521
1522/// isLegalRC - Return true if the value types that can be represented by the
1523/// specified register class are all legal.
1524bool TargetLoweringBase::isLegalRC(const TargetRegisterInfo &TRI,
1525 const TargetRegisterClass &RC) const {
1526 for (const auto *I = TRI.legalclasstypes_begin(RC); *I != MVT::Other; ++I)
1527 if (isTypeLegal(VT: *I))
1528 return true;
1529 return false;
1530}
1531
1532/// Replace/modify any TargetFrameIndex operands with a targte-dependent
1533/// sequence of memory operands that is recognized by PrologEpilogInserter.
1534MachineBasicBlock *
1535TargetLoweringBase::emitPatchPoint(MachineInstr &InitialMI,
1536 MachineBasicBlock *MBB) const {
1537 MachineInstr *MI = &InitialMI;
1538 MachineFunction &MF = *MI->getMF();
1539 MachineFrameInfo &MFI = MF.getFrameInfo();
1540
1541 // We're handling multiple types of operands here:
1542 // PATCHPOINT MetaArgs - live-in, read only, direct
1543 // STATEPOINT Deopt Spill - live-through, read only, indirect
1544 // STATEPOINT Deopt Alloca - live-through, read only, direct
1545 // (We're currently conservative and mark the deopt slots read/write in
1546 // practice.)
1547 // STATEPOINT GC Spill - live-through, read/write, indirect
1548 // STATEPOINT GC Alloca - live-through, read/write, direct
1549 // The live-in vs live-through is handled already (the live through ones are
1550 // all stack slots), but we need to handle the different type of stackmap
1551 // operands and memory effects here.
1552
1553 if (llvm::none_of(Range: MI->operands(),
1554 P: [](MachineOperand &Operand) { return Operand.isFI(); }))
1555 return MBB;
1556
1557 MachineInstrBuilder MIB = BuildMI(MF, MIMD: MI->getDebugLoc(), MCID: MI->getDesc());
1558
1559 // Inherit previous memory operands.
1560 MIB.cloneMemRefs(OtherMI: *MI);
1561
1562 for (unsigned i = 0; i < MI->getNumOperands(); ++i) {
1563 MachineOperand &MO = MI->getOperand(i);
1564 if (!MO.isFI()) {
1565 // Index of Def operand this Use it tied to.
1566 // Since Defs are coming before Uses, if Use is tied, then
1567 // index of Def must be smaller that index of that Use.
1568 // Also, Defs preserve their position in new MI.
1569 unsigned TiedTo = i;
1570 if (MO.isReg() && MO.isTied())
1571 TiedTo = MI->findTiedOperandIdx(OpIdx: i);
1572 MIB.add(MO);
1573 if (TiedTo < i)
1574 MIB->tieOperands(DefIdx: TiedTo, UseIdx: MIB->getNumOperands() - 1);
1575 continue;
1576 }
1577
1578 // foldMemoryOperand builds a new MI after replacing a single FI operand
1579 // with the canonical set of five x86 addressing-mode operands.
1580 int FI = MO.getIndex();
1581
1582 // Add frame index operands recognized by stackmaps.cpp
1583 if (MFI.isStatepointSpillSlotObjectIndex(ObjectIdx: FI)) {
1584 // indirect-mem-ref tag, size, #FI, offset.
1585 // Used for spills inserted by StatepointLowering. This codepath is not
1586 // used for patchpoints/stackmaps at all, for these spilling is done via
1587 // foldMemoryOperand callback only.
1588 assert(MI->getOpcode() == TargetOpcode::STATEPOINT && "sanity");
1589 MIB.addImm(Val: StackMaps::IndirectMemRefOp);
1590 MIB.addImm(Val: MFI.getObjectSize(ObjectIdx: FI));
1591 MIB.add(MO);
1592 MIB.addImm(Val: 0);
1593 } else {
1594 // direct-mem-ref tag, #FI, offset.
1595 // Used by patchpoint, and direct alloca arguments to statepoints
1596 MIB.addImm(Val: StackMaps::DirectMemRefOp);
1597 MIB.add(MO);
1598 MIB.addImm(Val: 0);
1599 }
1600
1601 assert(MIB->mayLoad() && "Folded a stackmap use to a non-load!");
1602
1603 // Add a new memory operand for this FI.
1604 assert(MFI.getObjectOffset(FI) != -1);
1605
1606 // Note: STATEPOINT MMOs are added during SelectionDAG. STACKMAP, and
1607 // PATCHPOINT should be updated to do the same. (TODO)
1608 if (MI->getOpcode() != TargetOpcode::STATEPOINT) {
1609 auto Flags = MachineMemOperand::MOLoad;
1610 MachineMemOperand *MMO = MF.getMachineMemOperand(
1611 PtrInfo: MachinePointerInfo::getFixedStack(MF, FI), F: Flags,
1612 Size: MF.getDataLayout().getPointerSize(), BaseAlignment: MFI.getObjectAlign(ObjectIdx: FI));
1613 MIB->addMemOperand(MF, MO: MMO);
1614 }
1615 }
1616 MBB->insert(I: MachineBasicBlock::iterator(MI), MI: MIB);
1617 MI->eraseFromParent();
1618 return MBB;
1619}
1620
1621/// findRepresentativeClass - Return the largest legal super-reg register class
1622/// of the register class for the specified type and its associated "cost".
1623// This function is in TargetLowering because it uses RegClassForVT which would
1624// need to be moved to TargetRegisterInfo and would necessitate moving
1625// isTypeLegal over as well - a massive change that would just require
1626// TargetLowering having a TargetRegisterInfo class member that it would use.
1627std::pair<const TargetRegisterClass *, uint8_t>
1628TargetLoweringBase::findRepresentativeClass(const TargetRegisterInfo *TRI,
1629 MVT VT) const {
1630 const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
1631 if (!RC)
1632 return std::make_pair(x&: RC, y: 0);
1633
1634 // Compute the set of all super-register classes.
1635 BitVector SuperRegRC(TRI->getNumRegClasses());
1636 for (SuperRegClassIterator RCI(RC, TRI); RCI.isValid(); ++RCI)
1637 SuperRegRC.setBitsInMask(Mask: RCI.getMask());
1638
1639 // Find the first legal register class with the largest spill size.
1640 const TargetRegisterClass *BestRC = RC;
1641 for (unsigned i : SuperRegRC.set_bits()) {
1642 const TargetRegisterClass *SuperRC = TRI->getRegClass(i);
1643 // We want the largest possible spill size.
1644 if (TRI->getSpillSize(RC: *SuperRC) <= TRI->getSpillSize(RC: *BestRC))
1645 continue;
1646 if (!isLegalRC(TRI: *TRI, RC: *SuperRC))
1647 continue;
1648 BestRC = SuperRC;
1649 }
1650 return std::make_pair(x&: BestRC, y: 1);
1651}
1652
1653/// computeRegisterProperties - Once all of the register classes are added,
1654/// this allows us to compute derived properties we expose.
1655void TargetLoweringBase::computeRegisterProperties(
1656 const TargetRegisterInfo *TRI) {
1657 // Everything defaults to needing one register.
1658 for (unsigned i = 0; i != MVT::VALUETYPE_SIZE; ++i) {
1659 NumRegistersForVT[i] = 1;
1660 RegisterTypeForVT[i] = TransformToType[i] = (MVT::SimpleValueType)i;
1661 }
1662 // ...except isVoid, which doesn't need any registers.
1663 NumRegistersForVT[MVT::isVoid] = 0;
1664
1665 // Find the largest integer register class.
1666 unsigned LargestIntReg = MVT::LAST_INTEGER_VALUETYPE;
1667 for (; RegClassForVT[LargestIntReg] == nullptr; --LargestIntReg)
1668 assert(LargestIntReg != MVT::i1 && "No integer registers defined!");
1669
1670 // Every integer value type larger than this largest register takes twice as
1671 // many registers to represent as the previous ValueType.
1672 for (unsigned ExpandedReg = LargestIntReg + 1;
1673 ExpandedReg <= MVT::LAST_INTEGER_VALUETYPE; ++ExpandedReg) {
1674 NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1];
1675 RegisterTypeForVT[ExpandedReg] = (MVT::SimpleValueType)LargestIntReg;
1676 TransformToType[ExpandedReg] = (MVT::SimpleValueType)(ExpandedReg - 1);
1677 ValueTypeActions.setTypeAction(VT: (MVT::SimpleValueType)ExpandedReg,
1678 Action: TypeExpandInteger);
1679 }
1680
1681 // Inspect all of the ValueType's smaller than the largest integer
1682 // register to see which ones need promotion.
1683 unsigned LegalIntReg = LargestIntReg;
1684 for (unsigned IntReg = LargestIntReg - 1;
1685 IntReg >= (unsigned)MVT::i1; --IntReg) {
1686 MVT IVT = (MVT::SimpleValueType)IntReg;
1687 if (isTypeLegal(VT: IVT)) {
1688 LegalIntReg = IntReg;
1689 } else {
1690 RegisterTypeForVT[IntReg] = TransformToType[IntReg] =
1691 (MVT::SimpleValueType)LegalIntReg;
1692 ValueTypeActions.setTypeAction(VT: IVT, Action: TypePromoteInteger);
1693 }
1694 }
1695
1696 // ppcf128 type is really two f64's.
1697 if (!isTypeLegal(VT: MVT::ppcf128)) {
1698 if (isTypeLegal(VT: MVT::f64)) {
1699 NumRegistersForVT[MVT::ppcf128] = 2*NumRegistersForVT[MVT::f64];
1700 RegisterTypeForVT[MVT::ppcf128] = MVT::f64;
1701 TransformToType[MVT::ppcf128] = MVT::f64;
1702 ValueTypeActions.setTypeAction(VT: MVT::ppcf128, Action: TypeExpandFloat);
1703 } else {
1704 NumRegistersForVT[MVT::ppcf128] = NumRegistersForVT[MVT::i128];
1705 RegisterTypeForVT[MVT::ppcf128] = RegisterTypeForVT[MVT::i128];
1706 TransformToType[MVT::ppcf128] = MVT::i128;
1707 ValueTypeActions.setTypeAction(VT: MVT::ppcf128, Action: TypeSoftenFloat);
1708 }
1709 }
1710
1711 // Decide how to handle f128. If the target does not have native f128 support,
1712 // expand it to i128 and we will be generating soft float library calls.
1713 if (!isTypeLegal(VT: MVT::f128)) {
1714 NumRegistersForVT[MVT::f128] = NumRegistersForVT[MVT::i128];
1715 RegisterTypeForVT[MVT::f128] = RegisterTypeForVT[MVT::i128];
1716 TransformToType[MVT::f128] = MVT::i128;
1717 ValueTypeActions.setTypeAction(VT: MVT::f128, Action: TypeSoftenFloat);
1718 }
1719
1720 // Decide how to handle f80. If the target does not have native f80 support,
1721 // expand it to i96 and we will be generating soft float library calls.
1722 if (!isTypeLegal(VT: MVT::f80)) {
1723 NumRegistersForVT[MVT::f80] = 3*NumRegistersForVT[MVT::i32];
1724 RegisterTypeForVT[MVT::f80] = RegisterTypeForVT[MVT::i32];
1725 TransformToType[MVT::f80] = MVT::i32;
1726 ValueTypeActions.setTypeAction(VT: MVT::f80, Action: TypeSoftenFloat);
1727 }
1728
1729 // Decide how to handle f64. If the target does not have native f64 support,
1730 // expand it to i64 and we will be generating soft float library calls.
1731 if (!isTypeLegal(VT: MVT::f64)) {
1732 NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64];
1733 RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64];
1734 TransformToType[MVT::f64] = MVT::i64;
1735 ValueTypeActions.setTypeAction(VT: MVT::f64, Action: TypeSoftenFloat);
1736 }
1737
1738 // Decide how to handle f32. If the target does not have native f32 support,
1739 // expand it to i32 and we will be generating soft float library calls.
1740 if (!isTypeLegal(VT: MVT::f32)) {
1741 NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32];
1742 RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32];
1743 TransformToType[MVT::f32] = MVT::i32;
1744 ValueTypeActions.setTypeAction(VT: MVT::f32, Action: TypeSoftenFloat);
1745 }
1746
1747 // Decide how to handle f16. If the target does not have native f16 support,
1748 // promote it to f32, because there are no f16 library calls (except for
1749 // conversions).
1750 if (!isTypeLegal(VT: MVT::f16)) {
1751 // Allow targets to control how we legalize half.
1752 bool UseFPRegsForHalfType = useFPRegsForHalfType();
1753
1754 if (!UseFPRegsForHalfType) {
1755 NumRegistersForVT[MVT::f16] = NumRegistersForVT[MVT::i16];
1756 RegisterTypeForVT[MVT::f16] = RegisterTypeForVT[MVT::i16];
1757 } else {
1758 NumRegistersForVT[MVT::f16] = NumRegistersForVT[MVT::f32];
1759 RegisterTypeForVT[MVT::f16] = RegisterTypeForVT[MVT::f32];
1760 }
1761 TransformToType[MVT::f16] = MVT::f32;
1762 ValueTypeActions.setTypeAction(VT: MVT::f16, Action: TypeSoftPromoteHalf);
1763 }
1764
1765 // Decide how to handle bf16. If the target does not have native bf16 support,
1766 // promote it to f32, because there are no bf16 library calls (except for
1767 // converting from f32 to bf16).
1768 if (!isTypeLegal(VT: MVT::bf16)) {
1769 NumRegistersForVT[MVT::bf16] = NumRegistersForVT[MVT::f32];
1770 RegisterTypeForVT[MVT::bf16] = RegisterTypeForVT[MVT::f32];
1771 TransformToType[MVT::bf16] = MVT::f32;
1772 ValueTypeActions.setTypeAction(VT: MVT::bf16, Action: TypeSoftPromoteHalf);
1773 }
1774
1775 // Loop over all of the vector value types to see which need transformations.
1776 for (unsigned i = MVT::FIRST_VECTOR_VALUETYPE;
1777 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1778 MVT VT = (MVT::SimpleValueType) i;
1779 if (isTypeLegal(VT))
1780 continue;
1781
1782 MVT EltVT = VT.getVectorElementType();
1783 ElementCount EC = VT.getVectorElementCount();
1784 bool IsLegalWiderType = false;
1785 bool IsScalable = VT.isScalableVector();
1786 LegalizeTypeAction PreferredAction = getPreferredVectorAction(VT);
1787 switch (PreferredAction) {
1788 case TypePromoteInteger: {
1789 MVT::SimpleValueType EndVT = IsScalable ?
1790 MVT::LAST_INTEGER_SCALABLE_VECTOR_VALUETYPE :
1791 MVT::LAST_INTEGER_FIXEDLEN_VECTOR_VALUETYPE;
1792 // Try to promote the elements of integer vectors. If no legal
1793 // promotion was found, fall through to the widen-vector method.
1794 for (unsigned nVT = i + 1;
1795 (MVT::SimpleValueType)nVT <= EndVT; ++nVT) {
1796 MVT SVT = (MVT::SimpleValueType) nVT;
1797 // Promote vectors of integers to vectors with the same number
1798 // of elements, with a wider element type.
1799 if (SVT.getScalarSizeInBits() > EltVT.getFixedSizeInBits() &&
1800 SVT.getVectorElementCount() == EC && isTypeLegal(VT: SVT)) {
1801 TransformToType[i] = SVT;
1802 RegisterTypeForVT[i] = SVT;
1803 NumRegistersForVT[i] = 1;
1804 ValueTypeActions.setTypeAction(VT, Action: TypePromoteInteger);
1805 IsLegalWiderType = true;
1806 break;
1807 }
1808 }
1809 if (IsLegalWiderType)
1810 break;
1811 [[fallthrough]];
1812 }
1813
1814 case TypeWidenVector:
1815 if (isPowerOf2_32(Value: EC.getKnownMinValue())) {
1816 // Try to widen the vector.
1817 for (unsigned nVT = i + 1; nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
1818 MVT SVT = (MVT::SimpleValueType) nVT;
1819 if (SVT.getVectorElementType() == EltVT &&
1820 SVT.isScalableVector() == IsScalable &&
1821 SVT.getVectorElementCount().getKnownMinValue() >
1822 EC.getKnownMinValue() &&
1823 isTypeLegal(VT: SVT)) {
1824 TransformToType[i] = SVT;
1825 RegisterTypeForVT[i] = SVT;
1826 NumRegistersForVT[i] = 1;
1827 ValueTypeActions.setTypeAction(VT, Action: TypeWidenVector);
1828 IsLegalWiderType = true;
1829 break;
1830 }
1831 }
1832 if (IsLegalWiderType)
1833 break;
1834 } else {
1835 // Only widen to the next power of 2 to keep consistency with EVT.
1836 MVT NVT = VT.getPow2VectorType();
1837 if (isTypeLegal(VT: NVT)) {
1838 TransformToType[i] = NVT;
1839 ValueTypeActions.setTypeAction(VT, Action: TypeWidenVector);
1840 RegisterTypeForVT[i] = NVT;
1841 NumRegistersForVT[i] = 1;
1842 break;
1843 }
1844 }
1845 [[fallthrough]];
1846
1847 case TypeSplitVector:
1848 case TypeScalarizeVector: {
1849 MVT IntermediateVT;
1850 MVT RegisterVT;
1851 unsigned NumIntermediates;
1852 unsigned NumRegisters = getVectorTypeBreakdownMVT(VT, IntermediateVT,
1853 NumIntermediates, RegisterVT, TLI: this);
1854 NumRegistersForVT[i] = NumRegisters;
1855 assert(NumRegistersForVT[i] == NumRegisters &&
1856 "NumRegistersForVT size cannot represent NumRegisters!");
1857 RegisterTypeForVT[i] = RegisterVT;
1858
1859 MVT NVT = VT.getPow2VectorType();
1860 if (NVT == VT) {
1861 // Type is already a power of 2. The default action is to split.
1862 TransformToType[i] = MVT::Other;
1863 if (PreferredAction == TypeScalarizeVector)
1864 ValueTypeActions.setTypeAction(VT, Action: TypeScalarizeVector);
1865 else if (PreferredAction == TypeSplitVector)
1866 ValueTypeActions.setTypeAction(VT, Action: TypeSplitVector);
1867 else if (EC.getKnownMinValue() > 1)
1868 ValueTypeActions.setTypeAction(VT, Action: TypeSplitVector);
1869 else
1870 ValueTypeActions.setTypeAction(VT, Action: EC.isScalable()
1871 ? TypeScalarizeScalableVector
1872 : TypeScalarizeVector);
1873 } else {
1874 TransformToType[i] = NVT;
1875 ValueTypeActions.setTypeAction(VT, Action: TypeWidenVector);
1876 }
1877 break;
1878 }
1879 default:
1880 llvm_unreachable("Unknown vector legalization action!");
1881 }
1882 }
1883
1884 // Determine the 'representative' register class for each value type.
1885 // An representative register class is the largest (meaning one which is
1886 // not a sub-register class / subreg register class) legal register class for
1887 // a group of value types. For example, on i386, i8, i16, and i32
1888 // representative would be GR32; while on x86_64 it's GR64.
1889 for (unsigned i = 0; i != MVT::VALUETYPE_SIZE; ++i) {
1890 const TargetRegisterClass* RRC;
1891 uint8_t Cost;
1892 std::tie(args&: RRC, args&: Cost) = findRepresentativeClass(TRI, VT: (MVT::SimpleValueType)i);
1893 RepRegClassForVT[i] = RRC;
1894 RepRegClassCostForVT[i] = Cost;
1895 }
1896}
1897
1898EVT TargetLoweringBase::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1899 EVT VT) const {
1900 assert(!VT.isVector() && "No default SetCC type for vectors!");
1901 return getPointerTy(DL).SimpleTy;
1902}
1903
1904MVT::SimpleValueType TargetLoweringBase::getCmpLibcallReturnType() const {
1905 return MVT::i32; // return the default value
1906}
1907
1908/// getVectorTypeBreakdown - Vector types are broken down into some number of
1909/// legal first class types. For example, MVT::v8f32 maps to 2 MVT::v4f32
1910/// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
1911/// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
1912///
1913/// This method returns the number of registers needed, and the VT for each
1914/// register. It also returns the VT and quantity of the intermediate values
1915/// before they are promoted/expanded.
1916unsigned TargetLoweringBase::getVectorTypeBreakdown(LLVMContext &Context,
1917 EVT VT, EVT &IntermediateVT,
1918 unsigned &NumIntermediates,
1919 MVT &RegisterVT) const {
1920 ElementCount EltCnt = VT.getVectorElementCount();
1921
1922 // If there is a wider vector type with the same element type as this one,
1923 // or a promoted vector type that has the same number of elements which
1924 // are wider, then we should convert to that legal vector type.
1925 // This handles things like <2 x float> -> <4 x float> and
1926 // <4 x i1> -> <4 x i32>.
1927 LegalizeTypeAction TA = getTypeAction(Context, VT);
1928 if (!EltCnt.isScalar() &&
1929 (TA == TypeWidenVector || TA == TypePromoteInteger)) {
1930 EVT RegisterEVT = getTypeToTransformTo(Context, VT);
1931 if (isTypeLegal(VT: RegisterEVT)) {
1932 IntermediateVT = RegisterEVT;
1933 RegisterVT = RegisterEVT.getSimpleVT();
1934 NumIntermediates = 1;
1935 return 1;
1936 }
1937 }
1938
1939 // Figure out the right, legal destination reg to copy into.
1940 EVT EltTy = VT.getVectorElementType();
1941
1942 unsigned NumVectorRegs = 1;
1943
1944 // Scalable vectors cannot be scalarized, so handle the legalisation of the
1945 // types like done elsewhere in SelectionDAG.
1946 if (EltCnt.isScalable()) {
1947 LegalizeKind LK;
1948 EVT PartVT = VT;
1949 do {
1950 // Iterate until we've found a legal (part) type to hold VT.
1951 LK = getTypeConversion(Context, VT: PartVT);
1952 PartVT = LK.second;
1953 } while (LK.first != TypeLegal);
1954
1955 if (!PartVT.isVector()) {
1956 report_fatal_error(
1957 reason: "Don't know how to legalize this scalable vector type");
1958 }
1959
1960 NumIntermediates =
1961 divideCeil(Numerator: VT.getVectorElementCount().getKnownMinValue(),
1962 Denominator: PartVT.getVectorElementCount().getKnownMinValue());
1963 IntermediateVT = PartVT;
1964 RegisterVT = getRegisterType(Context, VT: IntermediateVT);
1965 return NumIntermediates;
1966 }
1967
1968 // FIXME: We don't support non-power-of-2-sized vectors for now. Ideally
1969 // we could break down into LHS/RHS like LegalizeDAG does.
1970 if (!isPowerOf2_32(Value: EltCnt.getKnownMinValue())) {
1971 NumVectorRegs = EltCnt.getKnownMinValue();
1972 EltCnt = ElementCount::getFixed(MinVal: 1);
1973 }
1974
1975 // Divide the input until we get to a supported size. This will always
1976 // end with a scalar if the target doesn't support vectors.
1977 while (EltCnt.getKnownMinValue() > 1 &&
1978 !isTypeLegal(VT: EVT::getVectorVT(Context, VT: EltTy, EC: EltCnt))) {
1979 EltCnt = EltCnt.divideCoefficientBy(RHS: 2);
1980 NumVectorRegs <<= 1;
1981 }
1982
1983 NumIntermediates = NumVectorRegs;
1984
1985 EVT NewVT = EVT::getVectorVT(Context, VT: EltTy, EC: EltCnt);
1986 if (!isTypeLegal(VT: NewVT))
1987 NewVT = EltTy;
1988 IntermediateVT = NewVT;
1989
1990 MVT DestVT = getRegisterType(Context, VT: NewVT);
1991 RegisterVT = DestVT;
1992
1993 if (EVT(DestVT).bitsLT(VT: NewVT)) { // Value is expanded, e.g. i64 -> i16.
1994 TypeSize NewVTSize = NewVT.getSizeInBits();
1995 // Convert sizes such as i33 to i64.
1996 if (!llvm::has_single_bit<uint32_t>(Value: NewVTSize.getKnownMinValue()))
1997 NewVTSize = NewVTSize.coefficientNextPowerOf2();
1998 return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits());
1999 }
2000
2001 // Otherwise, promotion or legal types use the same number of registers as
2002 // the vector decimated to the appropriate level.
2003 return NumVectorRegs;
2004}
2005
2006bool TargetLoweringBase::isSuitableForJumpTable(const SwitchInst *SI,
2007 uint64_t NumCases,
2008 uint64_t Range,
2009 ProfileSummaryInfo *PSI,
2010 BlockFrequencyInfo *BFI) const {
2011 // FIXME: This function check the maximum table size and density, but the
2012 // minimum size is not checked. It would be nice if the minimum size is
2013 // also combined within this function. Currently, the minimum size check is
2014 // performed in findJumpTable() in SelectionDAGBuiler and
2015 // getEstimatedNumberOfCaseClusters() in BasicTTIImpl.
2016 const bool OptForSize =
2017 llvm::shouldOptimizeForSize(BB: SI->getParent(), PSI, BFI);
2018 const unsigned MinDensity = getMinimumJumpTableDensity(OptForSize);
2019 const unsigned MaxJumpTableSize = getMaximumJumpTableSize();
2020
2021 // Check whether the number of cases is small enough and
2022 // the range is dense enough for a jump table.
2023 return (OptForSize || Range <= MaxJumpTableSize) &&
2024 (NumCases * 100 >= Range * MinDensity);
2025}
2026
2027MVT TargetLoweringBase::getPreferredSwitchConditionType(LLVMContext &Context,
2028 EVT ConditionVT) const {
2029 return getRegisterType(Context, VT: ConditionVT);
2030}
2031
2032/// Get the EVTs and ArgFlags collections that represent the legalized return
2033/// type of the given function. This does not require a DAG or a return value,
2034/// and is suitable for use before any DAGs for the function are constructed.
2035/// TODO: Move this out of TargetLowering.cpp.
2036void llvm::GetReturnInfo(CallingConv::ID CC, Type *ReturnType,
2037 AttributeList attr,
2038 SmallVectorImpl<ISD::OutputArg> &Outs,
2039 const TargetLowering &TLI, const DataLayout &DL) {
2040 SmallVector<Type *, 4> Types;
2041 ComputeValueTypes(DL, Ty: ReturnType, Types);
2042 unsigned NumValues = Types.size();
2043 if (NumValues == 0) return;
2044
2045 for (Type *Ty : Types) {
2046 EVT VT = TLI.getValueType(DL, Ty);
2047 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2048
2049 if (attr.hasRetAttr(Kind: Attribute::SExt))
2050 ExtendKind = ISD::SIGN_EXTEND;
2051 else if (attr.hasRetAttr(Kind: Attribute::ZExt))
2052 ExtendKind = ISD::ZERO_EXTEND;
2053
2054 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2055 VT = TLI.getTypeForExtReturn(Context&: ReturnType->getContext(), VT, ExtendKind);
2056
2057 unsigned NumParts =
2058 TLI.getNumRegistersForCallingConv(Context&: ReturnType->getContext(), CC, VT);
2059 MVT PartVT =
2060 TLI.getRegisterTypeForCallingConv(Context&: ReturnType->getContext(), CC, VT);
2061
2062 // 'inreg' on function refers to return value
2063 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2064 if (attr.hasRetAttr(Kind: Attribute::InReg))
2065 Flags.setInReg();
2066
2067 // Propagate extension type if any
2068 if (attr.hasRetAttr(Kind: Attribute::SExt))
2069 Flags.setSExt();
2070 else if (attr.hasRetAttr(Kind: Attribute::ZExt))
2071 Flags.setZExt();
2072
2073 for (unsigned i = 0; i < NumParts; ++i)
2074 Outs.push_back(Elt: ISD::OutputArg(Flags, PartVT, VT, Ty, 0, 0));
2075 }
2076}
2077
2078Align TargetLoweringBase::getByValTypeAlignment(Type *Ty,
2079 const DataLayout &DL) const {
2080 return DL.getABITypeAlign(Ty);
2081}
2082
2083bool TargetLoweringBase::allowsMemoryAccessForAlignment(
2084 LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace,
2085 Align Alignment, MachineMemOperand::Flags Flags, unsigned *Fast) const {
2086 // Check if the specified alignment is sufficient based on the data layout.
2087 // TODO: While using the data layout works in practice, a better solution
2088 // would be to implement this check directly (make this a virtual function).
2089 // For example, the ABI alignment may change based on software platform while
2090 // this function should only be affected by hardware implementation.
2091 Type *Ty = VT.getTypeForEVT(Context);
2092 if (VT.isZeroSized() || Alignment >= DL.getABITypeAlign(Ty)) {
2093 // Assume that an access that meets the ABI-specified alignment is fast.
2094 if (Fast != nullptr)
2095 *Fast = 1;
2096 return true;
2097 }
2098
2099 // This is a misaligned access.
2100 return allowsMisalignedMemoryAccesses(VT, AddrSpace, Alignment, Flags, Fast);
2101}
2102
2103bool TargetLoweringBase::allowsMemoryAccessForAlignment(
2104 LLVMContext &Context, const DataLayout &DL, EVT VT,
2105 const MachineMemOperand &MMO, unsigned *Fast) const {
2106 return allowsMemoryAccessForAlignment(Context, DL, VT, AddrSpace: MMO.getAddrSpace(),
2107 Alignment: MMO.getAlign(), Flags: MMO.getFlags(), Fast);
2108}
2109
2110bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context,
2111 const DataLayout &DL, EVT VT,
2112 unsigned AddrSpace, Align Alignment,
2113 MachineMemOperand::Flags Flags,
2114 unsigned *Fast) const {
2115 return allowsMemoryAccessForAlignment(Context, DL, VT, AddrSpace, Alignment,
2116 Flags, Fast);
2117}
2118
2119bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context,
2120 const DataLayout &DL, EVT VT,
2121 const MachineMemOperand &MMO,
2122 unsigned *Fast) const {
2123 return allowsMemoryAccess(Context, DL, VT, AddrSpace: MMO.getAddrSpace(), Alignment: MMO.getAlign(),
2124 Flags: MMO.getFlags(), Fast);
2125}
2126
2127bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context,
2128 const DataLayout &DL, LLT Ty,
2129 const MachineMemOperand &MMO,
2130 unsigned *Fast) const {
2131 EVT VT = getApproximateEVTForLLT(Ty, Ctx&: Context);
2132 return allowsMemoryAccess(Context, DL, VT, AddrSpace: MMO.getAddrSpace(), Alignment: MMO.getAlign(),
2133 Flags: MMO.getFlags(), Fast);
2134}
2135
2136unsigned TargetLoweringBase::getMaxStoresPerMemset(bool OptSize) const {
2137 if (MaxStoresPerMemsetOverride > 0)
2138 return MaxStoresPerMemsetOverride;
2139
2140 return OptSize ? MaxStoresPerMemsetOptSize : MaxStoresPerMemset;
2141}
2142
2143unsigned TargetLoweringBase::getMaxStoresPerMemcpy(bool OptSize) const {
2144 if (MaxStoresPerMemcpyOverride > 0)
2145 return MaxStoresPerMemcpyOverride;
2146
2147 return OptSize ? MaxStoresPerMemcpyOptSize : MaxStoresPerMemcpy;
2148}
2149
2150unsigned TargetLoweringBase::getMaxStoresPerMemmove(bool OptSize) const {
2151 if (MaxStoresPerMemmoveOverride > 0)
2152 return MaxStoresPerMemmoveOverride;
2153
2154 return OptSize ? MaxStoresPerMemmoveOptSize : MaxStoresPerMemmove;
2155}
2156
2157//===----------------------------------------------------------------------===//
2158// TargetTransformInfo Helpers
2159//===----------------------------------------------------------------------===//
2160
2161int TargetLoweringBase::InstructionOpcodeToISD(unsigned Opcode) const {
2162 enum InstructionOpcodes {
2163#define HANDLE_INST(NUM, OPCODE, CLASS) OPCODE = NUM,
2164#define LAST_OTHER_INST(NUM) InstructionOpcodesCount = NUM
2165#include "llvm/IR/Instruction.def"
2166 };
2167 switch (static_cast<InstructionOpcodes>(Opcode)) {
2168 case Ret: return 0;
2169 case Br: return 0;
2170 case Switch: return 0;
2171 case IndirectBr: return 0;
2172 case Invoke: return 0;
2173 case CallBr: return 0;
2174 case Resume: return 0;
2175 case Unreachable: return 0;
2176 case CleanupRet: return 0;
2177 case CatchRet: return 0;
2178 case CatchPad: return 0;
2179 case CatchSwitch: return 0;
2180 case CleanupPad: return 0;
2181 case FNeg: return ISD::FNEG;
2182 case Add: return ISD::ADD;
2183 case FAdd: return ISD::FADD;
2184 case Sub: return ISD::SUB;
2185 case FSub: return ISD::FSUB;
2186 case Mul: return ISD::MUL;
2187 case FMul: return ISD::FMUL;
2188 case UDiv: return ISD::UDIV;
2189 case SDiv: return ISD::SDIV;
2190 case FDiv: return ISD::FDIV;
2191 case URem: return ISD::UREM;
2192 case SRem: return ISD::SREM;
2193 case FRem: return ISD::FREM;
2194 case Shl: return ISD::SHL;
2195 case LShr: return ISD::SRL;
2196 case AShr: return ISD::SRA;
2197 case And: return ISD::AND;
2198 case Or: return ISD::OR;
2199 case Xor: return ISD::XOR;
2200 case Alloca: return 0;
2201 case Load: return ISD::LOAD;
2202 case Store: return ISD::STORE;
2203 case GetElementPtr: return 0;
2204 case Fence: return 0;
2205 case AtomicCmpXchg: return 0;
2206 case AtomicRMW: return 0;
2207 case Trunc: return ISD::TRUNCATE;
2208 case ZExt: return ISD::ZERO_EXTEND;
2209 case SExt: return ISD::SIGN_EXTEND;
2210 case FPToUI: return ISD::FP_TO_UINT;
2211 case FPToSI: return ISD::FP_TO_SINT;
2212 case UIToFP: return ISD::UINT_TO_FP;
2213 case SIToFP: return ISD::SINT_TO_FP;
2214 case FPTrunc: return ISD::FP_ROUND;
2215 case FPExt: return ISD::FP_EXTEND;
2216 case PtrToAddr: return ISD::BITCAST;
2217 case PtrToInt: return ISD::BITCAST;
2218 case IntToPtr: return ISD::BITCAST;
2219 case BitCast: return ISD::BITCAST;
2220 case AddrSpaceCast: return ISD::ADDRSPACECAST;
2221 case ICmp: return ISD::SETCC;
2222 case FCmp: return ISD::SETCC;
2223 case PHI: return 0;
2224 case Call: return 0;
2225 case Select: return ISD::SELECT;
2226 case UserOp1: return 0;
2227 case UserOp2: return 0;
2228 case VAArg: return 0;
2229 case ExtractElement: return ISD::EXTRACT_VECTOR_ELT;
2230 case InsertElement: return ISD::INSERT_VECTOR_ELT;
2231 case ShuffleVector: return ISD::VECTOR_SHUFFLE;
2232 case ExtractValue: return ISD::MERGE_VALUES;
2233 case InsertValue: return ISD::MERGE_VALUES;
2234 case LandingPad: return 0;
2235 case Freeze: return ISD::FREEZE;
2236 }
2237
2238 llvm_unreachable("Unknown instruction type encountered!");
2239}
2240
2241int TargetLoweringBase::IntrinsicIDToISD(Intrinsic::ID ID) const {
2242 switch (ID) {
2243 case Intrinsic::exp:
2244 return ISD::FEXP;
2245 case Intrinsic::exp2:
2246 return ISD::FEXP2;
2247 case Intrinsic::log:
2248 return ISD::FLOG;
2249 default:
2250 return ISD::DELETED_NODE;
2251 }
2252}
2253
2254Value *
2255TargetLoweringBase::getDefaultSafeStackPointerLocation(IRBuilderBase &IRB,
2256 bool UseTLS) const {
2257 // compiler-rt provides a variable with a magic name. Targets that do not
2258 // link with compiler-rt may also provide such a variable.
2259 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
2260 const char *UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr";
2261 auto UnsafeStackPtr =
2262 dyn_cast_or_null<GlobalVariable>(Val: M->getNamedValue(Name: UnsafeStackPtrVar));
2263
2264 const DataLayout &DL = M->getDataLayout();
2265 PointerType *StackPtrTy = DL.getAllocaPtrType(Ctx&: M->getContext());
2266
2267 if (!UnsafeStackPtr) {
2268 auto TLSModel = UseTLS ?
2269 GlobalValue::InitialExecTLSModel :
2270 GlobalValue::NotThreadLocal;
2271 // The global variable is not defined yet, define it ourselves.
2272 // We use the initial-exec TLS model because we do not support the
2273 // variable living anywhere other than in the main executable.
2274 UnsafeStackPtr = new GlobalVariable(
2275 *M, StackPtrTy, false, GlobalValue::ExternalLinkage, nullptr,
2276 UnsafeStackPtrVar, nullptr, TLSModel);
2277 } else {
2278 // The variable exists, check its type and attributes.
2279 //
2280 // FIXME: Move to IR verifier.
2281 if (UnsafeStackPtr->getValueType() != StackPtrTy)
2282 report_fatal_error(reason: Twine(UnsafeStackPtrVar) + " must have void* type");
2283 if (UseTLS != UnsafeStackPtr->isThreadLocal())
2284 report_fatal_error(reason: Twine(UnsafeStackPtrVar) + " must " +
2285 (UseTLS ? "" : "not ") + "be thread-local");
2286 }
2287 return UnsafeStackPtr;
2288}
2289
2290Value *TargetLoweringBase::getSafeStackPointerLocation(
2291 IRBuilderBase &IRB, const LibcallLoweringInfo &Libcalls) const {
2292 // FIXME: Can this triple check be replaced with SAFESTACK_POINTER_ADDRESS
2293 // being available?
2294 if (!TM.getTargetTriple().isAndroid())
2295 return getDefaultSafeStackPointerLocation(IRB, UseTLS: true);
2296
2297 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
2298 auto *PtrTy = PointerType::getUnqual(C&: M->getContext());
2299
2300 RTLIB::LibcallImpl SafestackPointerAddressImpl =
2301 Libcalls.getLibcallImpl(Call: RTLIB::SAFESTACK_POINTER_ADDRESS);
2302 if (SafestackPointerAddressImpl == RTLIB::Unsupported) {
2303 M->getContext().emitError(
2304 ErrorStr: "no libcall available for safestack pointer address");
2305 return PoisonValue::get(T: PtrTy);
2306 }
2307
2308 // Android provides a libc function to retrieve the address of the current
2309 // thread's unsafe stack pointer.
2310 FunctionCallee Fn =
2311 M->getOrInsertFunction(Name: RTLIB::RuntimeLibcallsInfo::getLibcallImplName(
2312 CallImpl: SafestackPointerAddressImpl),
2313 RetTy: PtrTy);
2314 return IRB.CreateCall(Callee: Fn);
2315}
2316
2317//===----------------------------------------------------------------------===//
2318// Loop Strength Reduction hooks
2319//===----------------------------------------------------------------------===//
2320
2321/// isLegalAddressingMode - Return true if the addressing mode represented
2322/// by AM is legal for this target, for a load/store of the specified type.
2323bool TargetLoweringBase::isLegalAddressingMode(const DataLayout &DL,
2324 const AddrMode &AM, Type *Ty,
2325 unsigned AS, Instruction *I) const {
2326 // The default implementation of this implements a conservative RISCy, r+r and
2327 // r+i addr mode.
2328
2329 // Scalable offsets not supported
2330 if (AM.ScalableOffset)
2331 return false;
2332
2333 // Allows a sign-extended 16-bit immediate field.
2334 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
2335 return false;
2336
2337 // No global is ever allowed as a base.
2338 if (AM.BaseGV)
2339 return false;
2340
2341 // Only support r+r,
2342 switch (AM.Scale) {
2343 case 0: // "r+i" or just "i", depending on HasBaseReg.
2344 break;
2345 case 1:
2346 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
2347 return false;
2348 // Otherwise we have r+r or r+i.
2349 break;
2350 case 2:
2351 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
2352 return false;
2353 // Allow 2*r as r+r.
2354 break;
2355 default: // Don't allow n * r
2356 return false;
2357 }
2358
2359 return true;
2360}
2361
2362//===----------------------------------------------------------------------===//
2363// Stack Protector
2364//===----------------------------------------------------------------------===//
2365
2366// For OpenBSD return its special guard variable. Otherwise return nullptr,
2367// so that SelectionDAG handle SSP.
2368Value *
2369TargetLoweringBase::getIRStackGuard(IRBuilderBase &IRB,
2370 const LibcallLoweringInfo &Libcalls) const {
2371 RTLIB::LibcallImpl GuardLocalImpl =
2372 Libcalls.getLibcallImpl(Call: RTLIB::STACK_CHECK_GUARD);
2373 if (GuardLocalImpl != RTLIB::impl___guard_local)
2374 return nullptr;
2375
2376 Module &M = *IRB.GetInsertBlock()->getParent()->getParent();
2377 const DataLayout &DL = M.getDataLayout();
2378 PointerType *PtrTy =
2379 PointerType::get(C&: M.getContext(), AddressSpace: DL.getDefaultGlobalsAddressSpace());
2380 GlobalVariable *G =
2381 M.getOrInsertGlobal(Name: getLibcallImplName(Call: GuardLocalImpl), Ty: PtrTy);
2382 G->setVisibility(GlobalValue::HiddenVisibility);
2383 return G;
2384}
2385
2386// Currently only support "standard" __stack_chk_guard.
2387// TODO: add LOAD_STACK_GUARD support.
2388void TargetLoweringBase::insertSSPDeclarations(
2389 Module &M, const LibcallLoweringInfo &Libcalls) const {
2390 RTLIB::LibcallImpl StackGuardImpl =
2391 Libcalls.getLibcallImpl(Call: RTLIB::STACK_CHECK_GUARD);
2392 if (StackGuardImpl == RTLIB::Unsupported)
2393 return;
2394
2395 StringRef StackGuardVarName = getLibcallImplName(Call: StackGuardImpl);
2396 M.getOrInsertGlobal(
2397 Name: StackGuardVarName, Ty: PointerType::getUnqual(C&: M.getContext()), CreateGlobalCallback: [=, &M]() {
2398 auto *GV = new GlobalVariable(M, PointerType::getUnqual(C&: M.getContext()),
2399 false, GlobalVariable::ExternalLinkage,
2400 nullptr, StackGuardVarName);
2401
2402 // FreeBSD has "__stack_chk_guard" defined externally on libc.so
2403 if (M.getDirectAccessExternalData() &&
2404 !TM.getTargetTriple().isOSCygMing() &&
2405 !(TM.getTargetTriple().isPPC64() &&
2406 TM.getTargetTriple().isOSFreeBSD()) &&
2407 (!TM.getTargetTriple().isOSDarwin() ||
2408 TM.getRelocationModel() == Reloc::Static))
2409 GV->setDSOLocal(true);
2410
2411 return GV;
2412 });
2413}
2414
2415// Currently only support "standard" __stack_chk_guard.
2416// TODO: add LOAD_STACK_GUARD support.
2417Value *TargetLoweringBase::getSDagStackGuard(
2418 const Module &M, const LibcallLoweringInfo &Libcalls) const {
2419 RTLIB::LibcallImpl GuardVarImpl =
2420 Libcalls.getLibcallImpl(Call: RTLIB::STACK_CHECK_GUARD);
2421 if (GuardVarImpl == RTLIB::Unsupported)
2422 return nullptr;
2423 return M.getNamedValue(Name: getLibcallImplName(Call: GuardVarImpl));
2424}
2425
2426Function *TargetLoweringBase::getSSPStackGuardCheck(
2427 const Module &M, const LibcallLoweringInfo &Libcalls) const {
2428 // MSVC CRT has a function to validate security cookie.
2429 RTLIB::LibcallImpl SecurityCheckCookieLibcall =
2430 Libcalls.getLibcallImpl(Call: RTLIB::SECURITY_CHECK_COOKIE);
2431 if (SecurityCheckCookieLibcall != RTLIB::Unsupported)
2432 return M.getFunction(Name: getLibcallImplName(Call: SecurityCheckCookieLibcall));
2433 return nullptr;
2434}
2435
2436unsigned TargetLoweringBase::getMinimumJumpTableEntries() const {
2437 return MinimumJumpTableEntries;
2438}
2439
2440void TargetLoweringBase::setMinimumJumpTableEntries(unsigned Val) {
2441 MinimumJumpTableEntries = Val;
2442}
2443
2444unsigned TargetLoweringBase::getMinimumJumpTableDensity(bool OptForSize) const {
2445 return OptForSize ? OptsizeJumpTableDensity : JumpTableDensity;
2446}
2447
2448unsigned TargetLoweringBase::getMaximumJumpTableSize() const {
2449 return MaximumJumpTableSize;
2450}
2451
2452void TargetLoweringBase::setMaximumJumpTableSize(unsigned Val) {
2453 MaximumJumpTableSize = Val;
2454}
2455
2456bool TargetLoweringBase::isJumpTableRelative() const {
2457 return getTargetMachine().isPositionIndependent();
2458}
2459
2460unsigned TargetLoweringBase::getMinimumBitTestCmps() const {
2461 return MinimumBitTestCmps;
2462}
2463
2464void TargetLoweringBase::setMinimumBitTestCmps(unsigned Val) {
2465 MinimumBitTestCmps = Val;
2466}
2467
2468Align TargetLoweringBase::getPrefLoopAlignment(MachineLoop *ML) const {
2469 if (TM.Options.LoopAlignment)
2470 return Align(TM.Options.LoopAlignment);
2471 return PrefLoopAlignment;
2472}
2473
2474unsigned TargetLoweringBase::getMaxPermittedBytesForAlignment(
2475 MachineBasicBlock *MBB) const {
2476 return MaxBytesForAlignment;
2477}
2478
2479//===----------------------------------------------------------------------===//
2480// Reciprocal Estimates
2481//===----------------------------------------------------------------------===//
2482
2483/// Get the reciprocal estimate attribute string for a function that will
2484/// override the target defaults.
2485static StringRef getRecipEstimateForFunc(MachineFunction &MF) {
2486 const Function &F = MF.getFunction();
2487 return F.getFnAttribute(Kind: "reciprocal-estimates").getValueAsString();
2488}
2489
2490/// Construct a string for the given reciprocal operation of the given type.
2491/// This string should match the corresponding option to the front-end's
2492/// "-mrecip" flag assuming those strings have been passed through in an
2493/// attribute string. For example, "vec-divf" for a division of a vXf32.
2494static std::string getReciprocalOpName(bool IsSqrt, EVT VT) {
2495 std::string Name = VT.isVector() ? "vec-" : "";
2496
2497 Name += IsSqrt ? "sqrt" : "div";
2498
2499 // TODO: Handle other float types?
2500 if (VT.getScalarType() == MVT::f64) {
2501 Name += "d";
2502 } else if (VT.getScalarType() == MVT::f16) {
2503 Name += "h";
2504 } else {
2505 assert(VT.getScalarType() == MVT::f32 &&
2506 "Unexpected FP type for reciprocal estimate");
2507 Name += "f";
2508 }
2509
2510 return Name;
2511}
2512
2513/// Return the character position and value (a single numeric character) of a
2514/// customized refinement operation in the input string if it exists. Return
2515/// false if there is no customized refinement step count.
2516static bool parseRefinementStep(StringRef In, size_t &Position,
2517 uint8_t &Value) {
2518 const char RefStepToken = ':';
2519 Position = In.find(C: RefStepToken);
2520 if (Position == StringRef::npos)
2521 return false;
2522
2523 StringRef RefStepString = In.substr(Start: Position + 1);
2524 // Allow exactly one numeric character for the additional refinement
2525 // step parameter.
2526 if (RefStepString.size() == 1) {
2527 char RefStepChar = RefStepString[0];
2528 if (isDigit(C: RefStepChar)) {
2529 Value = RefStepChar - '0';
2530 return true;
2531 }
2532 }
2533 report_fatal_error(reason: "Invalid refinement step for -recip.");
2534}
2535
2536/// For the input attribute string, return one of the ReciprocalEstimate enum
2537/// status values (enabled, disabled, or not specified) for this operation on
2538/// the specified data type.
2539static int getOpEnabled(bool IsSqrt, EVT VT, StringRef Override) {
2540 if (Override.empty())
2541 return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2542
2543 SmallVector<StringRef, 4> OverrideVector;
2544 Override.split(A&: OverrideVector, Separator: ',');
2545 unsigned NumArgs = OverrideVector.size();
2546
2547 // Check if "all", "none", or "default" was specified.
2548 if (NumArgs == 1) {
2549 // Look for an optional setting of the number of refinement steps needed
2550 // for this type of reciprocal operation.
2551 size_t RefPos;
2552 uint8_t RefSteps;
2553 if (parseRefinementStep(In: Override, Position&: RefPos, Value&: RefSteps)) {
2554 // Split the string for further processing.
2555 Override = Override.substr(Start: 0, N: RefPos);
2556 }
2557
2558 // All reciprocal types are enabled.
2559 if (Override == "all")
2560 return TargetLoweringBase::ReciprocalEstimate::Enabled;
2561
2562 // All reciprocal types are disabled.
2563 if (Override == "none")
2564 return TargetLoweringBase::ReciprocalEstimate::Disabled;
2565
2566 // Target defaults for enablement are used.
2567 if (Override == "default")
2568 return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2569 }
2570
2571 // The attribute string may omit the size suffix ('f'/'d').
2572 std::string VTName = getReciprocalOpName(IsSqrt, VT);
2573 std::string VTNameNoSize = VTName;
2574 VTNameNoSize.pop_back();
2575 static const char DisabledPrefix = '!';
2576
2577 for (StringRef RecipType : OverrideVector) {
2578 size_t RefPos;
2579 uint8_t RefSteps;
2580 if (parseRefinementStep(In: RecipType, Position&: RefPos, Value&: RefSteps))
2581 RecipType = RecipType.substr(Start: 0, N: RefPos);
2582
2583 // Ignore the disablement token for string matching.
2584 bool IsDisabled = RecipType[0] == DisabledPrefix;
2585 if (IsDisabled)
2586 RecipType = RecipType.substr(Start: 1);
2587
2588 if (RecipType == VTName || RecipType == VTNameNoSize)
2589 return IsDisabled ? TargetLoweringBase::ReciprocalEstimate::Disabled
2590 : TargetLoweringBase::ReciprocalEstimate::Enabled;
2591 }
2592
2593 return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2594}
2595
2596/// For the input attribute string, return the customized refinement step count
2597/// for this operation on the specified data type. If the step count does not
2598/// exist, return the ReciprocalEstimate enum value for unspecified.
2599static int getOpRefinementSteps(bool IsSqrt, EVT VT, StringRef Override) {
2600 if (Override.empty())
2601 return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2602
2603 SmallVector<StringRef, 4> OverrideVector;
2604 Override.split(A&: OverrideVector, Separator: ',');
2605 unsigned NumArgs = OverrideVector.size();
2606
2607 // Check if "all", "default", or "none" was specified.
2608 if (NumArgs == 1) {
2609 // Look for an optional setting of the number of refinement steps needed
2610 // for this type of reciprocal operation.
2611 size_t RefPos;
2612 uint8_t RefSteps;
2613 if (!parseRefinementStep(In: Override, Position&: RefPos, Value&: RefSteps))
2614 return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2615
2616 // Split the string for further processing.
2617 Override = Override.substr(Start: 0, N: RefPos);
2618 assert(Override != "none" &&
2619 "Disabled reciprocals, but specifed refinement steps?");
2620
2621 // If this is a general override, return the specified number of steps.
2622 if (Override == "all" || Override == "default")
2623 return RefSteps;
2624 }
2625
2626 // The attribute string may omit the size suffix ('f'/'d').
2627 std::string VTName = getReciprocalOpName(IsSqrt, VT);
2628 std::string VTNameNoSize = VTName;
2629 VTNameNoSize.pop_back();
2630
2631 for (StringRef RecipType : OverrideVector) {
2632 size_t RefPos;
2633 uint8_t RefSteps;
2634 if (!parseRefinementStep(In: RecipType, Position&: RefPos, Value&: RefSteps))
2635 continue;
2636
2637 RecipType = RecipType.substr(Start: 0, N: RefPos);
2638 if (RecipType == VTName || RecipType == VTNameNoSize)
2639 return RefSteps;
2640 }
2641
2642 return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2643}
2644
2645int TargetLoweringBase::getRecipEstimateSqrtEnabled(EVT VT,
2646 MachineFunction &MF) const {
2647 return getOpEnabled(IsSqrt: true, VT, Override: getRecipEstimateForFunc(MF));
2648}
2649
2650int TargetLoweringBase::getRecipEstimateDivEnabled(EVT VT,
2651 MachineFunction &MF) const {
2652 return getOpEnabled(IsSqrt: false, VT, Override: getRecipEstimateForFunc(MF));
2653}
2654
2655int TargetLoweringBase::getSqrtRefinementSteps(EVT VT,
2656 MachineFunction &MF) const {
2657 return getOpRefinementSteps(IsSqrt: true, VT, Override: getRecipEstimateForFunc(MF));
2658}
2659
2660int TargetLoweringBase::getDivRefinementSteps(EVT VT,
2661 MachineFunction &MF) const {
2662 return getOpRefinementSteps(IsSqrt: false, VT, Override: getRecipEstimateForFunc(MF));
2663}
2664
2665bool TargetLoweringBase::isLoadBitCastBeneficial(
2666 EVT LoadVT, EVT BitcastVT, const SelectionDAG &DAG,
2667 const MachineMemOperand &MMO) const {
2668 // Single-element vectors are scalarized, so we should generally avoid having
2669 // any memory operations on such types, as they would get scalarized too.
2670 if (LoadVT.isFixedLengthVector() && BitcastVT.isFixedLengthVector() &&
2671 BitcastVT.getVectorNumElements() == 1)
2672 return false;
2673
2674 // Don't do if we could do an indexed load on the original type, but not on
2675 // the new one.
2676 if (!LoadVT.isSimple() || !BitcastVT.isSimple())
2677 return true;
2678
2679 MVT LoadMVT = LoadVT.getSimpleVT();
2680
2681 // Don't bother doing this if it's just going to be promoted again later, as
2682 // doing so might interfere with other combines.
2683 if (getOperationAction(Op: ISD::LOAD, VT: LoadMVT) == Promote &&
2684 getTypeToPromoteTo(Op: ISD::LOAD, VT: LoadMVT) == BitcastVT.getSimpleVT())
2685 return false;
2686
2687 unsigned Fast = 0;
2688 return allowsMemoryAccess(Context&: *DAG.getContext(), DL: DAG.getDataLayout(), VT: BitcastVT,
2689 MMO, Fast: &Fast) &&
2690 Fast;
2691}
2692
2693void TargetLoweringBase::finalizeLowering(MachineFunction &MF) const {
2694 MF.getRegInfo().freezeReservedRegs();
2695}
2696
2697MachineMemOperand::Flags TargetLoweringBase::getLoadMemOperandFlags(
2698 const LoadInst &LI, const DataLayout &DL, AssumptionCache *AC,
2699 const TargetLibraryInfo *LibInfo) const {
2700 MachineMemOperand::Flags Flags = MachineMemOperand::MOLoad;
2701 if (LI.isVolatile())
2702 Flags |= MachineMemOperand::MOVolatile;
2703
2704 if (LI.hasMetadata(KindID: LLVMContext::MD_nontemporal))
2705 Flags |= MachineMemOperand::MONonTemporal;
2706
2707 if (LI.hasMetadata(KindID: LLVMContext::MD_invariant_load))
2708 Flags |= MachineMemOperand::MOInvariant;
2709
2710 if (isDereferenceableAndAlignedPointer(V: LI.getPointerOperand(), Ty: LI.getType(),
2711 Alignment: LI.getAlign(), DL, CtxI: &LI, AC,
2712 /*DT=*/nullptr, TLI: LibInfo))
2713 Flags |= MachineMemOperand::MODereferenceable;
2714
2715 Flags |= getTargetMMOFlags(I: LI);
2716 return Flags;
2717}
2718
2719MachineMemOperand::Flags
2720TargetLoweringBase::getStoreMemOperandFlags(const StoreInst &SI,
2721 const DataLayout &DL) const {
2722 MachineMemOperand::Flags Flags = MachineMemOperand::MOStore;
2723
2724 if (SI.isVolatile())
2725 Flags |= MachineMemOperand::MOVolatile;
2726
2727 if (SI.hasMetadata(KindID: LLVMContext::MD_nontemporal))
2728 Flags |= MachineMemOperand::MONonTemporal;
2729
2730 // FIXME: Not preserving dereferenceable
2731 Flags |= getTargetMMOFlags(I: SI);
2732 return Flags;
2733}
2734
2735MachineMemOperand::Flags
2736TargetLoweringBase::getAtomicMemOperandFlags(const Instruction &AI,
2737 const DataLayout &DL) const {
2738 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
2739
2740 if (const AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Val: &AI)) {
2741 if (RMW->isVolatile())
2742 Flags |= MachineMemOperand::MOVolatile;
2743 } else if (const AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Val: &AI)) {
2744 if (CmpX->isVolatile())
2745 Flags |= MachineMemOperand::MOVolatile;
2746 } else
2747 llvm_unreachable("not an atomic instruction");
2748
2749 // FIXME: Not preserving dereferenceable
2750 Flags |= getTargetMMOFlags(I: AI);
2751 return Flags;
2752}
2753
2754MachineMemOperand::Flags TargetLoweringBase::getVPIntrinsicMemOperandFlags(
2755 const VPIntrinsic &VPIntrin) const {
2756 MachineMemOperand::Flags Flags = MachineMemOperand::MONone;
2757 Intrinsic::ID IntrinID = VPIntrin.getIntrinsicID();
2758
2759 switch (IntrinID) {
2760 default:
2761 llvm_unreachable("unexpected intrinsic. Existing code may be appropriate "
2762 "for it, but support must be explicitly enabled");
2763 case Intrinsic::vp_load:
2764 case Intrinsic::vp_gather:
2765 case Intrinsic::experimental_vp_strided_load:
2766 Flags = MachineMemOperand::MOLoad;
2767 break;
2768 case Intrinsic::vp_store:
2769 case Intrinsic::vp_scatter:
2770 case Intrinsic::experimental_vp_strided_store:
2771 Flags = MachineMemOperand::MOStore;
2772 break;
2773 }
2774
2775 if (VPIntrin.hasMetadata(KindID: LLVMContext::MD_nontemporal))
2776 Flags |= MachineMemOperand::MONonTemporal;
2777
2778 Flags |= getTargetMMOFlags(I: VPIntrin);
2779 return Flags;
2780}
2781
2782Instruction *TargetLoweringBase::emitLeadingFence(IRBuilderBase &Builder,
2783 Instruction *Inst,
2784 AtomicOrdering Ord) const {
2785 if (isReleaseOrStronger(AO: Ord) && Inst->hasAtomicStore())
2786 return Builder.CreateFence(Ordering: Ord);
2787 else
2788 return nullptr;
2789}
2790
2791Instruction *TargetLoweringBase::emitTrailingFence(IRBuilderBase &Builder,
2792 Instruction *Inst,
2793 AtomicOrdering Ord) const {
2794 if (isAcquireOrStronger(AO: Ord))
2795 return Builder.CreateFence(Ordering: Ord);
2796 else
2797 return nullptr;
2798}
2799
2800//===----------------------------------------------------------------------===//
2801// GlobalISel Hooks
2802//===----------------------------------------------------------------------===//
2803
2804bool TargetLoweringBase::shouldLocalize(const MachineInstr &MI,
2805 const TargetTransformInfo *TTI) const {
2806 auto &MF = *MI.getMF();
2807 auto &MRI = MF.getRegInfo();
2808 // Assuming a spill and reload of a value has a cost of 1 instruction each,
2809 // this helper function computes the maximum number of uses we should consider
2810 // for remat. E.g. on arm64 global addresses take 2 insts to materialize. We
2811 // break even in terms of code size when the original MI has 2 users vs
2812 // choosing to potentially spill. Any more than 2 users we we have a net code
2813 // size increase. This doesn't take into account register pressure though.
2814 auto maxUses = [](unsigned RematCost) {
2815 // A cost of 1 means remats are basically free.
2816 if (RematCost == 1)
2817 return std::numeric_limits<unsigned>::max();
2818 if (RematCost == 2)
2819 return 2U;
2820
2821 // Remat is too expensive, only sink if there's one user.
2822 if (RematCost > 2)
2823 return 1U;
2824 llvm_unreachable("Unexpected remat cost");
2825 };
2826
2827 switch (MI.getOpcode()) {
2828 default:
2829 return false;
2830 // Constants-like instructions should be close to their users.
2831 // We don't want long live-ranges for them.
2832 case TargetOpcode::G_CONSTANT:
2833 case TargetOpcode::G_FCONSTANT:
2834 case TargetOpcode::G_FRAME_INDEX:
2835 case TargetOpcode::G_INTTOPTR:
2836 return true;
2837 case TargetOpcode::G_GLOBAL_VALUE: {
2838 unsigned RematCost = TTI->getGISelRematGlobalCost();
2839 Register Reg = MI.getOperand(i: 0).getReg();
2840 unsigned MaxUses = maxUses(RematCost);
2841 if (MaxUses == UINT_MAX)
2842 return true; // Remats are "free" so always localize.
2843 return MRI.hasAtMostUserInstrs(Reg, MaxUsers: MaxUses);
2844 }
2845 }
2846}
2847