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