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