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