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