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.getFixedSizeInBits());
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::SSHLSAT, VT, Expand);
661     setOperationAction(ISD::USHLSAT, VT, Expand);
662     setOperationAction(ISD::SMULFIX, VT, Expand);
663     setOperationAction(ISD::SMULFIXSAT, VT, Expand);
664     setOperationAction(ISD::UMULFIX, VT, Expand);
665     setOperationAction(ISD::UMULFIXSAT, VT, Expand);
666     setOperationAction(ISD::SDIVFIX, VT, Expand);
667     setOperationAction(ISD::SDIVFIXSAT, VT, Expand);
668     setOperationAction(ISD::UDIVFIX, VT, Expand);
669     setOperationAction(ISD::UDIVFIXSAT, VT, Expand);
670 
671     // Overflow operations default to expand
672     setOperationAction(ISD::SADDO, VT, Expand);
673     setOperationAction(ISD::SSUBO, VT, Expand);
674     setOperationAction(ISD::UADDO, VT, Expand);
675     setOperationAction(ISD::USUBO, VT, Expand);
676     setOperationAction(ISD::SMULO, VT, Expand);
677     setOperationAction(ISD::UMULO, VT, Expand);
678 
679     // ADDCARRY operations default to expand
680     setOperationAction(ISD::ADDCARRY, VT, Expand);
681     setOperationAction(ISD::SUBCARRY, VT, Expand);
682     setOperationAction(ISD::SETCCCARRY, VT, Expand);
683     setOperationAction(ISD::SADDO_CARRY, VT, Expand);
684     setOperationAction(ISD::SSUBO_CARRY, VT, Expand);
685 
686     // ADDC/ADDE/SUBC/SUBE default to expand.
687     setOperationAction(ISD::ADDC, VT, Expand);
688     setOperationAction(ISD::ADDE, VT, Expand);
689     setOperationAction(ISD::SUBC, VT, Expand);
690     setOperationAction(ISD::SUBE, VT, Expand);
691 
692     // These default to Expand so they will be expanded to CTLZ/CTTZ by default.
693     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
694     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
695 
696     setOperationAction(ISD::BITREVERSE, VT, Expand);
697     setOperationAction(ISD::PARITY, VT, Expand);
698 
699     // These library functions default to expand.
700     setOperationAction(ISD::FROUND, VT, Expand);
701     setOperationAction(ISD::FROUNDEVEN, VT, Expand);
702     setOperationAction(ISD::FPOWI, VT, Expand);
703 
704     // These operations default to expand for vector types.
705     if (VT.isVector()) {
706       setOperationAction(ISD::FCOPYSIGN, VT, Expand);
707       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
708       setOperationAction(ISD::ANY_EXTEND_VECTOR_INREG, VT, Expand);
709       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Expand);
710       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Expand);
711       setOperationAction(ISD::SPLAT_VECTOR, VT, Expand);
712     }
713 
714     // Constrained floating-point operations default to expand.
715 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
716     setOperationAction(ISD::STRICT_##DAGN, VT, Expand);
717 #include "llvm/IR/ConstrainedOps.def"
718 
719     // For most targets @llvm.get.dynamic.area.offset just returns 0.
720     setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, VT, Expand);
721 
722     // Vector reduction default to expand.
723     setOperationAction(ISD::VECREDUCE_FADD, VT, Expand);
724     setOperationAction(ISD::VECREDUCE_FMUL, VT, Expand);
725     setOperationAction(ISD::VECREDUCE_ADD, VT, Expand);
726     setOperationAction(ISD::VECREDUCE_MUL, VT, Expand);
727     setOperationAction(ISD::VECREDUCE_AND, VT, Expand);
728     setOperationAction(ISD::VECREDUCE_OR, VT, Expand);
729     setOperationAction(ISD::VECREDUCE_XOR, VT, Expand);
730     setOperationAction(ISD::VECREDUCE_SMAX, VT, Expand);
731     setOperationAction(ISD::VECREDUCE_SMIN, VT, Expand);
732     setOperationAction(ISD::VECREDUCE_UMAX, VT, Expand);
733     setOperationAction(ISD::VECREDUCE_UMIN, VT, Expand);
734     setOperationAction(ISD::VECREDUCE_FMAX, VT, Expand);
735     setOperationAction(ISD::VECREDUCE_FMIN, VT, Expand);
736     setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Expand);
737   }
738 
739   // Most targets ignore the @llvm.prefetch intrinsic.
740   setOperationAction(ISD::PREFETCH, MVT::Other, Expand);
741 
742   // Most targets also ignore the @llvm.readcyclecounter intrinsic.
743   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Expand);
744 
745   // ConstantFP nodes default to expand.  Targets can either change this to
746   // Legal, in which case all fp constants are legal, or use isFPImmLegal()
747   // to optimize expansions for certain constants.
748   setOperationAction(ISD::ConstantFP, MVT::f16, Expand);
749   setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
750   setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
751   setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
752   setOperationAction(ISD::ConstantFP, MVT::f128, Expand);
753 
754   // These library functions default to expand.
755   for (MVT VT : {MVT::f32, MVT::f64, MVT::f128}) {
756     setOperationAction(ISD::FCBRT,      VT, Expand);
757     setOperationAction(ISD::FLOG ,      VT, Expand);
758     setOperationAction(ISD::FLOG2,      VT, Expand);
759     setOperationAction(ISD::FLOG10,     VT, Expand);
760     setOperationAction(ISD::FEXP ,      VT, Expand);
761     setOperationAction(ISD::FEXP2,      VT, Expand);
762     setOperationAction(ISD::FFLOOR,     VT, Expand);
763     setOperationAction(ISD::FNEARBYINT, VT, Expand);
764     setOperationAction(ISD::FCEIL,      VT, Expand);
765     setOperationAction(ISD::FRINT,      VT, Expand);
766     setOperationAction(ISD::FTRUNC,     VT, Expand);
767     setOperationAction(ISD::FROUND,     VT, Expand);
768     setOperationAction(ISD::FROUNDEVEN, VT, Expand);
769     setOperationAction(ISD::LROUND,     VT, Expand);
770     setOperationAction(ISD::LLROUND,    VT, Expand);
771     setOperationAction(ISD::LRINT,      VT, Expand);
772     setOperationAction(ISD::LLRINT,     VT, Expand);
773   }
774 
775   // Default ISD::TRAP to expand (which turns it into abort).
776   setOperationAction(ISD::TRAP, MVT::Other, Expand);
777 
778   // On most systems, DEBUGTRAP and TRAP have no difference. The "Expand"
779   // here is to inform DAG Legalizer to replace DEBUGTRAP with TRAP.
780   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Expand);
781 }
782 
783 MVT TargetLoweringBase::getScalarShiftAmountTy(const DataLayout &DL,
784                                                EVT) const {
785   return MVT::getIntegerVT(DL.getPointerSizeInBits(0));
786 }
787 
788 EVT TargetLoweringBase::getShiftAmountTy(EVT LHSTy, const DataLayout &DL,
789                                          bool LegalTypes) const {
790   assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
791   if (LHSTy.isVector())
792     return LHSTy;
793   return LegalTypes ? getScalarShiftAmountTy(DL, LHSTy)
794                     : getPointerTy(DL);
795 }
796 
797 bool TargetLoweringBase::canOpTrap(unsigned Op, EVT VT) const {
798   assert(isTypeLegal(VT));
799   switch (Op) {
800   default:
801     return false;
802   case ISD::SDIV:
803   case ISD::UDIV:
804   case ISD::SREM:
805   case ISD::UREM:
806     return true;
807   }
808 }
809 
810 bool TargetLoweringBase::isFreeAddrSpaceCast(unsigned SrcAS,
811                                              unsigned DestAS) const {
812   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
813 }
814 
815 void TargetLoweringBase::setJumpIsExpensive(bool isExpensive) {
816   // If the command-line option was specified, ignore this request.
817   if (!JumpIsExpensiveOverride.getNumOccurrences())
818     JumpIsExpensive = isExpensive;
819 }
820 
821 TargetLoweringBase::LegalizeKind
822 TargetLoweringBase::getTypeConversion(LLVMContext &Context, EVT VT) const {
823   // If this is a simple type, use the ComputeRegisterProp mechanism.
824   if (VT.isSimple()) {
825     MVT SVT = VT.getSimpleVT();
826     assert((unsigned)SVT.SimpleTy < array_lengthof(TransformToType));
827     MVT NVT = TransformToType[SVT.SimpleTy];
828     LegalizeTypeAction LA = ValueTypeActions.getTypeAction(SVT);
829 
830     assert((LA == TypeLegal || LA == TypeSoftenFloat ||
831             LA == TypeSoftPromoteHalf ||
832             (NVT.isVector() ||
833              ValueTypeActions.getTypeAction(NVT) != TypePromoteInteger)) &&
834            "Promote may not follow Expand or Promote");
835 
836     if (LA == TypeSplitVector)
837       return LegalizeKind(LA, EVT(SVT).getHalfNumVectorElementsVT(Context));
838     if (LA == TypeScalarizeVector)
839       return LegalizeKind(LA, SVT.getVectorElementType());
840     return LegalizeKind(LA, NVT);
841   }
842 
843   // Handle Extended Scalar Types.
844   if (!VT.isVector()) {
845     assert(VT.isInteger() && "Float types must be simple");
846     unsigned BitSize = VT.getSizeInBits();
847     // First promote to a power-of-two size, then expand if necessary.
848     if (BitSize < 8 || !isPowerOf2_32(BitSize)) {
849       EVT NVT = VT.getRoundIntegerType(Context);
850       assert(NVT != VT && "Unable to round integer VT");
851       LegalizeKind NextStep = getTypeConversion(Context, NVT);
852       // Avoid multi-step promotion.
853       if (NextStep.first == TypePromoteInteger)
854         return NextStep;
855       // Return rounded integer type.
856       return LegalizeKind(TypePromoteInteger, NVT);
857     }
858 
859     return LegalizeKind(TypeExpandInteger,
860                         EVT::getIntegerVT(Context, VT.getSizeInBits() / 2));
861   }
862 
863   // Handle vector types.
864   ElementCount NumElts = VT.getVectorElementCount();
865   EVT EltVT = VT.getVectorElementType();
866 
867   // Vectors with only one element are always scalarized.
868   if (NumElts.isScalar())
869     return LegalizeKind(TypeScalarizeVector, EltVT);
870 
871   if (VT.getVectorElementCount() == ElementCount::getScalable(1))
872     report_fatal_error("Cannot legalize this vector");
873 
874   // Try to widen vector elements until the element type is a power of two and
875   // promote it to a legal type later on, for example:
876   // <3 x i8> -> <4 x i8> -> <4 x i32>
877   if (EltVT.isInteger()) {
878     // Vectors with a number of elements that is not a power of two are always
879     // widened, for example <3 x i8> -> <4 x i8>.
880     if (!VT.isPow2VectorType()) {
881       NumElts = NumElts.coefficientNextPowerOf2();
882       EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts);
883       return LegalizeKind(TypeWidenVector, NVT);
884     }
885 
886     // Examine the element type.
887     LegalizeKind LK = getTypeConversion(Context, EltVT);
888 
889     // If type is to be expanded, split the vector.
890     //  <4 x i140> -> <2 x i140>
891     if (LK.first == TypeExpandInteger)
892       return LegalizeKind(TypeSplitVector,
893                           VT.getHalfNumVectorElementsVT(Context));
894 
895     // Promote the integer element types until a legal vector type is found
896     // or until the element integer type is too big. If a legal type was not
897     // found, fallback to the usual mechanism of widening/splitting the
898     // vector.
899     EVT OldEltVT = EltVT;
900     while (true) {
901       // Increase the bitwidth of the element to the next pow-of-two
902       // (which is greater than 8 bits).
903       EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits())
904                   .getRoundIntegerType(Context);
905 
906       // Stop trying when getting a non-simple element type.
907       // Note that vector elements may be greater than legal vector element
908       // types. Example: X86 XMM registers hold 64bit element on 32bit
909       // systems.
910       if (!EltVT.isSimple())
911         break;
912 
913       // Build a new vector type and check if it is legal.
914       MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
915       // Found a legal promoted vector type.
916       if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal)
917         return LegalizeKind(TypePromoteInteger,
918                             EVT::getVectorVT(Context, EltVT, NumElts));
919     }
920 
921     // Reset the type to the unexpanded type if we did not find a legal vector
922     // type with a promoted vector element type.
923     EltVT = OldEltVT;
924   }
925 
926   // Try to widen the vector until a legal type is found.
927   // If there is no wider legal type, split the vector.
928   while (true) {
929     // Round up to the next power of 2.
930     NumElts = NumElts.coefficientNextPowerOf2();
931 
932     // If there is no simple vector type with this many elements then there
933     // cannot be a larger legal vector type.  Note that this assumes that
934     // there are no skipped intermediate vector types in the simple types.
935     if (!EltVT.isSimple())
936       break;
937     MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
938     if (LargerVector == MVT())
939       break;
940 
941     // If this type is legal then widen the vector.
942     if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal)
943       return LegalizeKind(TypeWidenVector, LargerVector);
944   }
945 
946   // Widen odd vectors to next power of two.
947   if (!VT.isPow2VectorType()) {
948     EVT NVT = VT.getPow2VectorType(Context);
949     return LegalizeKind(TypeWidenVector, NVT);
950   }
951 
952   // Vectors with illegal element types are expanded.
953   EVT NVT = EVT::getVectorVT(Context, EltVT,
954                              VT.getVectorElementCount().divideCoefficientBy(2));
955   return LegalizeKind(TypeSplitVector, NVT);
956 }
957 
958 static unsigned getVectorTypeBreakdownMVT(MVT VT, MVT &IntermediateVT,
959                                           unsigned &NumIntermediates,
960                                           MVT &RegisterVT,
961                                           TargetLoweringBase *TLI) {
962   // Figure out the right, legal destination reg to copy into.
963   ElementCount EC = VT.getVectorElementCount();
964   MVT EltTy = VT.getVectorElementType();
965 
966   unsigned NumVectorRegs = 1;
967 
968   // Scalable vectors cannot be scalarized, so splitting or widening is
969   // required.
970   if (VT.isScalableVector() && !isPowerOf2_32(EC.getKnownMinValue()))
971     llvm_unreachable(
972         "Splitting or widening of non-power-of-2 MVTs is not implemented.");
973 
974   // FIXME: We don't support non-power-of-2-sized vectors for now.
975   // Ideally we could break down into LHS/RHS like LegalizeDAG does.
976   if (!isPowerOf2_32(EC.getKnownMinValue())) {
977     // Split EC to unit size (scalable property is preserved).
978     NumVectorRegs = EC.getKnownMinValue();
979     EC = ElementCount::getFixed(1);
980   }
981 
982   // Divide the input until we get to a supported size. This will
983   // always end up with an EC that represent a scalar or a scalable
984   // scalar.
985   while (EC.getKnownMinValue() > 1 &&
986          !TLI->isTypeLegal(MVT::getVectorVT(EltTy, EC))) {
987     EC = EC.divideCoefficientBy(2);
988     NumVectorRegs <<= 1;
989   }
990 
991   NumIntermediates = NumVectorRegs;
992 
993   MVT NewVT = MVT::getVectorVT(EltTy, EC);
994   if (!TLI->isTypeLegal(NewVT))
995     NewVT = EltTy;
996   IntermediateVT = NewVT;
997 
998   unsigned LaneSizeInBits = NewVT.getScalarSizeInBits();
999 
1000   // Convert sizes such as i33 to i64.
1001   if (!isPowerOf2_32(LaneSizeInBits))
1002     LaneSizeInBits = NextPowerOf2(LaneSizeInBits);
1003 
1004   MVT DestVT = TLI->getRegisterType(NewVT);
1005   RegisterVT = DestVT;
1006   if (EVT(DestVT).bitsLT(NewVT))    // Value is expanded, e.g. i64 -> i16.
1007     return NumVectorRegs * (LaneSizeInBits / DestVT.getScalarSizeInBits());
1008 
1009   // Otherwise, promotion or legal types use the same number of registers as
1010   // the vector decimated to the appropriate level.
1011   return NumVectorRegs;
1012 }
1013 
1014 /// isLegalRC - Return true if the value types that can be represented by the
1015 /// specified register class are all legal.
1016 bool TargetLoweringBase::isLegalRC(const TargetRegisterInfo &TRI,
1017                                    const TargetRegisterClass &RC) const {
1018   for (auto I = TRI.legalclasstypes_begin(RC); *I != MVT::Other; ++I)
1019     if (isTypeLegal(*I))
1020       return true;
1021   return false;
1022 }
1023 
1024 /// Replace/modify any TargetFrameIndex operands with a targte-dependent
1025 /// sequence of memory operands that is recognized by PrologEpilogInserter.
1026 MachineBasicBlock *
1027 TargetLoweringBase::emitPatchPoint(MachineInstr &InitialMI,
1028                                    MachineBasicBlock *MBB) const {
1029   MachineInstr *MI = &InitialMI;
1030   MachineFunction &MF = *MI->getMF();
1031   MachineFrameInfo &MFI = MF.getFrameInfo();
1032 
1033   // We're handling multiple types of operands here:
1034   // PATCHPOINT MetaArgs - live-in, read only, direct
1035   // STATEPOINT Deopt Spill - live-through, read only, indirect
1036   // STATEPOINT Deopt Alloca - live-through, read only, direct
1037   // (We're currently conservative and mark the deopt slots read/write in
1038   // practice.)
1039   // STATEPOINT GC Spill - live-through, read/write, indirect
1040   // STATEPOINT GC Alloca - live-through, read/write, direct
1041   // The live-in vs live-through is handled already (the live through ones are
1042   // all stack slots), but we need to handle the different type of stackmap
1043   // operands and memory effects here.
1044 
1045   if (!llvm::any_of(MI->operands(),
1046                     [](MachineOperand &Operand) { return Operand.isFI(); }))
1047     return MBB;
1048 
1049   MachineInstrBuilder MIB = BuildMI(MF, MI->getDebugLoc(), MI->getDesc());
1050 
1051   // Inherit previous memory operands.
1052   MIB.cloneMemRefs(*MI);
1053 
1054   for (unsigned i = 0; i < MI->getNumOperands(); ++i) {
1055     MachineOperand &MO = MI->getOperand(i);
1056     if (!MO.isFI()) {
1057       // Index of Def operand this Use it tied to.
1058       // Since Defs are coming before Uses, if Use is tied, then
1059       // index of Def must be smaller that index of that Use.
1060       // Also, Defs preserve their position in new MI.
1061       unsigned TiedTo = i;
1062       if (MO.isReg() && MO.isTied())
1063         TiedTo = MI->findTiedOperandIdx(i);
1064       MIB.add(MO);
1065       if (TiedTo < i)
1066         MIB->tieOperands(TiedTo, MIB->getNumOperands() - 1);
1067       continue;
1068     }
1069 
1070     // foldMemoryOperand builds a new MI after replacing a single FI operand
1071     // with the canonical set of five x86 addressing-mode operands.
1072     int FI = MO.getIndex();
1073 
1074     // Add frame index operands recognized by stackmaps.cpp
1075     if (MFI.isStatepointSpillSlotObjectIndex(FI)) {
1076       // indirect-mem-ref tag, size, #FI, offset.
1077       // Used for spills inserted by StatepointLowering.  This codepath is not
1078       // used for patchpoints/stackmaps at all, for these spilling is done via
1079       // foldMemoryOperand callback only.
1080       assert(MI->getOpcode() == TargetOpcode::STATEPOINT && "sanity");
1081       MIB.addImm(StackMaps::IndirectMemRefOp);
1082       MIB.addImm(MFI.getObjectSize(FI));
1083       MIB.add(MO);
1084       MIB.addImm(0);
1085     } else {
1086       // direct-mem-ref tag, #FI, offset.
1087       // Used by patchpoint, and direct alloca arguments to statepoints
1088       MIB.addImm(StackMaps::DirectMemRefOp);
1089       MIB.add(MO);
1090       MIB.addImm(0);
1091     }
1092 
1093     assert(MIB->mayLoad() && "Folded a stackmap use to a non-load!");
1094 
1095     // Add a new memory operand for this FI.
1096     assert(MFI.getObjectOffset(FI) != -1);
1097 
1098     // Note: STATEPOINT MMOs are added during SelectionDAG.  STACKMAP, and
1099     // PATCHPOINT should be updated to do the same. (TODO)
1100     if (MI->getOpcode() != TargetOpcode::STATEPOINT) {
1101       auto Flags = MachineMemOperand::MOLoad;
1102       MachineMemOperand *MMO = MF.getMachineMemOperand(
1103           MachinePointerInfo::getFixedStack(MF, FI), Flags,
1104           MF.getDataLayout().getPointerSize(), MFI.getObjectAlign(FI));
1105       MIB->addMemOperand(MF, MMO);
1106     }
1107   }
1108   MBB->insert(MachineBasicBlock::iterator(MI), MIB);
1109   MI->eraseFromParent();
1110   return MBB;
1111 }
1112 
1113 MachineBasicBlock *
1114 TargetLoweringBase::emitXRayCustomEvent(MachineInstr &MI,
1115                                         MachineBasicBlock *MBB) const {
1116   assert(MI.getOpcode() == TargetOpcode::PATCHABLE_EVENT_CALL &&
1117          "Called emitXRayCustomEvent on the wrong MI!");
1118   auto &MF = *MI.getMF();
1119   auto MIB = BuildMI(MF, MI.getDebugLoc(), MI.getDesc());
1120   for (unsigned OpIdx = 0; OpIdx != MI.getNumOperands(); ++OpIdx)
1121     MIB.add(MI.getOperand(OpIdx));
1122 
1123   MBB->insert(MachineBasicBlock::iterator(MI), MIB);
1124   MI.eraseFromParent();
1125   return MBB;
1126 }
1127 
1128 MachineBasicBlock *
1129 TargetLoweringBase::emitXRayTypedEvent(MachineInstr &MI,
1130                                        MachineBasicBlock *MBB) const {
1131   assert(MI.getOpcode() == TargetOpcode::PATCHABLE_TYPED_EVENT_CALL &&
1132          "Called emitXRayTypedEvent on the wrong MI!");
1133   auto &MF = *MI.getMF();
1134   auto MIB = BuildMI(MF, MI.getDebugLoc(), MI.getDesc());
1135   for (unsigned OpIdx = 0; OpIdx != MI.getNumOperands(); ++OpIdx)
1136     MIB.add(MI.getOperand(OpIdx));
1137 
1138   MBB->insert(MachineBasicBlock::iterator(MI), MIB);
1139   MI.eraseFromParent();
1140   return MBB;
1141 }
1142 
1143 /// findRepresentativeClass - Return the largest legal super-reg register class
1144 /// of the register class for the specified type and its associated "cost".
1145 // This function is in TargetLowering because it uses RegClassForVT which would
1146 // need to be moved to TargetRegisterInfo and would necessitate moving
1147 // isTypeLegal over as well - a massive change that would just require
1148 // TargetLowering having a TargetRegisterInfo class member that it would use.
1149 std::pair<const TargetRegisterClass *, uint8_t>
1150 TargetLoweringBase::findRepresentativeClass(const TargetRegisterInfo *TRI,
1151                                             MVT VT) const {
1152   const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
1153   if (!RC)
1154     return std::make_pair(RC, 0);
1155 
1156   // Compute the set of all super-register classes.
1157   BitVector SuperRegRC(TRI->getNumRegClasses());
1158   for (SuperRegClassIterator RCI(RC, TRI); RCI.isValid(); ++RCI)
1159     SuperRegRC.setBitsInMask(RCI.getMask());
1160 
1161   // Find the first legal register class with the largest spill size.
1162   const TargetRegisterClass *BestRC = RC;
1163   for (unsigned i : SuperRegRC.set_bits()) {
1164     const TargetRegisterClass *SuperRC = TRI->getRegClass(i);
1165     // We want the largest possible spill size.
1166     if (TRI->getSpillSize(*SuperRC) <= TRI->getSpillSize(*BestRC))
1167       continue;
1168     if (!isLegalRC(*TRI, *SuperRC))
1169       continue;
1170     BestRC = SuperRC;
1171   }
1172   return std::make_pair(BestRC, 1);
1173 }
1174 
1175 /// computeRegisterProperties - Once all of the register classes are added,
1176 /// this allows us to compute derived properties we expose.
1177 void TargetLoweringBase::computeRegisterProperties(
1178     const TargetRegisterInfo *TRI) {
1179   static_assert(MVT::LAST_VALUETYPE <= MVT::MAX_ALLOWED_VALUETYPE,
1180                 "Too many value types for ValueTypeActions to hold!");
1181 
1182   // Everything defaults to needing one register.
1183   for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
1184     NumRegistersForVT[i] = 1;
1185     RegisterTypeForVT[i] = TransformToType[i] = (MVT::SimpleValueType)i;
1186   }
1187   // ...except isVoid, which doesn't need any registers.
1188   NumRegistersForVT[MVT::isVoid] = 0;
1189 
1190   // Find the largest integer register class.
1191   unsigned LargestIntReg = MVT::LAST_INTEGER_VALUETYPE;
1192   for (; RegClassForVT[LargestIntReg] == nullptr; --LargestIntReg)
1193     assert(LargestIntReg != MVT::i1 && "No integer registers defined!");
1194 
1195   // Every integer value type larger than this largest register takes twice as
1196   // many registers to represent as the previous ValueType.
1197   for (unsigned ExpandedReg = LargestIntReg + 1;
1198        ExpandedReg <= MVT::LAST_INTEGER_VALUETYPE; ++ExpandedReg) {
1199     NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1];
1200     RegisterTypeForVT[ExpandedReg] = (MVT::SimpleValueType)LargestIntReg;
1201     TransformToType[ExpandedReg] = (MVT::SimpleValueType)(ExpandedReg - 1);
1202     ValueTypeActions.setTypeAction((MVT::SimpleValueType)ExpandedReg,
1203                                    TypeExpandInteger);
1204   }
1205 
1206   // Inspect all of the ValueType's smaller than the largest integer
1207   // register to see which ones need promotion.
1208   unsigned LegalIntReg = LargestIntReg;
1209   for (unsigned IntReg = LargestIntReg - 1;
1210        IntReg >= (unsigned)MVT::i1; --IntReg) {
1211     MVT IVT = (MVT::SimpleValueType)IntReg;
1212     if (isTypeLegal(IVT)) {
1213       LegalIntReg = IntReg;
1214     } else {
1215       RegisterTypeForVT[IntReg] = TransformToType[IntReg] =
1216         (MVT::SimpleValueType)LegalIntReg;
1217       ValueTypeActions.setTypeAction(IVT, TypePromoteInteger);
1218     }
1219   }
1220 
1221   // ppcf128 type is really two f64's.
1222   if (!isTypeLegal(MVT::ppcf128)) {
1223     if (isTypeLegal(MVT::f64)) {
1224       NumRegistersForVT[MVT::ppcf128] = 2*NumRegistersForVT[MVT::f64];
1225       RegisterTypeForVT[MVT::ppcf128] = MVT::f64;
1226       TransformToType[MVT::ppcf128] = MVT::f64;
1227       ValueTypeActions.setTypeAction(MVT::ppcf128, TypeExpandFloat);
1228     } else {
1229       NumRegistersForVT[MVT::ppcf128] = NumRegistersForVT[MVT::i128];
1230       RegisterTypeForVT[MVT::ppcf128] = RegisterTypeForVT[MVT::i128];
1231       TransformToType[MVT::ppcf128] = MVT::i128;
1232       ValueTypeActions.setTypeAction(MVT::ppcf128, TypeSoftenFloat);
1233     }
1234   }
1235 
1236   // Decide how to handle f128. If the target does not have native f128 support,
1237   // expand it to i128 and we will be generating soft float library calls.
1238   if (!isTypeLegal(MVT::f128)) {
1239     NumRegistersForVT[MVT::f128] = NumRegistersForVT[MVT::i128];
1240     RegisterTypeForVT[MVT::f128] = RegisterTypeForVT[MVT::i128];
1241     TransformToType[MVT::f128] = MVT::i128;
1242     ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
1243   }
1244 
1245   // Decide how to handle f64. If the target does not have native f64 support,
1246   // expand it to i64 and we will be generating soft float library calls.
1247   if (!isTypeLegal(MVT::f64)) {
1248     NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64];
1249     RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64];
1250     TransformToType[MVT::f64] = MVT::i64;
1251     ValueTypeActions.setTypeAction(MVT::f64, TypeSoftenFloat);
1252   }
1253 
1254   // Decide how to handle f32. If the target does not have native f32 support,
1255   // expand it to i32 and we will be generating soft float library calls.
1256   if (!isTypeLegal(MVT::f32)) {
1257     NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32];
1258     RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32];
1259     TransformToType[MVT::f32] = MVT::i32;
1260     ValueTypeActions.setTypeAction(MVT::f32, TypeSoftenFloat);
1261   }
1262 
1263   // Decide how to handle f16. If the target does not have native f16 support,
1264   // promote it to f32, because there are no f16 library calls (except for
1265   // conversions).
1266   if (!isTypeLegal(MVT::f16)) {
1267     // Allow targets to control how we legalize half.
1268     if (softPromoteHalfType()) {
1269       NumRegistersForVT[MVT::f16] = NumRegistersForVT[MVT::i16];
1270       RegisterTypeForVT[MVT::f16] = RegisterTypeForVT[MVT::i16];
1271       TransformToType[MVT::f16] = MVT::f32;
1272       ValueTypeActions.setTypeAction(MVT::f16, TypeSoftPromoteHalf);
1273     } else {
1274       NumRegistersForVT[MVT::f16] = NumRegistersForVT[MVT::f32];
1275       RegisterTypeForVT[MVT::f16] = RegisterTypeForVT[MVT::f32];
1276       TransformToType[MVT::f16] = MVT::f32;
1277       ValueTypeActions.setTypeAction(MVT::f16, TypePromoteFloat);
1278     }
1279   }
1280 
1281   // Loop over all of the vector value types to see which need transformations.
1282   for (unsigned i = MVT::FIRST_VECTOR_VALUETYPE;
1283        i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1284     MVT VT = (MVT::SimpleValueType) i;
1285     if (isTypeLegal(VT))
1286       continue;
1287 
1288     MVT EltVT = VT.getVectorElementType();
1289     ElementCount EC = VT.getVectorElementCount();
1290     bool IsLegalWiderType = false;
1291     bool IsScalable = VT.isScalableVector();
1292     LegalizeTypeAction PreferredAction = getPreferredVectorAction(VT);
1293     switch (PreferredAction) {
1294     case TypePromoteInteger: {
1295       MVT::SimpleValueType EndVT = IsScalable ?
1296                                    MVT::LAST_INTEGER_SCALABLE_VECTOR_VALUETYPE :
1297                                    MVT::LAST_INTEGER_FIXEDLEN_VECTOR_VALUETYPE;
1298       // Try to promote the elements of integer vectors. If no legal
1299       // promotion was found, fall through to the widen-vector method.
1300       for (unsigned nVT = i + 1;
1301            (MVT::SimpleValueType)nVT <= EndVT; ++nVT) {
1302         MVT SVT = (MVT::SimpleValueType) nVT;
1303         // Promote vectors of integers to vectors with the same number
1304         // of elements, with a wider element type.
1305         if (SVT.getScalarSizeInBits() > EltVT.getFixedSizeInBits() &&
1306             SVT.getVectorElementCount() == EC && isTypeLegal(SVT)) {
1307           TransformToType[i] = SVT;
1308           RegisterTypeForVT[i] = SVT;
1309           NumRegistersForVT[i] = 1;
1310           ValueTypeActions.setTypeAction(VT, TypePromoteInteger);
1311           IsLegalWiderType = true;
1312           break;
1313         }
1314       }
1315       if (IsLegalWiderType)
1316         break;
1317       LLVM_FALLTHROUGH;
1318     }
1319 
1320     case TypeWidenVector:
1321       if (isPowerOf2_32(EC.getKnownMinValue())) {
1322         // Try to widen the vector.
1323         for (unsigned nVT = i + 1; nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
1324           MVT SVT = (MVT::SimpleValueType) nVT;
1325           if (SVT.getVectorElementType() == EltVT &&
1326               SVT.isScalableVector() == IsScalable &&
1327               SVT.getVectorElementCount().getKnownMinValue() >
1328                   EC.getKnownMinValue() &&
1329               isTypeLegal(SVT)) {
1330             TransformToType[i] = SVT;
1331             RegisterTypeForVT[i] = SVT;
1332             NumRegistersForVT[i] = 1;
1333             ValueTypeActions.setTypeAction(VT, TypeWidenVector);
1334             IsLegalWiderType = true;
1335             break;
1336           }
1337         }
1338         if (IsLegalWiderType)
1339           break;
1340       } else {
1341         // Only widen to the next power of 2 to keep consistency with EVT.
1342         MVT NVT = VT.getPow2VectorType();
1343         if (isTypeLegal(NVT)) {
1344           TransformToType[i] = NVT;
1345           ValueTypeActions.setTypeAction(VT, TypeWidenVector);
1346           RegisterTypeForVT[i] = NVT;
1347           NumRegistersForVT[i] = 1;
1348           break;
1349         }
1350       }
1351       LLVM_FALLTHROUGH;
1352 
1353     case TypeSplitVector:
1354     case TypeScalarizeVector: {
1355       MVT IntermediateVT;
1356       MVT RegisterVT;
1357       unsigned NumIntermediates;
1358       unsigned NumRegisters = getVectorTypeBreakdownMVT(VT, IntermediateVT,
1359           NumIntermediates, RegisterVT, this);
1360       NumRegistersForVT[i] = NumRegisters;
1361       assert(NumRegistersForVT[i] == NumRegisters &&
1362              "NumRegistersForVT size cannot represent NumRegisters!");
1363       RegisterTypeForVT[i] = RegisterVT;
1364 
1365       MVT NVT = VT.getPow2VectorType();
1366       if (NVT == VT) {
1367         // Type is already a power of 2.  The default action is to split.
1368         TransformToType[i] = MVT::Other;
1369         if (PreferredAction == TypeScalarizeVector)
1370           ValueTypeActions.setTypeAction(VT, TypeScalarizeVector);
1371         else if (PreferredAction == TypeSplitVector)
1372           ValueTypeActions.setTypeAction(VT, TypeSplitVector);
1373         else if (EC.getKnownMinValue() > 1)
1374           ValueTypeActions.setTypeAction(VT, TypeSplitVector);
1375         else
1376           ValueTypeActions.setTypeAction(VT, EC.isScalable()
1377                                                  ? TypeScalarizeScalableVector
1378                                                  : TypeScalarizeVector);
1379       } else {
1380         TransformToType[i] = NVT;
1381         ValueTypeActions.setTypeAction(VT, TypeWidenVector);
1382       }
1383       break;
1384     }
1385     default:
1386       llvm_unreachable("Unknown vector legalization action!");
1387     }
1388   }
1389 
1390   // Determine the 'representative' register class for each value type.
1391   // An representative register class is the largest (meaning one which is
1392   // not a sub-register class / subreg register class) legal register class for
1393   // a group of value types. For example, on i386, i8, i16, and i32
1394   // representative would be GR32; while on x86_64 it's GR64.
1395   for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
1396     const TargetRegisterClass* RRC;
1397     uint8_t Cost;
1398     std::tie(RRC, Cost) = findRepresentativeClass(TRI, (MVT::SimpleValueType)i);
1399     RepRegClassForVT[i] = RRC;
1400     RepRegClassCostForVT[i] = Cost;
1401   }
1402 }
1403 
1404 EVT TargetLoweringBase::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1405                                            EVT VT) const {
1406   assert(!VT.isVector() && "No default SetCC type for vectors!");
1407   return getPointerTy(DL).SimpleTy;
1408 }
1409 
1410 MVT::SimpleValueType TargetLoweringBase::getCmpLibcallReturnType() const {
1411   return MVT::i32; // return the default value
1412 }
1413 
1414 /// getVectorTypeBreakdown - Vector types are broken down into some number of
1415 /// legal first class types.  For example, MVT::v8f32 maps to 2 MVT::v4f32
1416 /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
1417 /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
1418 ///
1419 /// This method returns the number of registers needed, and the VT for each
1420 /// register.  It also returns the VT and quantity of the intermediate values
1421 /// before they are promoted/expanded.
1422 unsigned TargetLoweringBase::getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
1423                                                 EVT &IntermediateVT,
1424                                                 unsigned &NumIntermediates,
1425                                                 MVT &RegisterVT) const {
1426   ElementCount EltCnt = VT.getVectorElementCount();
1427 
1428   // If there is a wider vector type with the same element type as this one,
1429   // or a promoted vector type that has the same number of elements which
1430   // are wider, then we should convert to that legal vector type.
1431   // This handles things like <2 x float> -> <4 x float> and
1432   // <4 x i1> -> <4 x i32>.
1433   LegalizeTypeAction TA = getTypeAction(Context, VT);
1434   if (EltCnt.getKnownMinValue() != 1 &&
1435       (TA == TypeWidenVector || TA == TypePromoteInteger)) {
1436     EVT RegisterEVT = getTypeToTransformTo(Context, VT);
1437     if (isTypeLegal(RegisterEVT)) {
1438       IntermediateVT = RegisterEVT;
1439       RegisterVT = RegisterEVT.getSimpleVT();
1440       NumIntermediates = 1;
1441       return 1;
1442     }
1443   }
1444 
1445   // Figure out the right, legal destination reg to copy into.
1446   EVT EltTy = VT.getVectorElementType();
1447 
1448   unsigned NumVectorRegs = 1;
1449 
1450   // Scalable vectors cannot be scalarized, so handle the legalisation of the
1451   // types like done elsewhere in SelectionDAG.
1452   if (VT.isScalableVector() && !isPowerOf2_32(EltCnt.getKnownMinValue())) {
1453     LegalizeKind LK;
1454     EVT PartVT = VT;
1455     do {
1456       // Iterate until we've found a legal (part) type to hold VT.
1457       LK = getTypeConversion(Context, PartVT);
1458       PartVT = LK.second;
1459     } while (LK.first != TypeLegal);
1460 
1461     NumIntermediates = VT.getVectorElementCount().getKnownMinValue() /
1462                        PartVT.getVectorElementCount().getKnownMinValue();
1463 
1464     // FIXME: This code needs to be extended to handle more complex vector
1465     // breakdowns, like nxv7i64 -> nxv8i64 -> 4 x nxv2i64. Currently the only
1466     // supported cases are vectors that are broken down into equal parts
1467     // such as nxv6i64 -> 3 x nxv2i64.
1468     assert((PartVT.getVectorElementCount() * NumIntermediates) ==
1469                VT.getVectorElementCount() &&
1470            "Expected an integer multiple of PartVT");
1471     IntermediateVT = PartVT;
1472     RegisterVT = getRegisterType(Context, IntermediateVT);
1473     return NumIntermediates;
1474   }
1475 
1476   // FIXME: We don't support non-power-of-2-sized vectors for now.  Ideally
1477   // we could break down into LHS/RHS like LegalizeDAG does.
1478   if (!isPowerOf2_32(EltCnt.getKnownMinValue())) {
1479     NumVectorRegs = EltCnt.getKnownMinValue();
1480     EltCnt = ElementCount::getFixed(1);
1481   }
1482 
1483   // Divide the input until we get to a supported size.  This will always
1484   // end with a scalar if the target doesn't support vectors.
1485   while (EltCnt.getKnownMinValue() > 1 &&
1486          !isTypeLegal(EVT::getVectorVT(Context, EltTy, EltCnt))) {
1487     EltCnt = EltCnt.divideCoefficientBy(2);
1488     NumVectorRegs <<= 1;
1489   }
1490 
1491   NumIntermediates = NumVectorRegs;
1492 
1493   EVT NewVT = EVT::getVectorVT(Context, EltTy, EltCnt);
1494   if (!isTypeLegal(NewVT))
1495     NewVT = EltTy;
1496   IntermediateVT = NewVT;
1497 
1498   MVT DestVT = getRegisterType(Context, NewVT);
1499   RegisterVT = DestVT;
1500 
1501   if (EVT(DestVT).bitsLT(NewVT)) {  // Value is expanded, e.g. i64 -> i16.
1502     TypeSize NewVTSize = NewVT.getSizeInBits();
1503     // Convert sizes such as i33 to i64.
1504     if (!isPowerOf2_32(NewVTSize.getKnownMinSize()))
1505       NewVTSize = NewVTSize.coefficientNextPowerOf2();
1506     return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits());
1507   }
1508 
1509   // Otherwise, promotion or legal types use the same number of registers as
1510   // the vector decimated to the appropriate level.
1511   return NumVectorRegs;
1512 }
1513 
1514 bool TargetLoweringBase::isSuitableForJumpTable(const SwitchInst *SI,
1515                                                 uint64_t NumCases,
1516                                                 uint64_t Range,
1517                                                 ProfileSummaryInfo *PSI,
1518                                                 BlockFrequencyInfo *BFI) const {
1519   // FIXME: This function check the maximum table size and density, but the
1520   // minimum size is not checked. It would be nice if the minimum size is
1521   // also combined within this function. Currently, the minimum size check is
1522   // performed in findJumpTable() in SelectionDAGBuiler and
1523   // getEstimatedNumberOfCaseClusters() in BasicTTIImpl.
1524   const bool OptForSize =
1525       SI->getParent()->getParent()->hasOptSize() ||
1526       llvm::shouldOptimizeForSize(SI->getParent(), PSI, BFI);
1527   const unsigned MinDensity = getMinimumJumpTableDensity(OptForSize);
1528   const unsigned MaxJumpTableSize = getMaximumJumpTableSize();
1529 
1530   // Check whether the number of cases is small enough and
1531   // the range is dense enough for a jump table.
1532   return (OptForSize || Range <= MaxJumpTableSize) &&
1533          (NumCases * 100 >= Range * MinDensity);
1534 }
1535 
1536 /// Get the EVTs and ArgFlags collections that represent the legalized return
1537 /// type of the given function.  This does not require a DAG or a return value,
1538 /// and is suitable for use before any DAGs for the function are constructed.
1539 /// TODO: Move this out of TargetLowering.cpp.
1540 void llvm::GetReturnInfo(CallingConv::ID CC, Type *ReturnType,
1541                          AttributeList attr,
1542                          SmallVectorImpl<ISD::OutputArg> &Outs,
1543                          const TargetLowering &TLI, const DataLayout &DL) {
1544   SmallVector<EVT, 4> ValueVTs;
1545   ComputeValueVTs(TLI, DL, ReturnType, ValueVTs);
1546   unsigned NumValues = ValueVTs.size();
1547   if (NumValues == 0) return;
1548 
1549   for (unsigned j = 0, f = NumValues; j != f; ++j) {
1550     EVT VT = ValueVTs[j];
1551     ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1552 
1553     if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt))
1554       ExtendKind = ISD::SIGN_EXTEND;
1555     else if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt))
1556       ExtendKind = ISD::ZERO_EXTEND;
1557 
1558     // FIXME: C calling convention requires the return type to be promoted to
1559     // at least 32-bit. But this is not necessary for non-C calling
1560     // conventions. The frontend should mark functions whose return values
1561     // require promoting with signext or zeroext attributes.
1562     if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
1563       MVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
1564       if (VT.bitsLT(MinVT))
1565         VT = MinVT;
1566     }
1567 
1568     unsigned NumParts =
1569         TLI.getNumRegistersForCallingConv(ReturnType->getContext(), CC, VT);
1570     MVT PartVT =
1571         TLI.getRegisterTypeForCallingConv(ReturnType->getContext(), CC, VT);
1572 
1573     // 'inreg' on function refers to return value
1574     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1575     if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::InReg))
1576       Flags.setInReg();
1577 
1578     // Propagate extension type if any
1579     if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt))
1580       Flags.setSExt();
1581     else if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt))
1582       Flags.setZExt();
1583 
1584     for (unsigned i = 0; i < NumParts; ++i)
1585       Outs.push_back(ISD::OutputArg(Flags, PartVT, VT, /*isfixed=*/true, 0, 0));
1586   }
1587 }
1588 
1589 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1590 /// function arguments in the caller parameter area.  This is the actual
1591 /// alignment, not its logarithm.
1592 unsigned TargetLoweringBase::getByValTypeAlignment(Type *Ty,
1593                                                    const DataLayout &DL) const {
1594   return DL.getABITypeAlign(Ty).value();
1595 }
1596 
1597 bool TargetLoweringBase::allowsMemoryAccessForAlignment(
1598     LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace,
1599     Align Alignment, MachineMemOperand::Flags Flags, bool *Fast) const {
1600   // Check if the specified alignment is sufficient based on the data layout.
1601   // TODO: While using the data layout works in practice, a better solution
1602   // would be to implement this check directly (make this a virtual function).
1603   // For example, the ABI alignment may change based on software platform while
1604   // this function should only be affected by hardware implementation.
1605   Type *Ty = VT.getTypeForEVT(Context);
1606   if (Alignment >= DL.getABITypeAlign(Ty)) {
1607     // Assume that an access that meets the ABI-specified alignment is fast.
1608     if (Fast != nullptr)
1609       *Fast = true;
1610     return true;
1611   }
1612 
1613   // This is a misaligned access.
1614   return allowsMisalignedMemoryAccesses(VT, AddrSpace, Alignment.value(), Flags,
1615                                         Fast);
1616 }
1617 
1618 bool TargetLoweringBase::allowsMemoryAccessForAlignment(
1619     LLVMContext &Context, const DataLayout &DL, EVT VT,
1620     const MachineMemOperand &MMO, bool *Fast) const {
1621   return allowsMemoryAccessForAlignment(Context, DL, VT, MMO.getAddrSpace(),
1622                                         MMO.getAlign(), MMO.getFlags(), Fast);
1623 }
1624 
1625 bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context,
1626                                             const DataLayout &DL, EVT VT,
1627                                             unsigned AddrSpace, Align Alignment,
1628                                             MachineMemOperand::Flags Flags,
1629                                             bool *Fast) const {
1630   return allowsMemoryAccessForAlignment(Context, DL, VT, AddrSpace, Alignment,
1631                                         Flags, Fast);
1632 }
1633 
1634 bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context,
1635                                             const DataLayout &DL, EVT VT,
1636                                             const MachineMemOperand &MMO,
1637                                             bool *Fast) const {
1638   return allowsMemoryAccess(Context, DL, VT, MMO.getAddrSpace(), MMO.getAlign(),
1639                             MMO.getFlags(), Fast);
1640 }
1641 
1642 BranchProbability TargetLoweringBase::getPredictableBranchThreshold() const {
1643   return BranchProbability(MinPercentageForPredictableBranch, 100);
1644 }
1645 
1646 //===----------------------------------------------------------------------===//
1647 //  TargetTransformInfo Helpers
1648 //===----------------------------------------------------------------------===//
1649 
1650 int TargetLoweringBase::InstructionOpcodeToISD(unsigned Opcode) const {
1651   enum InstructionOpcodes {
1652 #define HANDLE_INST(NUM, OPCODE, CLASS) OPCODE = NUM,
1653 #define LAST_OTHER_INST(NUM) InstructionOpcodesCount = NUM
1654 #include "llvm/IR/Instruction.def"
1655   };
1656   switch (static_cast<InstructionOpcodes>(Opcode)) {
1657   case Ret:            return 0;
1658   case Br:             return 0;
1659   case Switch:         return 0;
1660   case IndirectBr:     return 0;
1661   case Invoke:         return 0;
1662   case CallBr:         return 0;
1663   case Resume:         return 0;
1664   case Unreachable:    return 0;
1665   case CleanupRet:     return 0;
1666   case CatchRet:       return 0;
1667   case CatchPad:       return 0;
1668   case CatchSwitch:    return 0;
1669   case CleanupPad:     return 0;
1670   case FNeg:           return ISD::FNEG;
1671   case Add:            return ISD::ADD;
1672   case FAdd:           return ISD::FADD;
1673   case Sub:            return ISD::SUB;
1674   case FSub:           return ISD::FSUB;
1675   case Mul:            return ISD::MUL;
1676   case FMul:           return ISD::FMUL;
1677   case UDiv:           return ISD::UDIV;
1678   case SDiv:           return ISD::SDIV;
1679   case FDiv:           return ISD::FDIV;
1680   case URem:           return ISD::UREM;
1681   case SRem:           return ISD::SREM;
1682   case FRem:           return ISD::FREM;
1683   case Shl:            return ISD::SHL;
1684   case LShr:           return ISD::SRL;
1685   case AShr:           return ISD::SRA;
1686   case And:            return ISD::AND;
1687   case Or:             return ISD::OR;
1688   case Xor:            return ISD::XOR;
1689   case Alloca:         return 0;
1690   case Load:           return ISD::LOAD;
1691   case Store:          return ISD::STORE;
1692   case GetElementPtr:  return 0;
1693   case Fence:          return 0;
1694   case AtomicCmpXchg:  return 0;
1695   case AtomicRMW:      return 0;
1696   case Trunc:          return ISD::TRUNCATE;
1697   case ZExt:           return ISD::ZERO_EXTEND;
1698   case SExt:           return ISD::SIGN_EXTEND;
1699   case FPToUI:         return ISD::FP_TO_UINT;
1700   case FPToSI:         return ISD::FP_TO_SINT;
1701   case UIToFP:         return ISD::UINT_TO_FP;
1702   case SIToFP:         return ISD::SINT_TO_FP;
1703   case FPTrunc:        return ISD::FP_ROUND;
1704   case FPExt:          return ISD::FP_EXTEND;
1705   case PtrToInt:       return ISD::BITCAST;
1706   case IntToPtr:       return ISD::BITCAST;
1707   case BitCast:        return ISD::BITCAST;
1708   case AddrSpaceCast:  return ISD::ADDRSPACECAST;
1709   case ICmp:           return ISD::SETCC;
1710   case FCmp:           return ISD::SETCC;
1711   case PHI:            return 0;
1712   case Call:           return 0;
1713   case Select:         return ISD::SELECT;
1714   case UserOp1:        return 0;
1715   case UserOp2:        return 0;
1716   case VAArg:          return 0;
1717   case ExtractElement: return ISD::EXTRACT_VECTOR_ELT;
1718   case InsertElement:  return ISD::INSERT_VECTOR_ELT;
1719   case ShuffleVector:  return ISD::VECTOR_SHUFFLE;
1720   case ExtractValue:   return ISD::MERGE_VALUES;
1721   case InsertValue:    return ISD::MERGE_VALUES;
1722   case LandingPad:     return 0;
1723   case Freeze:         return ISD::FREEZE;
1724   }
1725 
1726   llvm_unreachable("Unknown instruction type encountered!");
1727 }
1728 
1729 std::pair<int, MVT>
1730 TargetLoweringBase::getTypeLegalizationCost(const DataLayout &DL,
1731                                             Type *Ty) const {
1732   LLVMContext &C = Ty->getContext();
1733   EVT MTy = getValueType(DL, Ty);
1734 
1735   int Cost = 1;
1736   // We keep legalizing the type until we find a legal kind. We assume that
1737   // the only operation that costs anything is the split. After splitting
1738   // we need to handle two types.
1739   while (true) {
1740     LegalizeKind LK = getTypeConversion(C, MTy);
1741 
1742     if (LK.first == TypeLegal)
1743       return std::make_pair(Cost, MTy.getSimpleVT());
1744 
1745     if (LK.first == TypeSplitVector || LK.first == TypeExpandInteger)
1746       Cost *= 2;
1747 
1748     // Do not loop with f128 type.
1749     if (MTy == LK.second)
1750       return std::make_pair(Cost, MTy.getSimpleVT());
1751 
1752     // Keep legalizing the type.
1753     MTy = LK.second;
1754   }
1755 }
1756 
1757 Value *TargetLoweringBase::getDefaultSafeStackPointerLocation(IRBuilder<> &IRB,
1758                                                               bool UseTLS) const {
1759   // compiler-rt provides a variable with a magic name.  Targets that do not
1760   // link with compiler-rt may also provide such a variable.
1761   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
1762   const char *UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr";
1763   auto UnsafeStackPtr =
1764       dyn_cast_or_null<GlobalVariable>(M->getNamedValue(UnsafeStackPtrVar));
1765 
1766   Type *StackPtrTy = Type::getInt8PtrTy(M->getContext());
1767 
1768   if (!UnsafeStackPtr) {
1769     auto TLSModel = UseTLS ?
1770         GlobalValue::InitialExecTLSModel :
1771         GlobalValue::NotThreadLocal;
1772     // The global variable is not defined yet, define it ourselves.
1773     // We use the initial-exec TLS model because we do not support the
1774     // variable living anywhere other than in the main executable.
1775     UnsafeStackPtr = new GlobalVariable(
1776         *M, StackPtrTy, false, GlobalValue::ExternalLinkage, nullptr,
1777         UnsafeStackPtrVar, nullptr, TLSModel);
1778   } else {
1779     // The variable exists, check its type and attributes.
1780     if (UnsafeStackPtr->getValueType() != StackPtrTy)
1781       report_fatal_error(Twine(UnsafeStackPtrVar) + " must have void* type");
1782     if (UseTLS != UnsafeStackPtr->isThreadLocal())
1783       report_fatal_error(Twine(UnsafeStackPtrVar) + " must " +
1784                          (UseTLS ? "" : "not ") + "be thread-local");
1785   }
1786   return UnsafeStackPtr;
1787 }
1788 
1789 Value *TargetLoweringBase::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
1790   if (!TM.getTargetTriple().isAndroid())
1791     return getDefaultSafeStackPointerLocation(IRB, true);
1792 
1793   // Android provides a libc function to retrieve the address of the current
1794   // thread's unsafe stack pointer.
1795   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
1796   Type *StackPtrTy = Type::getInt8PtrTy(M->getContext());
1797   FunctionCallee Fn = M->getOrInsertFunction("__safestack_pointer_address",
1798                                              StackPtrTy->getPointerTo(0));
1799   return IRB.CreateCall(Fn);
1800 }
1801 
1802 //===----------------------------------------------------------------------===//
1803 //  Loop Strength Reduction hooks
1804 //===----------------------------------------------------------------------===//
1805 
1806 /// isLegalAddressingMode - Return true if the addressing mode represented
1807 /// by AM is legal for this target, for a load/store of the specified type.
1808 bool TargetLoweringBase::isLegalAddressingMode(const DataLayout &DL,
1809                                                const AddrMode &AM, Type *Ty,
1810                                                unsigned AS, Instruction *I) const {
1811   // The default implementation of this implements a conservative RISCy, r+r and
1812   // r+i addr mode.
1813 
1814   // Allows a sign-extended 16-bit immediate field.
1815   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
1816     return false;
1817 
1818   // No global is ever allowed as a base.
1819   if (AM.BaseGV)
1820     return false;
1821 
1822   // Only support r+r,
1823   switch (AM.Scale) {
1824   case 0:  // "r+i" or just "i", depending on HasBaseReg.
1825     break;
1826   case 1:
1827     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
1828       return false;
1829     // Otherwise we have r+r or r+i.
1830     break;
1831   case 2:
1832     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
1833       return false;
1834     // Allow 2*r as r+r.
1835     break;
1836   default: // Don't allow n * r
1837     return false;
1838   }
1839 
1840   return true;
1841 }
1842 
1843 //===----------------------------------------------------------------------===//
1844 //  Stack Protector
1845 //===----------------------------------------------------------------------===//
1846 
1847 // For OpenBSD return its special guard variable. Otherwise return nullptr,
1848 // so that SelectionDAG handle SSP.
1849 Value *TargetLoweringBase::getIRStackGuard(IRBuilder<> &IRB) const {
1850   if (getTargetMachine().getTargetTriple().isOSOpenBSD()) {
1851     Module &M = *IRB.GetInsertBlock()->getParent()->getParent();
1852     PointerType *PtrTy = Type::getInt8PtrTy(M.getContext());
1853     Constant *C = M.getOrInsertGlobal("__guard_local", PtrTy);
1854     if (GlobalVariable *G = dyn_cast_or_null<GlobalVariable>(C))
1855       G->setVisibility(GlobalValue::HiddenVisibility);
1856     return C;
1857   }
1858   return nullptr;
1859 }
1860 
1861 // Currently only support "standard" __stack_chk_guard.
1862 // TODO: add LOAD_STACK_GUARD support.
1863 void TargetLoweringBase::insertSSPDeclarations(Module &M) const {
1864   if (!M.getNamedValue("__stack_chk_guard"))
1865     new GlobalVariable(M, Type::getInt8PtrTy(M.getContext()), false,
1866                        GlobalVariable::ExternalLinkage,
1867                        nullptr, "__stack_chk_guard");
1868 }
1869 
1870 // Currently only support "standard" __stack_chk_guard.
1871 // TODO: add LOAD_STACK_GUARD support.
1872 Value *TargetLoweringBase::getSDagStackGuard(const Module &M) const {
1873   return M.getNamedValue("__stack_chk_guard");
1874 }
1875 
1876 Function *TargetLoweringBase::getSSPStackGuardCheck(const Module &M) const {
1877   return nullptr;
1878 }
1879 
1880 unsigned TargetLoweringBase::getMinimumJumpTableEntries() const {
1881   return MinimumJumpTableEntries;
1882 }
1883 
1884 void TargetLoweringBase::setMinimumJumpTableEntries(unsigned Val) {
1885   MinimumJumpTableEntries = Val;
1886 }
1887 
1888 unsigned TargetLoweringBase::getMinimumJumpTableDensity(bool OptForSize) const {
1889   return OptForSize ? OptsizeJumpTableDensity : JumpTableDensity;
1890 }
1891 
1892 unsigned TargetLoweringBase::getMaximumJumpTableSize() const {
1893   return MaximumJumpTableSize;
1894 }
1895 
1896 void TargetLoweringBase::setMaximumJumpTableSize(unsigned Val) {
1897   MaximumJumpTableSize = Val;
1898 }
1899 
1900 bool TargetLoweringBase::isJumpTableRelative() const {
1901   return getTargetMachine().isPositionIndependent();
1902 }
1903 
1904 //===----------------------------------------------------------------------===//
1905 //  Reciprocal Estimates
1906 //===----------------------------------------------------------------------===//
1907 
1908 /// Get the reciprocal estimate attribute string for a function that will
1909 /// override the target defaults.
1910 static StringRef getRecipEstimateForFunc(MachineFunction &MF) {
1911   const Function &F = MF.getFunction();
1912   return F.getFnAttribute("reciprocal-estimates").getValueAsString();
1913 }
1914 
1915 /// Construct a string for the given reciprocal operation of the given type.
1916 /// This string should match the corresponding option to the front-end's
1917 /// "-mrecip" flag assuming those strings have been passed through in an
1918 /// attribute string. For example, "vec-divf" for a division of a vXf32.
1919 static std::string getReciprocalOpName(bool IsSqrt, EVT VT) {
1920   std::string Name = VT.isVector() ? "vec-" : "";
1921 
1922   Name += IsSqrt ? "sqrt" : "div";
1923 
1924   // TODO: Handle "half" or other float types?
1925   if (VT.getScalarType() == MVT::f64) {
1926     Name += "d";
1927   } else {
1928     assert(VT.getScalarType() == MVT::f32 &&
1929            "Unexpected FP type for reciprocal estimate");
1930     Name += "f";
1931   }
1932 
1933   return Name;
1934 }
1935 
1936 /// Return the character position and value (a single numeric character) of a
1937 /// customized refinement operation in the input string if it exists. Return
1938 /// false if there is no customized refinement step count.
1939 static bool parseRefinementStep(StringRef In, size_t &Position,
1940                                 uint8_t &Value) {
1941   const char RefStepToken = ':';
1942   Position = In.find(RefStepToken);
1943   if (Position == StringRef::npos)
1944     return false;
1945 
1946   StringRef RefStepString = In.substr(Position + 1);
1947   // Allow exactly one numeric character for the additional refinement
1948   // step parameter.
1949   if (RefStepString.size() == 1) {
1950     char RefStepChar = RefStepString[0];
1951     if (RefStepChar >= '0' && RefStepChar <= '9') {
1952       Value = RefStepChar - '0';
1953       return true;
1954     }
1955   }
1956   report_fatal_error("Invalid refinement step for -recip.");
1957 }
1958 
1959 /// For the input attribute string, return one of the ReciprocalEstimate enum
1960 /// status values (enabled, disabled, or not specified) for this operation on
1961 /// the specified data type.
1962 static int getOpEnabled(bool IsSqrt, EVT VT, StringRef Override) {
1963   if (Override.empty())
1964     return TargetLoweringBase::ReciprocalEstimate::Unspecified;
1965 
1966   SmallVector<StringRef, 4> OverrideVector;
1967   Override.split(OverrideVector, ',');
1968   unsigned NumArgs = OverrideVector.size();
1969 
1970   // Check if "all", "none", or "default" was specified.
1971   if (NumArgs == 1) {
1972     // Look for an optional setting of the number of refinement steps needed
1973     // for this type of reciprocal operation.
1974     size_t RefPos;
1975     uint8_t RefSteps;
1976     if (parseRefinementStep(Override, RefPos, RefSteps)) {
1977       // Split the string for further processing.
1978       Override = Override.substr(0, RefPos);
1979     }
1980 
1981     // All reciprocal types are enabled.
1982     if (Override == "all")
1983       return TargetLoweringBase::ReciprocalEstimate::Enabled;
1984 
1985     // All reciprocal types are disabled.
1986     if (Override == "none")
1987       return TargetLoweringBase::ReciprocalEstimate::Disabled;
1988 
1989     // Target defaults for enablement are used.
1990     if (Override == "default")
1991       return TargetLoweringBase::ReciprocalEstimate::Unspecified;
1992   }
1993 
1994   // The attribute string may omit the size suffix ('f'/'d').
1995   std::string VTName = getReciprocalOpName(IsSqrt, VT);
1996   std::string VTNameNoSize = VTName;
1997   VTNameNoSize.pop_back();
1998   static const char DisabledPrefix = '!';
1999 
2000   for (StringRef RecipType : OverrideVector) {
2001     size_t RefPos;
2002     uint8_t RefSteps;
2003     if (parseRefinementStep(RecipType, RefPos, RefSteps))
2004       RecipType = RecipType.substr(0, RefPos);
2005 
2006     // Ignore the disablement token for string matching.
2007     bool IsDisabled = RecipType[0] == DisabledPrefix;
2008     if (IsDisabled)
2009       RecipType = RecipType.substr(1);
2010 
2011     if (RecipType.equals(VTName) || RecipType.equals(VTNameNoSize))
2012       return IsDisabled ? TargetLoweringBase::ReciprocalEstimate::Disabled
2013                         : TargetLoweringBase::ReciprocalEstimate::Enabled;
2014   }
2015 
2016   return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2017 }
2018 
2019 /// For the input attribute string, return the customized refinement step count
2020 /// for this operation on the specified data type. If the step count does not
2021 /// exist, return the ReciprocalEstimate enum value for unspecified.
2022 static int getOpRefinementSteps(bool IsSqrt, EVT VT, StringRef Override) {
2023   if (Override.empty())
2024     return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2025 
2026   SmallVector<StringRef, 4> OverrideVector;
2027   Override.split(OverrideVector, ',');
2028   unsigned NumArgs = OverrideVector.size();
2029 
2030   // Check if "all", "default", or "none" was specified.
2031   if (NumArgs == 1) {
2032     // Look for an optional setting of the number of refinement steps needed
2033     // for this type of reciprocal operation.
2034     size_t RefPos;
2035     uint8_t RefSteps;
2036     if (!parseRefinementStep(Override, RefPos, RefSteps))
2037       return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2038 
2039     // Split the string for further processing.
2040     Override = Override.substr(0, RefPos);
2041     assert(Override != "none" &&
2042            "Disabled reciprocals, but specifed refinement steps?");
2043 
2044     // If this is a general override, return the specified number of steps.
2045     if (Override == "all" || Override == "default")
2046       return RefSteps;
2047   }
2048 
2049   // The attribute string may omit the size suffix ('f'/'d').
2050   std::string VTName = getReciprocalOpName(IsSqrt, VT);
2051   std::string VTNameNoSize = VTName;
2052   VTNameNoSize.pop_back();
2053 
2054   for (StringRef RecipType : OverrideVector) {
2055     size_t RefPos;
2056     uint8_t RefSteps;
2057     if (!parseRefinementStep(RecipType, RefPos, RefSteps))
2058       continue;
2059 
2060     RecipType = RecipType.substr(0, RefPos);
2061     if (RecipType.equals(VTName) || RecipType.equals(VTNameNoSize))
2062       return RefSteps;
2063   }
2064 
2065   return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2066 }
2067 
2068 int TargetLoweringBase::getRecipEstimateSqrtEnabled(EVT VT,
2069                                                     MachineFunction &MF) const {
2070   return getOpEnabled(true, VT, getRecipEstimateForFunc(MF));
2071 }
2072 
2073 int TargetLoweringBase::getRecipEstimateDivEnabled(EVT VT,
2074                                                    MachineFunction &MF) const {
2075   return getOpEnabled(false, VT, getRecipEstimateForFunc(MF));
2076 }
2077 
2078 int TargetLoweringBase::getSqrtRefinementSteps(EVT VT,
2079                                                MachineFunction &MF) const {
2080   return getOpRefinementSteps(true, VT, getRecipEstimateForFunc(MF));
2081 }
2082 
2083 int TargetLoweringBase::getDivRefinementSteps(EVT VT,
2084                                               MachineFunction &MF) const {
2085   return getOpRefinementSteps(false, VT, getRecipEstimateForFunc(MF));
2086 }
2087 
2088 void TargetLoweringBase::finalizeLowering(MachineFunction &MF) const {
2089   MF.getRegInfo().freezeReservedRegs(MF);
2090 }
2091 
2092 MachineMemOperand::Flags
2093 TargetLoweringBase::getLoadMemOperandFlags(const LoadInst &LI,
2094                                            const DataLayout &DL) const {
2095   MachineMemOperand::Flags Flags = MachineMemOperand::MOLoad;
2096   if (LI.isVolatile())
2097     Flags |= MachineMemOperand::MOVolatile;
2098 
2099   if (LI.hasMetadata(LLVMContext::MD_nontemporal))
2100     Flags |= MachineMemOperand::MONonTemporal;
2101 
2102   if (LI.hasMetadata(LLVMContext::MD_invariant_load))
2103     Flags |= MachineMemOperand::MOInvariant;
2104 
2105   if (isDereferenceablePointer(LI.getPointerOperand(), LI.getType(), DL))
2106     Flags |= MachineMemOperand::MODereferenceable;
2107 
2108   Flags |= getTargetMMOFlags(LI);
2109   return Flags;
2110 }
2111 
2112 MachineMemOperand::Flags
2113 TargetLoweringBase::getStoreMemOperandFlags(const StoreInst &SI,
2114                                             const DataLayout &DL) const {
2115   MachineMemOperand::Flags Flags = MachineMemOperand::MOStore;
2116 
2117   if (SI.isVolatile())
2118     Flags |= MachineMemOperand::MOVolatile;
2119 
2120   if (SI.hasMetadata(LLVMContext::MD_nontemporal))
2121     Flags |= MachineMemOperand::MONonTemporal;
2122 
2123   // FIXME: Not preserving dereferenceable
2124   Flags |= getTargetMMOFlags(SI);
2125   return Flags;
2126 }
2127 
2128 MachineMemOperand::Flags
2129 TargetLoweringBase::getAtomicMemOperandFlags(const Instruction &AI,
2130                                              const DataLayout &DL) const {
2131   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
2132 
2133   if (const AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(&AI)) {
2134     if (RMW->isVolatile())
2135       Flags |= MachineMemOperand::MOVolatile;
2136   } else if (const AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(&AI)) {
2137     if (CmpX->isVolatile())
2138       Flags |= MachineMemOperand::MOVolatile;
2139   } else
2140     llvm_unreachable("not an atomic instruction");
2141 
2142   // FIXME: Not preserving dereferenceable
2143   Flags |= getTargetMMOFlags(AI);
2144   return Flags;
2145 }
2146 
2147 //===----------------------------------------------------------------------===//
2148 //  GlobalISel Hooks
2149 //===----------------------------------------------------------------------===//
2150 
2151 bool TargetLoweringBase::shouldLocalize(const MachineInstr &MI,
2152                                         const TargetTransformInfo *TTI) const {
2153   auto &MF = *MI.getMF();
2154   auto &MRI = MF.getRegInfo();
2155   // Assuming a spill and reload of a value has a cost of 1 instruction each,
2156   // this helper function computes the maximum number of uses we should consider
2157   // for remat. E.g. on arm64 global addresses take 2 insts to materialize. We
2158   // break even in terms of code size when the original MI has 2 users vs
2159   // choosing to potentially spill. Any more than 2 users we we have a net code
2160   // size increase. This doesn't take into account register pressure though.
2161   auto maxUses = [](unsigned RematCost) {
2162     // A cost of 1 means remats are basically free.
2163     if (RematCost == 1)
2164       return UINT_MAX;
2165     if (RematCost == 2)
2166       return 2U;
2167 
2168     // Remat is too expensive, only sink if there's one user.
2169     if (RematCost > 2)
2170       return 1U;
2171     llvm_unreachable("Unexpected remat cost");
2172   };
2173 
2174   // Helper to walk through uses and terminate if we've reached a limit. Saves
2175   // us spending time traversing uses if all we want to know is if it's >= min.
2176   auto isUsesAtMost = [&](unsigned Reg, unsigned MaxUses) {
2177     unsigned NumUses = 0;
2178     auto UI = MRI.use_instr_nodbg_begin(Reg), UE = MRI.use_instr_nodbg_end();
2179     for (; UI != UE && NumUses < MaxUses; ++UI) {
2180       NumUses++;
2181     }
2182     // If we haven't reached the end yet then there are more than MaxUses users.
2183     return UI == UE;
2184   };
2185 
2186   switch (MI.getOpcode()) {
2187   default:
2188     return false;
2189   // Constants-like instructions should be close to their users.
2190   // We don't want long live-ranges for them.
2191   case TargetOpcode::G_CONSTANT:
2192   case TargetOpcode::G_FCONSTANT:
2193   case TargetOpcode::G_FRAME_INDEX:
2194   case TargetOpcode::G_INTTOPTR:
2195     return true;
2196   case TargetOpcode::G_GLOBAL_VALUE: {
2197     unsigned RematCost = TTI->getGISelRematGlobalCost();
2198     Register Reg = MI.getOperand(0).getReg();
2199     unsigned MaxUses = maxUses(RematCost);
2200     if (MaxUses == UINT_MAX)
2201       return true; // Remats are "free" so always localize.
2202     bool B = isUsesAtMost(Reg, MaxUses);
2203     return B;
2204   }
2205   }
2206 }
2207