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