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