xref: /llvm-project/llvm/lib/CodeGen/TargetLoweringBase.cpp (revision c3260c65e86ac363aa3a39f084db66a8a1d1af7d)
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(
777         {ISD::FROUND, ISD::FPOWI, ISD::FLDEXP, ISD::FFREXP, ISD::FSINCOS}, VT,
778         Expand);
779 
780     // These operations default to expand for vector types.
781     if (VT.isVector())
782       setOperationAction(
783           {ISD::FCOPYSIGN, ISD::SIGN_EXTEND_INREG, ISD::ANY_EXTEND_VECTOR_INREG,
784            ISD::SIGN_EXTEND_VECTOR_INREG, ISD::ZERO_EXTEND_VECTOR_INREG,
785            ISD::SPLAT_VECTOR, ISD::LRINT, ISD::LLRINT, ISD::LROUND,
786            ISD::LLROUND, ISD::FTAN, ISD::FACOS, ISD::FASIN, ISD::FATAN,
787            ISD::FCOSH, ISD::FSINH, ISD::FTANH, ISD::FATAN2},
788           VT, Expand);
789 
790       // Constrained floating-point operations default to expand.
791 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
792     setOperationAction(ISD::STRICT_##DAGN, VT, Expand);
793 #include "llvm/IR/ConstrainedOps.def"
794 
795     // For most targets @llvm.get.dynamic.area.offset just returns 0.
796     setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, VT, Expand);
797 
798     // Vector reduction default to expand.
799     setOperationAction(
800         {ISD::VECREDUCE_FADD, ISD::VECREDUCE_FMUL, ISD::VECREDUCE_ADD,
801          ISD::VECREDUCE_MUL, ISD::VECREDUCE_AND, ISD::VECREDUCE_OR,
802          ISD::VECREDUCE_XOR, ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN,
803          ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN, ISD::VECREDUCE_FMAX,
804          ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAXIMUM, ISD::VECREDUCE_FMINIMUM,
805          ISD::VECREDUCE_SEQ_FADD, ISD::VECREDUCE_SEQ_FMUL},
806         VT, Expand);
807 
808     // Named vector shuffles default to expand.
809     setOperationAction(ISD::VECTOR_SPLICE, VT, Expand);
810 
811     // Only some target support this vector operation. Most need to expand it.
812     setOperationAction(ISD::VECTOR_COMPRESS, VT, Expand);
813 
814     // VP operations default to expand.
815 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...)                                   \
816     setOperationAction(ISD::SDOPC, VT, Expand);
817 #include "llvm/IR/VPIntrinsics.def"
818 
819     // FP environment operations default to expand.
820     setOperationAction(ISD::GET_FPENV, VT, Expand);
821     setOperationAction(ISD::SET_FPENV, VT, Expand);
822     setOperationAction(ISD::RESET_FPENV, VT, Expand);
823   }
824 
825   // Most targets ignore the @llvm.prefetch intrinsic.
826   setOperationAction(ISD::PREFETCH, MVT::Other, Expand);
827 
828   // Most targets also ignore the @llvm.readcyclecounter intrinsic.
829   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Expand);
830 
831   // Most targets also ignore the @llvm.readsteadycounter intrinsic.
832   setOperationAction(ISD::READSTEADYCOUNTER, MVT::i64, Expand);
833 
834   // ConstantFP nodes default to expand.  Targets can either change this to
835   // Legal, in which case all fp constants are legal, or use isFPImmLegal()
836   // to optimize expansions for certain constants.
837   setOperationAction(ISD::ConstantFP,
838                      {MVT::bf16, MVT::f16, MVT::f32, MVT::f64, MVT::f80, MVT::f128},
839                      Expand);
840 
841   // These library functions default to expand.
842   setOperationAction({ISD::FCBRT,      ISD::FLOG,  ISD::FLOG2,  ISD::FLOG10,
843                       ISD::FEXP,       ISD::FEXP2, ISD::FEXP10, ISD::FFLOOR,
844                       ISD::FNEARBYINT, ISD::FCEIL, ISD::FRINT,  ISD::FTRUNC,
845                       ISD::FROUNDEVEN, ISD::FTAN,  ISD::FACOS,  ISD::FASIN,
846                       ISD::FATAN,      ISD::FCOSH, ISD::FSINH,  ISD::FTANH,
847                       ISD::FATAN2},
848                      {MVT::f32, MVT::f64, MVT::f128}, Expand);
849 
850   // FIXME: Query RuntimeLibCalls to make the decision.
851   setOperationAction({ISD::LRINT, ISD::LLRINT, ISD::LROUND, ISD::LLROUND},
852                      {MVT::f32, MVT::f64, MVT::f128}, LibCall);
853 
854   setOperationAction({ISD::FTAN, ISD::FACOS, ISD::FASIN, ISD::FATAN, ISD::FCOSH,
855                       ISD::FSINH, ISD::FTANH, ISD::FATAN2},
856                      MVT::f16, Promote);
857   // Default ISD::TRAP to expand (which turns it into abort).
858   setOperationAction(ISD::TRAP, MVT::Other, Expand);
859 
860   // On most systems, DEBUGTRAP and TRAP have no difference. The "Expand"
861   // here is to inform DAG Legalizer to replace DEBUGTRAP with TRAP.
862   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Expand);
863 
864   setOperationAction(ISD::UBSANTRAP, MVT::Other, Expand);
865 
866   setOperationAction(ISD::GET_FPENV_MEM, MVT::Other, Expand);
867   setOperationAction(ISD::SET_FPENV_MEM, MVT::Other, Expand);
868 
869   for (MVT VT : {MVT::i8, MVT::i16, MVT::i32, MVT::i64}) {
870     setOperationAction(ISD::GET_FPMODE, VT, Expand);
871     setOperationAction(ISD::SET_FPMODE, VT, Expand);
872   }
873   setOperationAction(ISD::RESET_FPMODE, MVT::Other, Expand);
874 
875   // This one by default will call __clear_cache unless the target
876   // wants something different.
877   setOperationAction(ISD::CLEAR_CACHE, MVT::Other, LibCall);
878 }
879 
880 MVT TargetLoweringBase::getScalarShiftAmountTy(const DataLayout &DL,
881                                                EVT) const {
882   return MVT::getIntegerVT(DL.getPointerSizeInBits(0));
883 }
884 
885 EVT TargetLoweringBase::getShiftAmountTy(EVT LHSTy,
886                                          const DataLayout &DL) const {
887   assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
888   if (LHSTy.isVector())
889     return LHSTy;
890   MVT ShiftVT = getScalarShiftAmountTy(DL, LHSTy);
891   // If any possible shift value won't fit in the prefered type, just use
892   // something safe. Assume it will be legalized when the shift is expanded.
893   if (ShiftVT.getSizeInBits() < Log2_32_Ceil(LHSTy.getSizeInBits()))
894     ShiftVT = MVT::i32;
895   assert(ShiftVT.getSizeInBits() >= Log2_32_Ceil(LHSTy.getSizeInBits()) &&
896          "ShiftVT is still too small!");
897   return ShiftVT;
898 }
899 
900 bool TargetLoweringBase::canOpTrap(unsigned Op, EVT VT) const {
901   assert(isTypeLegal(VT));
902   switch (Op) {
903   default:
904     return false;
905   case ISD::SDIV:
906   case ISD::UDIV:
907   case ISD::SREM:
908   case ISD::UREM:
909     return true;
910   }
911 }
912 
913 bool TargetLoweringBase::isFreeAddrSpaceCast(unsigned SrcAS,
914                                              unsigned DestAS) const {
915   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
916 }
917 
918 unsigned TargetLoweringBase::getBitWidthForCttzElements(
919     Type *RetTy, ElementCount EC, bool ZeroIsPoison,
920     const ConstantRange *VScaleRange) const {
921   // Find the smallest "sensible" element type to use for the expansion.
922   ConstantRange CR(APInt(64, EC.getKnownMinValue()));
923   if (EC.isScalable())
924     CR = CR.umul_sat(*VScaleRange);
925 
926   if (ZeroIsPoison)
927     CR = CR.subtract(APInt(64, 1));
928 
929   unsigned EltWidth = RetTy->getScalarSizeInBits();
930   EltWidth = std::min(EltWidth, (unsigned)CR.getActiveBits());
931   EltWidth = std::max(llvm::bit_ceil(EltWidth), (unsigned)8);
932 
933   return EltWidth;
934 }
935 
936 void TargetLoweringBase::setJumpIsExpensive(bool isExpensive) {
937   // If the command-line option was specified, ignore this request.
938   if (!JumpIsExpensiveOverride.getNumOccurrences())
939     JumpIsExpensive = isExpensive;
940 }
941 
942 TargetLoweringBase::LegalizeKind
943 TargetLoweringBase::getTypeConversion(LLVMContext &Context, EVT VT) const {
944   // If this is a simple type, use the ComputeRegisterProp mechanism.
945   if (VT.isSimple()) {
946     MVT SVT = VT.getSimpleVT();
947     assert((unsigned)SVT.SimpleTy < std::size(TransformToType));
948     MVT NVT = TransformToType[SVT.SimpleTy];
949     LegalizeTypeAction LA = ValueTypeActions.getTypeAction(SVT);
950 
951     assert((LA == TypeLegal || LA == TypeSoftenFloat ||
952             LA == TypeSoftPromoteHalf ||
953             (NVT.isVector() ||
954              ValueTypeActions.getTypeAction(NVT) != TypePromoteInteger)) &&
955            "Promote may not follow Expand or Promote");
956 
957     if (LA == TypeSplitVector)
958       return LegalizeKind(LA, EVT(SVT).getHalfNumVectorElementsVT(Context));
959     if (LA == TypeScalarizeVector)
960       return LegalizeKind(LA, SVT.getVectorElementType());
961     return LegalizeKind(LA, NVT);
962   }
963 
964   // Handle Extended Scalar Types.
965   if (!VT.isVector()) {
966     assert(VT.isInteger() && "Float types must be simple");
967     unsigned BitSize = VT.getSizeInBits();
968     // First promote to a power-of-two size, then expand if necessary.
969     if (BitSize < 8 || !isPowerOf2_32(BitSize)) {
970       EVT NVT = VT.getRoundIntegerType(Context);
971       assert(NVT != VT && "Unable to round integer VT");
972       LegalizeKind NextStep = getTypeConversion(Context, NVT);
973       // Avoid multi-step promotion.
974       if (NextStep.first == TypePromoteInteger)
975         return NextStep;
976       // Return rounded integer type.
977       return LegalizeKind(TypePromoteInteger, NVT);
978     }
979 
980     return LegalizeKind(TypeExpandInteger,
981                         EVT::getIntegerVT(Context, VT.getSizeInBits() / 2));
982   }
983 
984   // Handle vector types.
985   ElementCount NumElts = VT.getVectorElementCount();
986   EVT EltVT = VT.getVectorElementType();
987 
988   // Vectors with only one element are always scalarized.
989   if (NumElts.isScalar())
990     return LegalizeKind(TypeScalarizeVector, EltVT);
991 
992   // Try to widen vector elements until the element type is a power of two and
993   // promote it to a legal type later on, for example:
994   // <3 x i8> -> <4 x i8> -> <4 x i32>
995   if (EltVT.isInteger()) {
996     // Vectors with a number of elements that is not a power of two are always
997     // widened, for example <3 x i8> -> <4 x i8>.
998     if (!VT.isPow2VectorType()) {
999       NumElts = NumElts.coefficientNextPowerOf2();
1000       EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts);
1001       return LegalizeKind(TypeWidenVector, NVT);
1002     }
1003 
1004     // Examine the element type.
1005     LegalizeKind LK = getTypeConversion(Context, EltVT);
1006 
1007     // If type is to be expanded, split the vector.
1008     //  <4 x i140> -> <2 x i140>
1009     if (LK.first == TypeExpandInteger) {
1010       if (VT.getVectorElementCount().isScalable())
1011         return LegalizeKind(TypeScalarizeScalableVector, EltVT);
1012       return LegalizeKind(TypeSplitVector,
1013                           VT.getHalfNumVectorElementsVT(Context));
1014     }
1015 
1016     // Promote the integer element types until a legal vector type is found
1017     // or until the element integer type is too big. If a legal type was not
1018     // found, fallback to the usual mechanism of widening/splitting the
1019     // vector.
1020     EVT OldEltVT = EltVT;
1021     while (true) {
1022       // Increase the bitwidth of the element to the next pow-of-two
1023       // (which is greater than 8 bits).
1024       EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits())
1025                   .getRoundIntegerType(Context);
1026 
1027       // Stop trying when getting a non-simple element type.
1028       // Note that vector elements may be greater than legal vector element
1029       // types. Example: X86 XMM registers hold 64bit element on 32bit
1030       // systems.
1031       if (!EltVT.isSimple())
1032         break;
1033 
1034       // Build a new vector type and check if it is legal.
1035       MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1036       // Found a legal promoted vector type.
1037       if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal)
1038         return LegalizeKind(TypePromoteInteger,
1039                             EVT::getVectorVT(Context, EltVT, NumElts));
1040     }
1041 
1042     // Reset the type to the unexpanded type if we did not find a legal vector
1043     // type with a promoted vector element type.
1044     EltVT = OldEltVT;
1045   }
1046 
1047   // Try to widen the vector until a legal type is found.
1048   // If there is no wider legal type, split the vector.
1049   while (true) {
1050     // Round up to the next power of 2.
1051     NumElts = NumElts.coefficientNextPowerOf2();
1052 
1053     // If there is no simple vector type with this many elements then there
1054     // cannot be a larger legal vector type.  Note that this assumes that
1055     // there are no skipped intermediate vector types in the simple types.
1056     if (!EltVT.isSimple())
1057       break;
1058     MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1059     if (LargerVector == MVT())
1060       break;
1061 
1062     // If this type is legal then widen the vector.
1063     if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal)
1064       return LegalizeKind(TypeWidenVector, LargerVector);
1065   }
1066 
1067   // Widen odd vectors to next power of two.
1068   if (!VT.isPow2VectorType()) {
1069     EVT NVT = VT.getPow2VectorType(Context);
1070     return LegalizeKind(TypeWidenVector, NVT);
1071   }
1072 
1073   if (VT.getVectorElementCount() == ElementCount::getScalable(1))
1074     return LegalizeKind(TypeScalarizeScalableVector, EltVT);
1075 
1076   // Vectors with illegal element types are expanded.
1077   EVT NVT = EVT::getVectorVT(Context, EltVT,
1078                              VT.getVectorElementCount().divideCoefficientBy(2));
1079   return LegalizeKind(TypeSplitVector, NVT);
1080 }
1081 
1082 static unsigned getVectorTypeBreakdownMVT(MVT VT, MVT &IntermediateVT,
1083                                           unsigned &NumIntermediates,
1084                                           MVT &RegisterVT,
1085                                           TargetLoweringBase *TLI) {
1086   // Figure out the right, legal destination reg to copy into.
1087   ElementCount EC = VT.getVectorElementCount();
1088   MVT EltTy = VT.getVectorElementType();
1089 
1090   unsigned NumVectorRegs = 1;
1091 
1092   // Scalable vectors cannot be scalarized, so splitting or widening is
1093   // required.
1094   if (VT.isScalableVector() && !isPowerOf2_32(EC.getKnownMinValue()))
1095     llvm_unreachable(
1096         "Splitting or widening of non-power-of-2 MVTs is not implemented.");
1097 
1098   // FIXME: We don't support non-power-of-2-sized vectors for now.
1099   // Ideally we could break down into LHS/RHS like LegalizeDAG does.
1100   if (!isPowerOf2_32(EC.getKnownMinValue())) {
1101     // Split EC to unit size (scalable property is preserved).
1102     NumVectorRegs = EC.getKnownMinValue();
1103     EC = ElementCount::getFixed(1);
1104   }
1105 
1106   // Divide the input until we get to a supported size. This will
1107   // always end up with an EC that represent a scalar or a scalable
1108   // scalar.
1109   while (EC.getKnownMinValue() > 1 &&
1110          !TLI->isTypeLegal(MVT::getVectorVT(EltTy, EC))) {
1111     EC = EC.divideCoefficientBy(2);
1112     NumVectorRegs <<= 1;
1113   }
1114 
1115   NumIntermediates = NumVectorRegs;
1116 
1117   MVT NewVT = MVT::getVectorVT(EltTy, EC);
1118   if (!TLI->isTypeLegal(NewVT))
1119     NewVT = EltTy;
1120   IntermediateVT = NewVT;
1121 
1122   unsigned LaneSizeInBits = NewVT.getScalarSizeInBits();
1123 
1124   // Convert sizes such as i33 to i64.
1125   LaneSizeInBits = llvm::bit_ceil(LaneSizeInBits);
1126 
1127   MVT DestVT = TLI->getRegisterType(NewVT);
1128   RegisterVT = DestVT;
1129   if (EVT(DestVT).bitsLT(NewVT))    // Value is expanded, e.g. i64 -> i16.
1130     return NumVectorRegs * (LaneSizeInBits / DestVT.getScalarSizeInBits());
1131 
1132   // Otherwise, promotion or legal types use the same number of registers as
1133   // the vector decimated to the appropriate level.
1134   return NumVectorRegs;
1135 }
1136 
1137 /// isLegalRC - Return true if the value types that can be represented by the
1138 /// specified register class are all legal.
1139 bool TargetLoweringBase::isLegalRC(const TargetRegisterInfo &TRI,
1140                                    const TargetRegisterClass &RC) const {
1141   for (const auto *I = TRI.legalclasstypes_begin(RC); *I != MVT::Other; ++I)
1142     if (isTypeLegal(*I))
1143       return true;
1144   return false;
1145 }
1146 
1147 /// Replace/modify any TargetFrameIndex operands with a targte-dependent
1148 /// sequence of memory operands that is recognized by PrologEpilogInserter.
1149 MachineBasicBlock *
1150 TargetLoweringBase::emitPatchPoint(MachineInstr &InitialMI,
1151                                    MachineBasicBlock *MBB) const {
1152   MachineInstr *MI = &InitialMI;
1153   MachineFunction &MF = *MI->getMF();
1154   MachineFrameInfo &MFI = MF.getFrameInfo();
1155 
1156   // We're handling multiple types of operands here:
1157   // PATCHPOINT MetaArgs - live-in, read only, direct
1158   // STATEPOINT Deopt Spill - live-through, read only, indirect
1159   // STATEPOINT Deopt Alloca - live-through, read only, direct
1160   // (We're currently conservative and mark the deopt slots read/write in
1161   // practice.)
1162   // STATEPOINT GC Spill - live-through, read/write, indirect
1163   // STATEPOINT GC Alloca - live-through, read/write, direct
1164   // The live-in vs live-through is handled already (the live through ones are
1165   // all stack slots), but we need to handle the different type of stackmap
1166   // operands and memory effects here.
1167 
1168   if (llvm::none_of(MI->operands(),
1169                     [](MachineOperand &Operand) { return Operand.isFI(); }))
1170     return MBB;
1171 
1172   MachineInstrBuilder MIB = BuildMI(MF, MI->getDebugLoc(), MI->getDesc());
1173 
1174   // Inherit previous memory operands.
1175   MIB.cloneMemRefs(*MI);
1176 
1177   for (unsigned i = 0; i < MI->getNumOperands(); ++i) {
1178     MachineOperand &MO = MI->getOperand(i);
1179     if (!MO.isFI()) {
1180       // Index of Def operand this Use it tied to.
1181       // Since Defs are coming before Uses, if Use is tied, then
1182       // index of Def must be smaller that index of that Use.
1183       // Also, Defs preserve their position in new MI.
1184       unsigned TiedTo = i;
1185       if (MO.isReg() && MO.isTied())
1186         TiedTo = MI->findTiedOperandIdx(i);
1187       MIB.add(MO);
1188       if (TiedTo < i)
1189         MIB->tieOperands(TiedTo, MIB->getNumOperands() - 1);
1190       continue;
1191     }
1192 
1193     // foldMemoryOperand builds a new MI after replacing a single FI operand
1194     // with the canonical set of five x86 addressing-mode operands.
1195     int FI = MO.getIndex();
1196 
1197     // Add frame index operands recognized by stackmaps.cpp
1198     if (MFI.isStatepointSpillSlotObjectIndex(FI)) {
1199       // indirect-mem-ref tag, size, #FI, offset.
1200       // Used for spills inserted by StatepointLowering.  This codepath is not
1201       // used for patchpoints/stackmaps at all, for these spilling is done via
1202       // foldMemoryOperand callback only.
1203       assert(MI->getOpcode() == TargetOpcode::STATEPOINT && "sanity");
1204       MIB.addImm(StackMaps::IndirectMemRefOp);
1205       MIB.addImm(MFI.getObjectSize(FI));
1206       MIB.add(MO);
1207       MIB.addImm(0);
1208     } else {
1209       // direct-mem-ref tag, #FI, offset.
1210       // Used by patchpoint, and direct alloca arguments to statepoints
1211       MIB.addImm(StackMaps::DirectMemRefOp);
1212       MIB.add(MO);
1213       MIB.addImm(0);
1214     }
1215 
1216     assert(MIB->mayLoad() && "Folded a stackmap use to a non-load!");
1217 
1218     // Add a new memory operand for this FI.
1219     assert(MFI.getObjectOffset(FI) != -1);
1220 
1221     // Note: STATEPOINT MMOs are added during SelectionDAG.  STACKMAP, and
1222     // PATCHPOINT should be updated to do the same. (TODO)
1223     if (MI->getOpcode() != TargetOpcode::STATEPOINT) {
1224       auto Flags = MachineMemOperand::MOLoad;
1225       MachineMemOperand *MMO = MF.getMachineMemOperand(
1226           MachinePointerInfo::getFixedStack(MF, FI), Flags,
1227           MF.getDataLayout().getPointerSize(), MFI.getObjectAlign(FI));
1228       MIB->addMemOperand(MF, MMO);
1229     }
1230   }
1231   MBB->insert(MachineBasicBlock::iterator(MI), MIB);
1232   MI->eraseFromParent();
1233   return MBB;
1234 }
1235 
1236 /// findRepresentativeClass - Return the largest legal super-reg register class
1237 /// of the register class for the specified type and its associated "cost".
1238 // This function is in TargetLowering because it uses RegClassForVT which would
1239 // need to be moved to TargetRegisterInfo and would necessitate moving
1240 // isTypeLegal over as well - a massive change that would just require
1241 // TargetLowering having a TargetRegisterInfo class member that it would use.
1242 std::pair<const TargetRegisterClass *, uint8_t>
1243 TargetLoweringBase::findRepresentativeClass(const TargetRegisterInfo *TRI,
1244                                             MVT VT) const {
1245   const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
1246   if (!RC)
1247     return std::make_pair(RC, 0);
1248 
1249   // Compute the set of all super-register classes.
1250   BitVector SuperRegRC(TRI->getNumRegClasses());
1251   for (SuperRegClassIterator RCI(RC, TRI); RCI.isValid(); ++RCI)
1252     SuperRegRC.setBitsInMask(RCI.getMask());
1253 
1254   // Find the first legal register class with the largest spill size.
1255   const TargetRegisterClass *BestRC = RC;
1256   for (unsigned i : SuperRegRC.set_bits()) {
1257     const TargetRegisterClass *SuperRC = TRI->getRegClass(i);
1258     // We want the largest possible spill size.
1259     if (TRI->getSpillSize(*SuperRC) <= TRI->getSpillSize(*BestRC))
1260       continue;
1261     if (!isLegalRC(*TRI, *SuperRC))
1262       continue;
1263     BestRC = SuperRC;
1264   }
1265   return std::make_pair(BestRC, 1);
1266 }
1267 
1268 /// computeRegisterProperties - Once all of the register classes are added,
1269 /// this allows us to compute derived properties we expose.
1270 void TargetLoweringBase::computeRegisterProperties(
1271     const TargetRegisterInfo *TRI) {
1272   // Everything defaults to needing one register.
1273   for (unsigned i = 0; i != MVT::VALUETYPE_SIZE; ++i) {
1274     NumRegistersForVT[i] = 1;
1275     RegisterTypeForVT[i] = TransformToType[i] = (MVT::SimpleValueType)i;
1276   }
1277   // ...except isVoid, which doesn't need any registers.
1278   NumRegistersForVT[MVT::isVoid] = 0;
1279 
1280   // Find the largest integer register class.
1281   unsigned LargestIntReg = MVT::LAST_INTEGER_VALUETYPE;
1282   for (; RegClassForVT[LargestIntReg] == nullptr; --LargestIntReg)
1283     assert(LargestIntReg != MVT::i1 && "No integer registers defined!");
1284 
1285   // Every integer value type larger than this largest register takes twice as
1286   // many registers to represent as the previous ValueType.
1287   for (unsigned ExpandedReg = LargestIntReg + 1;
1288        ExpandedReg <= MVT::LAST_INTEGER_VALUETYPE; ++ExpandedReg) {
1289     NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1];
1290     RegisterTypeForVT[ExpandedReg] = (MVT::SimpleValueType)LargestIntReg;
1291     TransformToType[ExpandedReg] = (MVT::SimpleValueType)(ExpandedReg - 1);
1292     ValueTypeActions.setTypeAction((MVT::SimpleValueType)ExpandedReg,
1293                                    TypeExpandInteger);
1294   }
1295 
1296   // Inspect all of the ValueType's smaller than the largest integer
1297   // register to see which ones need promotion.
1298   unsigned LegalIntReg = LargestIntReg;
1299   for (unsigned IntReg = LargestIntReg - 1;
1300        IntReg >= (unsigned)MVT::i1; --IntReg) {
1301     MVT IVT = (MVT::SimpleValueType)IntReg;
1302     if (isTypeLegal(IVT)) {
1303       LegalIntReg = IntReg;
1304     } else {
1305       RegisterTypeForVT[IntReg] = TransformToType[IntReg] =
1306         (MVT::SimpleValueType)LegalIntReg;
1307       ValueTypeActions.setTypeAction(IVT, TypePromoteInteger);
1308     }
1309   }
1310 
1311   // ppcf128 type is really two f64's.
1312   if (!isTypeLegal(MVT::ppcf128)) {
1313     if (isTypeLegal(MVT::f64)) {
1314       NumRegistersForVT[MVT::ppcf128] = 2*NumRegistersForVT[MVT::f64];
1315       RegisterTypeForVT[MVT::ppcf128] = MVT::f64;
1316       TransformToType[MVT::ppcf128] = MVT::f64;
1317       ValueTypeActions.setTypeAction(MVT::ppcf128, TypeExpandFloat);
1318     } else {
1319       NumRegistersForVT[MVT::ppcf128] = NumRegistersForVT[MVT::i128];
1320       RegisterTypeForVT[MVT::ppcf128] = RegisterTypeForVT[MVT::i128];
1321       TransformToType[MVT::ppcf128] = MVT::i128;
1322       ValueTypeActions.setTypeAction(MVT::ppcf128, TypeSoftenFloat);
1323     }
1324   }
1325 
1326   // Decide how to handle f128. If the target does not have native f128 support,
1327   // expand it to i128 and we will be generating soft float library calls.
1328   if (!isTypeLegal(MVT::f128)) {
1329     NumRegistersForVT[MVT::f128] = NumRegistersForVT[MVT::i128];
1330     RegisterTypeForVT[MVT::f128] = RegisterTypeForVT[MVT::i128];
1331     TransformToType[MVT::f128] = MVT::i128;
1332     ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
1333   }
1334 
1335   // Decide how to handle f80. If the target does not have native f80 support,
1336   // expand it to i96 and we will be generating soft float library calls.
1337   if (!isTypeLegal(MVT::f80)) {
1338     NumRegistersForVT[MVT::f80] = 3*NumRegistersForVT[MVT::i32];
1339     RegisterTypeForVT[MVT::f80] = RegisterTypeForVT[MVT::i32];
1340     TransformToType[MVT::f80] = MVT::i32;
1341     ValueTypeActions.setTypeAction(MVT::f80, TypeSoftenFloat);
1342   }
1343 
1344   // Decide how to handle f64. If the target does not have native f64 support,
1345   // expand it to i64 and we will be generating soft float library calls.
1346   if (!isTypeLegal(MVT::f64)) {
1347     NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64];
1348     RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64];
1349     TransformToType[MVT::f64] = MVT::i64;
1350     ValueTypeActions.setTypeAction(MVT::f64, TypeSoftenFloat);
1351   }
1352 
1353   // Decide how to handle f32. If the target does not have native f32 support,
1354   // expand it to i32 and we will be generating soft float library calls.
1355   if (!isTypeLegal(MVT::f32)) {
1356     NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32];
1357     RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32];
1358     TransformToType[MVT::f32] = MVT::i32;
1359     ValueTypeActions.setTypeAction(MVT::f32, TypeSoftenFloat);
1360   }
1361 
1362   // Decide how to handle f16. If the target does not have native f16 support,
1363   // promote it to f32, because there are no f16 library calls (except for
1364   // conversions).
1365   if (!isTypeLegal(MVT::f16)) {
1366     // Allow targets to control how we legalize half.
1367     bool SoftPromoteHalfType = softPromoteHalfType();
1368     bool UseFPRegsForHalfType = !SoftPromoteHalfType || useFPRegsForHalfType();
1369 
1370     if (!UseFPRegsForHalfType) {
1371       NumRegistersForVT[MVT::f16] = NumRegistersForVT[MVT::i16];
1372       RegisterTypeForVT[MVT::f16] = RegisterTypeForVT[MVT::i16];
1373     } else {
1374       NumRegistersForVT[MVT::f16] = NumRegistersForVT[MVT::f32];
1375       RegisterTypeForVT[MVT::f16] = RegisterTypeForVT[MVT::f32];
1376     }
1377     TransformToType[MVT::f16] = MVT::f32;
1378     if (SoftPromoteHalfType) {
1379       ValueTypeActions.setTypeAction(MVT::f16, TypeSoftPromoteHalf);
1380     } else {
1381       ValueTypeActions.setTypeAction(MVT::f16, TypePromoteFloat);
1382     }
1383   }
1384 
1385   // Decide how to handle bf16. If the target does not have native bf16 support,
1386   // promote it to f32, because there are no bf16 library calls (except for
1387   // converting from f32 to bf16).
1388   if (!isTypeLegal(MVT::bf16)) {
1389     NumRegistersForVT[MVT::bf16] = NumRegistersForVT[MVT::f32];
1390     RegisterTypeForVT[MVT::bf16] = RegisterTypeForVT[MVT::f32];
1391     TransformToType[MVT::bf16] = MVT::f32;
1392     ValueTypeActions.setTypeAction(MVT::bf16, TypeSoftPromoteHalf);
1393   }
1394 
1395   // Loop over all of the vector value types to see which need transformations.
1396   for (unsigned i = MVT::FIRST_VECTOR_VALUETYPE;
1397        i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1398     MVT VT = (MVT::SimpleValueType) i;
1399     if (isTypeLegal(VT))
1400       continue;
1401 
1402     MVT EltVT = VT.getVectorElementType();
1403     ElementCount EC = VT.getVectorElementCount();
1404     bool IsLegalWiderType = false;
1405     bool IsScalable = VT.isScalableVector();
1406     LegalizeTypeAction PreferredAction = getPreferredVectorAction(VT);
1407     switch (PreferredAction) {
1408     case TypePromoteInteger: {
1409       MVT::SimpleValueType EndVT = IsScalable ?
1410                                    MVT::LAST_INTEGER_SCALABLE_VECTOR_VALUETYPE :
1411                                    MVT::LAST_INTEGER_FIXEDLEN_VECTOR_VALUETYPE;
1412       // Try to promote the elements of integer vectors. If no legal
1413       // promotion was found, fall through to the widen-vector method.
1414       for (unsigned nVT = i + 1;
1415            (MVT::SimpleValueType)nVT <= EndVT; ++nVT) {
1416         MVT SVT = (MVT::SimpleValueType) nVT;
1417         // Promote vectors of integers to vectors with the same number
1418         // of elements, with a wider element type.
1419         if (SVT.getScalarSizeInBits() > EltVT.getFixedSizeInBits() &&
1420             SVT.getVectorElementCount() == EC && isTypeLegal(SVT)) {
1421           TransformToType[i] = SVT;
1422           RegisterTypeForVT[i] = SVT;
1423           NumRegistersForVT[i] = 1;
1424           ValueTypeActions.setTypeAction(VT, TypePromoteInteger);
1425           IsLegalWiderType = true;
1426           break;
1427         }
1428       }
1429       if (IsLegalWiderType)
1430         break;
1431       [[fallthrough]];
1432     }
1433 
1434     case TypeWidenVector:
1435       if (isPowerOf2_32(EC.getKnownMinValue())) {
1436         // Try to widen the vector.
1437         for (unsigned nVT = i + 1; nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
1438           MVT SVT = (MVT::SimpleValueType) nVT;
1439           if (SVT.getVectorElementType() == EltVT &&
1440               SVT.isScalableVector() == IsScalable &&
1441               SVT.getVectorElementCount().getKnownMinValue() >
1442                   EC.getKnownMinValue() &&
1443               isTypeLegal(SVT)) {
1444             TransformToType[i] = SVT;
1445             RegisterTypeForVT[i] = SVT;
1446             NumRegistersForVT[i] = 1;
1447             ValueTypeActions.setTypeAction(VT, TypeWidenVector);
1448             IsLegalWiderType = true;
1449             break;
1450           }
1451         }
1452         if (IsLegalWiderType)
1453           break;
1454       } else {
1455         // Only widen to the next power of 2 to keep consistency with EVT.
1456         MVT NVT = VT.getPow2VectorType();
1457         if (isTypeLegal(NVT)) {
1458           TransformToType[i] = NVT;
1459           ValueTypeActions.setTypeAction(VT, TypeWidenVector);
1460           RegisterTypeForVT[i] = NVT;
1461           NumRegistersForVT[i] = 1;
1462           break;
1463         }
1464       }
1465       [[fallthrough]];
1466 
1467     case TypeSplitVector:
1468     case TypeScalarizeVector: {
1469       MVT IntermediateVT;
1470       MVT RegisterVT;
1471       unsigned NumIntermediates;
1472       unsigned NumRegisters = getVectorTypeBreakdownMVT(VT, IntermediateVT,
1473           NumIntermediates, RegisterVT, this);
1474       NumRegistersForVT[i] = NumRegisters;
1475       assert(NumRegistersForVT[i] == NumRegisters &&
1476              "NumRegistersForVT size cannot represent NumRegisters!");
1477       RegisterTypeForVT[i] = RegisterVT;
1478 
1479       MVT NVT = VT.getPow2VectorType();
1480       if (NVT == VT) {
1481         // Type is already a power of 2.  The default action is to split.
1482         TransformToType[i] = MVT::Other;
1483         if (PreferredAction == TypeScalarizeVector)
1484           ValueTypeActions.setTypeAction(VT, TypeScalarizeVector);
1485         else if (PreferredAction == TypeSplitVector)
1486           ValueTypeActions.setTypeAction(VT, TypeSplitVector);
1487         else if (EC.getKnownMinValue() > 1)
1488           ValueTypeActions.setTypeAction(VT, TypeSplitVector);
1489         else
1490           ValueTypeActions.setTypeAction(VT, EC.isScalable()
1491                                                  ? TypeScalarizeScalableVector
1492                                                  : TypeScalarizeVector);
1493       } else {
1494         TransformToType[i] = NVT;
1495         ValueTypeActions.setTypeAction(VT, TypeWidenVector);
1496       }
1497       break;
1498     }
1499     default:
1500       llvm_unreachable("Unknown vector legalization action!");
1501     }
1502   }
1503 
1504   // Determine the 'representative' register class for each value type.
1505   // An representative register class is the largest (meaning one which is
1506   // not a sub-register class / subreg register class) legal register class for
1507   // a group of value types. For example, on i386, i8, i16, and i32
1508   // representative would be GR32; while on x86_64 it's GR64.
1509   for (unsigned i = 0; i != MVT::VALUETYPE_SIZE; ++i) {
1510     const TargetRegisterClass* RRC;
1511     uint8_t Cost;
1512     std::tie(RRC, Cost) = findRepresentativeClass(TRI, (MVT::SimpleValueType)i);
1513     RepRegClassForVT[i] = RRC;
1514     RepRegClassCostForVT[i] = Cost;
1515   }
1516 }
1517 
1518 EVT TargetLoweringBase::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1519                                            EVT VT) const {
1520   assert(!VT.isVector() && "No default SetCC type for vectors!");
1521   return getPointerTy(DL).SimpleTy;
1522 }
1523 
1524 MVT::SimpleValueType TargetLoweringBase::getCmpLibcallReturnType() const {
1525   return MVT::i32; // return the default value
1526 }
1527 
1528 /// getVectorTypeBreakdown - Vector types are broken down into some number of
1529 /// legal first class types.  For example, MVT::v8f32 maps to 2 MVT::v4f32
1530 /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
1531 /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
1532 ///
1533 /// This method returns the number of registers needed, and the VT for each
1534 /// register.  It also returns the VT and quantity of the intermediate values
1535 /// before they are promoted/expanded.
1536 unsigned TargetLoweringBase::getVectorTypeBreakdown(LLVMContext &Context,
1537                                                     EVT VT, EVT &IntermediateVT,
1538                                                     unsigned &NumIntermediates,
1539                                                     MVT &RegisterVT) const {
1540   ElementCount EltCnt = VT.getVectorElementCount();
1541 
1542   // If there is a wider vector type with the same element type as this one,
1543   // or a promoted vector type that has the same number of elements which
1544   // are wider, then we should convert to that legal vector type.
1545   // This handles things like <2 x float> -> <4 x float> and
1546   // <4 x i1> -> <4 x i32>.
1547   LegalizeTypeAction TA = getTypeAction(Context, VT);
1548   if (!EltCnt.isScalar() &&
1549       (TA == TypeWidenVector || TA == TypePromoteInteger)) {
1550     EVT RegisterEVT = getTypeToTransformTo(Context, VT);
1551     if (isTypeLegal(RegisterEVT)) {
1552       IntermediateVT = RegisterEVT;
1553       RegisterVT = RegisterEVT.getSimpleVT();
1554       NumIntermediates = 1;
1555       return 1;
1556     }
1557   }
1558 
1559   // Figure out the right, legal destination reg to copy into.
1560   EVT EltTy = VT.getVectorElementType();
1561 
1562   unsigned NumVectorRegs = 1;
1563 
1564   // Scalable vectors cannot be scalarized, so handle the legalisation of the
1565   // types like done elsewhere in SelectionDAG.
1566   if (EltCnt.isScalable()) {
1567     LegalizeKind LK;
1568     EVT PartVT = VT;
1569     do {
1570       // Iterate until we've found a legal (part) type to hold VT.
1571       LK = getTypeConversion(Context, PartVT);
1572       PartVT = LK.second;
1573     } while (LK.first != TypeLegal);
1574 
1575     if (!PartVT.isVector()) {
1576       report_fatal_error(
1577           "Don't know how to legalize this scalable vector type");
1578     }
1579 
1580     NumIntermediates =
1581         divideCeil(VT.getVectorElementCount().getKnownMinValue(),
1582                    PartVT.getVectorElementCount().getKnownMinValue());
1583     IntermediateVT = PartVT;
1584     RegisterVT = getRegisterType(Context, IntermediateVT);
1585     return NumIntermediates;
1586   }
1587 
1588   // FIXME: We don't support non-power-of-2-sized vectors for now.  Ideally
1589   // we could break down into LHS/RHS like LegalizeDAG does.
1590   if (!isPowerOf2_32(EltCnt.getKnownMinValue())) {
1591     NumVectorRegs = EltCnt.getKnownMinValue();
1592     EltCnt = ElementCount::getFixed(1);
1593   }
1594 
1595   // Divide the input until we get to a supported size.  This will always
1596   // end with a scalar if the target doesn't support vectors.
1597   while (EltCnt.getKnownMinValue() > 1 &&
1598          !isTypeLegal(EVT::getVectorVT(Context, EltTy, EltCnt))) {
1599     EltCnt = EltCnt.divideCoefficientBy(2);
1600     NumVectorRegs <<= 1;
1601   }
1602 
1603   NumIntermediates = NumVectorRegs;
1604 
1605   EVT NewVT = EVT::getVectorVT(Context, EltTy, EltCnt);
1606   if (!isTypeLegal(NewVT))
1607     NewVT = EltTy;
1608   IntermediateVT = NewVT;
1609 
1610   MVT DestVT = getRegisterType(Context, NewVT);
1611   RegisterVT = DestVT;
1612 
1613   if (EVT(DestVT).bitsLT(NewVT)) {  // Value is expanded, e.g. i64 -> i16.
1614     TypeSize NewVTSize = NewVT.getSizeInBits();
1615     // Convert sizes such as i33 to i64.
1616     if (!llvm::has_single_bit<uint32_t>(NewVTSize.getKnownMinValue()))
1617       NewVTSize = NewVTSize.coefficientNextPowerOf2();
1618     return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits());
1619   }
1620 
1621   // Otherwise, promotion or legal types use the same number of registers as
1622   // the vector decimated to the appropriate level.
1623   return NumVectorRegs;
1624 }
1625 
1626 bool TargetLoweringBase::isSuitableForJumpTable(const SwitchInst *SI,
1627                                                 uint64_t NumCases,
1628                                                 uint64_t Range,
1629                                                 ProfileSummaryInfo *PSI,
1630                                                 BlockFrequencyInfo *BFI) const {
1631   // FIXME: This function check the maximum table size and density, but the
1632   // minimum size is not checked. It would be nice if the minimum size is
1633   // also combined within this function. Currently, the minimum size check is
1634   // performed in findJumpTable() in SelectionDAGBuiler and
1635   // getEstimatedNumberOfCaseClusters() in BasicTTIImpl.
1636   const bool OptForSize =
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