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