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