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