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