LLVM  6.0.0svn
TargetLowering.h
Go to the documentation of this file.
1 //===- llvm/CodeGen/TargetLowering.h - Target Lowering Info -----*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// This file describes how to lower LLVM code to machine code. This has two
12 /// main components:
13 ///
14 /// 1. Which ValueTypes are natively supported by the target.
15 /// 2. Which operations are supported for supported ValueTypes.
16 /// 3. Cost thresholds for alternative implementations of certain operations.
17 ///
18 /// In addition it has a few other components, like information about FP
19 /// immediates.
20 ///
21 //===----------------------------------------------------------------------===//
22 
23 #ifndef LLVM_CODEGEN_TARGETLOWERING_H
24 #define LLVM_CODEGEN_TARGETLOWERING_H
25 
26 #include "llvm/ADT/APInt.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/StringRef.h"
40 #include "llvm/IR/Attributes.h"
41 #include "llvm/IR/CallSite.h"
42 #include "llvm/IR/CallingConv.h"
43 #include "llvm/IR/DataLayout.h"
44 #include "llvm/IR/DerivedTypes.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/IRBuilder.h"
47 #include "llvm/IR/InlineAsm.h"
48 #include "llvm/IR/Instruction.h"
49 #include "llvm/IR/Instructions.h"
50 #include "llvm/IR/Type.h"
51 #include "llvm/MC/MCRegisterInfo.h"
53 #include "llvm/Support/Casting.h"
56 #include <algorithm>
57 #include <cassert>
58 #include <climits>
59 #include <cstdint>
60 #include <iterator>
61 #include <map>
62 #include <string>
63 #include <utility>
64 #include <vector>
65 
66 namespace llvm {
67 
68 class BranchProbability;
69 class CCState;
70 class CCValAssign;
71 class Constant;
72 class FastISel;
73 class FunctionLoweringInfo;
74 class GlobalValue;
75 class IntrinsicInst;
76 struct KnownBits;
77 class LLVMContext;
78 class MachineBasicBlock;
79 class MachineFunction;
80 class MachineInstr;
81 class MachineJumpTableInfo;
82 class MachineLoop;
83 class MachineRegisterInfo;
84 class MCContext;
85 class MCExpr;
86 class Module;
87 class TargetRegisterClass;
88 class TargetLibraryInfo;
89 class TargetRegisterInfo;
90 class Value;
91 
92 namespace Sched {
93 
94  enum Preference {
95  None, // No preference
96  Source, // Follow source order.
97  RegPressure, // Scheduling for lowest register pressure.
98  Hybrid, // Scheduling for both latency and register pressure.
99  ILP, // Scheduling for ILP in low register pressure mode.
100  VLIW // Scheduling for VLIW targets.
101  };
102 
103 } // end namespace Sched
104 
105 /// This base class for TargetLowering contains the SelectionDAG-independent
106 /// parts that can be used from the rest of CodeGen.
108 public:
109  /// This enum indicates whether operations are valid for a target, and if not,
110  /// what action should be used to make them valid.
111  enum LegalizeAction : uint8_t {
112  Legal, // The target natively supports this operation.
113  Promote, // This operation should be executed in a larger type.
114  Expand, // Try to expand this to other ops, otherwise use a libcall.
115  LibCall, // Don't try to expand this to other ops, always use a libcall.
116  Custom // Use the LowerOperation hook to implement custom lowering.
117  };
118 
119  /// This enum indicates whether a types are legal for a target, and if not,
120  /// what action should be used to make them valid.
121  enum LegalizeTypeAction : uint8_t {
122  TypeLegal, // The target natively supports this type.
123  TypePromoteInteger, // Replace this integer with a larger one.
124  TypeExpandInteger, // Split this integer into two of half the size.
125  TypeSoftenFloat, // Convert this float to a same size integer type,
126  // if an operation is not supported in target HW.
127  TypeExpandFloat, // Split this float into two of half the size.
128  TypeScalarizeVector, // Replace this one-element vector with its element.
129  TypeSplitVector, // Split this vector into two of half the size.
130  TypeWidenVector, // This vector should be widened into a larger vector.
131  TypePromoteFloat // Replace this float with a larger one.
132  };
133 
134  /// LegalizeKind holds the legalization kind that needs to happen to EVT
135  /// in order to type-legalize it.
136  using LegalizeKind = std::pair<LegalizeTypeAction, EVT>;
137 
138  /// Enum that describes how the target represents true/false values.
140  UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
141  ZeroOrOneBooleanContent, // All bits zero except for bit 0.
142  ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
143  };
144 
145  /// Enum that describes what type of support for selects the target has.
147  ScalarValSelect, // The target supports scalar selects (ex: cmov).
148  ScalarCondVectorVal, // The target supports selects with a scalar condition
149  // and vector values (ex: cmov).
150  VectorMaskSelect // The target supports vector selects with a vector
151  // mask (ex: x86 blends).
152  };
153 
154  /// Enum that specifies what an atomic load/AtomicRMWInst is expanded
155  /// to, if at all. Exists because different targets have different levels of
156  /// support for these atomic instructions, and also have different options
157  /// w.r.t. what they should expand to.
158  enum class AtomicExpansionKind {
159  None, // Don't expand the instruction.
160  LLSC, // Expand the instruction into loadlinked/storeconditional; used
161  // by ARM/AArch64.
162  LLOnly, // Expand the (load) instruction into just a load-linked, which has
163  // greater atomic guarantees than a normal load.
164  CmpXChg, // Expand the instruction into cmpxchg; used by at least X86.
165  };
166 
167  /// Enum that specifies when a multiplication should be expanded.
168  enum class MulExpansionKind {
169  Always, // Always expand the instruction.
170  OnlyLegalOrCustom, // Only expand when the resulting instructions are legal
171  // or custom.
172  };
173 
174  class ArgListEntry {
175  public:
176  Value *Val = nullptr;
177  SDValue Node = SDValue();
178  Type *Ty = nullptr;
179  bool IsSExt : 1;
180  bool IsZExt : 1;
181  bool IsInReg : 1;
182  bool IsSRet : 1;
183  bool IsNest : 1;
184  bool IsByVal : 1;
185  bool IsInAlloca : 1;
186  bool IsReturned : 1;
187  bool IsSwiftSelf : 1;
188  bool IsSwiftError : 1;
189  uint16_t Alignment = 0;
190 
192  : IsSExt(false), IsZExt(false), IsInReg(false), IsSRet(false),
193  IsNest(false), IsByVal(false), IsInAlloca(false), IsReturned(false),
194  IsSwiftSelf(false), IsSwiftError(false) {}
195 
196  void setAttributes(ImmutableCallSite *CS, unsigned ArgIdx);
197  };
198  using ArgListTy = std::vector<ArgListEntry>;
199 
200  virtual void markLibCallAttributes(MachineFunction *MF, unsigned CC,
201  ArgListTy &Args) const {};
202 
204  switch (Content) {
205  case UndefinedBooleanContent:
206  // Extend by adding rubbish bits.
207  return ISD::ANY_EXTEND;
208  case ZeroOrOneBooleanContent:
209  // Extend by adding zero bits.
210  return ISD::ZERO_EXTEND;
211  case ZeroOrNegativeOneBooleanContent:
212  // Extend by copying the sign bit.
213  return ISD::SIGN_EXTEND;
214  }
215  llvm_unreachable("Invalid content kind");
216  }
217 
218  /// NOTE: The TargetMachine owns TLOF.
219  explicit TargetLoweringBase(const TargetMachine &TM);
220  TargetLoweringBase(const TargetLoweringBase &) = delete;
221  TargetLoweringBase &operator=(const TargetLoweringBase &) = delete;
222  virtual ~TargetLoweringBase() = default;
223 
224 protected:
225  /// \brief Initialize all of the actions to default values.
226  void initActions();
227 
228 public:
229  const TargetMachine &getTargetMachine() const { return TM; }
230 
231  virtual bool useSoftFloat() const { return false; }
232 
233  /// Return the pointer type for the given address space, defaults to
234  /// the pointer type from the data layout.
235  /// FIXME: The default needs to be removed once all the code is updated.
236  MVT getPointerTy(const DataLayout &DL, uint32_t AS = 0) const {
238  }
239 
240  /// Return the type for frame index, which is determined by
241  /// the alloca address space specified through the data layout.
242  MVT getFrameIndexTy(const DataLayout &DL) const {
243  return getPointerTy(DL, DL.getAllocaAddrSpace());
244  }
245 
246  /// Return the type for operands of fence.
247  /// TODO: Let fence operands be of i32 type and remove this.
248  virtual MVT getFenceOperandTy(const DataLayout &DL) const {
249  return getPointerTy(DL);
250  }
251 
252  /// EVT is not used in-tree, but is used by out-of-tree target.
253  /// A documentation for this function would be nice...
254  virtual MVT getScalarShiftAmountTy(const DataLayout &, EVT) const;
255 
256  EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL) const;
257 
258  /// Returns the type to be used for the index operand of:
259  /// ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
260  /// ISD::INSERT_SUBVECTOR, and ISD::EXTRACT_SUBVECTOR
261  virtual MVT getVectorIdxTy(const DataLayout &DL) const {
262  return getPointerTy(DL);
263  }
264 
265  virtual bool isSelectSupported(SelectSupportKind /*kind*/) const {
266  return true;
267  }
268 
269  /// Return true if multiple condition registers are available.
271  return HasMultipleConditionRegisters;
272  }
273 
274  /// Return true if the target has BitExtract instructions.
275  bool hasExtractBitsInsn() const { return HasExtractBitsInsn; }
276 
277  /// Return the preferred vector type legalization action.
280  // The default action for one element vectors is to scalarize
281  if (VT.getVectorNumElements() == 1)
282  return TypeScalarizeVector;
283  // The default action for other vectors is to promote
284  return TypePromoteInteger;
285  }
286 
287  // There are two general methods for expanding a BUILD_VECTOR node:
288  // 1. Use SCALAR_TO_VECTOR on the defined scalar values and then shuffle
289  // them together.
290  // 2. Build the vector on the stack and then load it.
291  // If this function returns true, then method (1) will be used, subject to
292  // the constraint that all of the necessary shuffles are legal (as determined
293  // by isShuffleMaskLegal). If this function returns false, then method (2) is
294  // always used. The vector type, and the number of defined values, are
295  // provided.
296  virtual bool
298  unsigned DefinedValues) const {
299  return DefinedValues < 3;
300  }
301 
302  /// Return true if integer divide is usually cheaper than a sequence of
303  /// several shifts, adds, and multiplies for this target.
304  /// The definition of "cheaper" may depend on whether we're optimizing
305  /// for speed or for size.
306  virtual bool isIntDivCheap(EVT VT, AttributeList Attr) const { return false; }
307 
308  /// Return true if the target can handle a standalone remainder operation.
309  virtual bool hasStandaloneRem(EVT VT) const {
310  return true;
311  }
312 
313  /// Return true if SQRT(X) shouldn't be replaced with X*RSQRT(X).
314  virtual bool isFsqrtCheap(SDValue X, SelectionDAG &DAG) const {
315  // Default behavior is to replace SQRT(X) with X*RSQRT(X).
316  return false;
317  }
318 
319  /// Reciprocal estimate status values used by the functions below.
320  enum ReciprocalEstimate : int {
321  Unspecified = -1,
322  Disabled = 0,
324  };
325 
326  /// Return a ReciprocalEstimate enum value for a square root of the given type
327  /// based on the function's attributes. If the operation is not overridden by
328  /// the function's attributes, "Unspecified" is returned and target defaults
329  /// are expected to be used for instruction selection.
330  int getRecipEstimateSqrtEnabled(EVT VT, MachineFunction &MF) const;
331 
332  /// Return a ReciprocalEstimate enum value for a division of the given type
333  /// based on the function's attributes. If the operation is not overridden by
334  /// the function's attributes, "Unspecified" is returned and target defaults
335  /// are expected to be used for instruction selection.
336  int getRecipEstimateDivEnabled(EVT VT, MachineFunction &MF) const;
337 
338  /// Return the refinement step count for a square root of the given type based
339  /// on the function's attributes. If the operation is not overridden by
340  /// the function's attributes, "Unspecified" is returned and target defaults
341  /// are expected to be used for instruction selection.
342  int getSqrtRefinementSteps(EVT VT, MachineFunction &MF) const;
343 
344  /// Return the refinement step count for a division of the given type based
345  /// on the function's attributes. If the operation is not overridden by
346  /// the function's attributes, "Unspecified" is returned and target defaults
347  /// are expected to be used for instruction selection.
348  int getDivRefinementSteps(EVT VT, MachineFunction &MF) const;
349 
350  /// Returns true if target has indicated at least one type should be bypassed.
351  bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
352 
353  /// Returns map of slow types for division or remainder with corresponding
354  /// fast types
356  return BypassSlowDivWidths;
357  }
358 
359  /// Return true if Flow Control is an expensive operation that should be
360  /// avoided.
361  bool isJumpExpensive() const { return JumpIsExpensive; }
362 
363  /// Return true if selects are only cheaper than branches if the branch is
364  /// unlikely to be predicted right.
366  return PredictableSelectIsExpensive;
367  }
368 
369  /// If a branch or a select condition is skewed in one direction by more than
370  /// this factor, it is very likely to be predicted correctly.
371  virtual BranchProbability getPredictableBranchThreshold() const;
372 
373  /// Return true if the following transform is beneficial:
374  /// fold (conv (load x)) -> (load (conv*)x)
375  /// On architectures that don't natively support some vector loads
376  /// efficiently, casting the load to a smaller vector of larger types and
377  /// loading is more efficient, however, this can be undone by optimizations in
378  /// dag combiner.
379  virtual bool isLoadBitCastBeneficial(EVT LoadVT,
380  EVT BitcastVT) const {
381  // Don't do if we could do an indexed load on the original type, but not on
382  // the new one.
383  if (!LoadVT.isSimple() || !BitcastVT.isSimple())
384  return true;
385 
386  MVT LoadMVT = LoadVT.getSimpleVT();
387 
388  // Don't bother doing this if it's just going to be promoted again later, as
389  // doing so might interfere with other combines.
390  if (getOperationAction(ISD::LOAD, LoadMVT) == Promote &&
391  getTypeToPromoteTo(ISD::LOAD, LoadMVT) == BitcastVT.getSimpleVT())
392  return false;
393 
394  return true;
395  }
396 
397  /// Return true if the following transform is beneficial:
398  /// (store (y (conv x)), y*)) -> (store x, (x*))
399  virtual bool isStoreBitCastBeneficial(EVT StoreVT, EVT BitcastVT) const {
400  // Default to the same logic as loads.
401  return isLoadBitCastBeneficial(StoreVT, BitcastVT);
402  }
403 
404  /// Return true if it is expected to be cheaper to do a store of a non-zero
405  /// vector constant with the given size and type for the address space than to
406  /// store the individual scalar element constants.
407  virtual bool storeOfVectorConstantIsCheap(EVT MemVT,
408  unsigned NumElem,
409  unsigned AddrSpace) const {
410  return false;
411  }
412 
413  /// Allow store merging after legalization in addition to before legalization.
414  /// This may catch stores that do not exist earlier (eg, stores created from
415  /// intrinsics).
416  virtual bool mergeStoresAfterLegalization() const { return false; }
417 
418  /// Returns if it's reasonable to merge stores to MemVT size.
419  virtual bool canMergeStoresTo(unsigned AS, EVT MemVT,
420  const SelectionDAG &DAG) const {
421  return true;
422  }
423 
424  /// \brief Return true if it is cheap to speculate a call to intrinsic cttz.
425  virtual bool isCheapToSpeculateCttz() const {
426  return false;
427  }
428 
429  /// \brief Return true if it is cheap to speculate a call to intrinsic ctlz.
430  virtual bool isCheapToSpeculateCtlz() const {
431  return false;
432  }
433 
434  /// \brief Return true if ctlz instruction is fast.
435  virtual bool isCtlzFast() const {
436  return false;
437  }
438 
439  /// Return true if it is safe to transform an integer-domain bitwise operation
440  /// into the equivalent floating-point operation. This should be set to true
441  /// if the target has IEEE-754-compliant fabs/fneg operations for the input
442  /// type.
443  virtual bool hasBitPreservingFPLogic(EVT VT) const {
444  return false;
445  }
446 
447  /// \brief Return true if it is cheaper to split the store of a merged int val
448  /// from a pair of smaller values into multiple stores.
449  virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const {
450  return false;
451  }
452 
453  /// \brief Return if the target supports combining a
454  /// chain like:
455  /// \code
456  /// %andResult = and %val1, #mask
457  /// %icmpResult = icmp %andResult, 0
458  /// \endcode
459  /// into a single machine instruction of a form like:
460  /// \code
461  /// cc = test %register, #mask
462  /// \endcode
463  virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
464  return false;
465  }
466 
467  /// Use bitwise logic to make pairs of compares more efficient. For example:
468  /// and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
469  /// This should be true when it takes more than one instruction to lower
470  /// setcc (cmp+set on x86 scalar), when bitwise ops are faster than logic on
471  /// condition bits (crand on PowerPC), and/or when reducing cmp+br is a win.
472  virtual bool convertSetCCLogicToBitwiseLogic(EVT VT) const {
473  return false;
474  }
475 
476  /// Return the preferred operand type if the target has a quick way to compare
477  /// integer values of the given size. Assume that any legal integer type can
478  /// be compared efficiently. Targets may override this to allow illegal wide
479  /// types to return a vector type if there is support to compare that type.
480  virtual MVT hasFastEqualityCompare(unsigned NumBits) const {
481  MVT VT = MVT::getIntegerVT(NumBits);
482  return isTypeLegal(VT) ? VT : MVT::INVALID_SIMPLE_VALUE_TYPE;
483  }
484 
485  /// Return true if the target should transform:
486  /// (X & Y) == Y ---> (~X & Y) == 0
487  /// (X & Y) != Y ---> (~X & Y) != 0
488  ///
489  /// This may be profitable if the target has a bitwise and-not operation that
490  /// sets comparison flags. A target may want to limit the transformation based
491  /// on the type of Y or if Y is a constant.
492  ///
493  /// Note that the transform will not occur if Y is known to be a power-of-2
494  /// because a mask and compare of a single bit can be handled by inverting the
495  /// predicate, for example:
496  /// (X & 8) == 8 ---> (X & 8) != 0
497  virtual bool hasAndNotCompare(SDValue Y) const {
498  return false;
499  }
500 
501  /// Return true if the target has a bitwise and-not operation:
502  /// X = ~A & B
503  /// This can be used to simplify select or other instructions.
504  virtual bool hasAndNot(SDValue X) const {
505  // If the target has the more complex version of this operation, assume that
506  // it has this operation too.
507  return hasAndNotCompare(X);
508  }
509 
510  /// \brief Return true if the target wants to use the optimization that
511  /// turns ext(promotableInst1(...(promotableInstN(load)))) into
512  /// promotedInst1(...(promotedInstN(ext(load)))).
513  bool enableExtLdPromotion() const { return EnableExtLdPromotion; }
514 
515  /// Return true if the target can combine store(extractelement VectorTy,
516  /// Idx).
517  /// \p Cost[out] gives the cost of that transformation when this is true.
518  virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
519  unsigned &Cost) const {
520  return false;
521  }
522 
523  /// Return true if target supports floating point exceptions.
525  return HasFloatingPointExceptions;
526  }
527 
528  /// Return true if target always beneficiates from combining into FMA for a
529  /// given value type. This must typically return false on targets where FMA
530  /// takes more cycles to execute than FADD.
531  virtual bool enableAggressiveFMAFusion(EVT VT) const {
532  return false;
533  }
534 
535  /// Return the ValueType of the result of SETCC operations.
536  virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context,
537  EVT VT) const;
538 
539  /// Return the ValueType for comparison libcalls. Comparions libcalls include
540  /// floating point comparion calls, and Ordered/Unordered check calls on
541  /// floating point numbers.
542  virtual
543  MVT::SimpleValueType getCmpLibcallReturnType() const;
544 
545  /// For targets without i1 registers, this gives the nature of the high-bits
546  /// of boolean values held in types wider than i1.
547  ///
548  /// "Boolean values" are special true/false values produced by nodes like
549  /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
550  /// Not to be confused with general values promoted from i1. Some cpus
551  /// distinguish between vectors of boolean and scalars; the isVec parameter
552  /// selects between the two kinds. For example on X86 a scalar boolean should
553  /// be zero extended from i1, while the elements of a vector of booleans
554  /// should be sign extended from i1.
555  ///
556  /// Some cpus also treat floating point types the same way as they treat
557  /// vectors instead of the way they treat scalars.
558  BooleanContent getBooleanContents(bool isVec, bool isFloat) const {
559  if (isVec)
560  return BooleanVectorContents;
561  return isFloat ? BooleanFloatContents : BooleanContents;
562  }
563 
565  return getBooleanContents(Type.isVector(), Type.isFloatingPoint());
566  }
567 
568  /// Return target scheduling preference.
570  return SchedPreferenceInfo;
571  }
572 
573  /// Some scheduler, e.g. hybrid, can switch to different scheduling heuristics
574  /// for different nodes. This function returns the preference (or none) for
575  /// the given node.
577  return Sched::None;
578  }
579 
580  /// Return the register class that should be used for the specified value
581  /// type.
582  virtual const TargetRegisterClass *getRegClassFor(MVT VT) const {
583  const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
584  assert(RC && "This value type is not natively supported!");
585  return RC;
586  }
587 
588  /// Return the 'representative' register class for the specified value
589  /// type.
590  ///
591  /// The 'representative' register class is the largest legal super-reg
592  /// register class for the register class of the value type. For example, on
593  /// i386 the rep register class for i8, i16, and i32 are GR32; while the rep
594  /// register class is GR64 on x86_64.
595  virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
596  const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
597  return RC;
598  }
599 
600  /// Return the cost of the 'representative' register class for the specified
601  /// value type.
602  virtual uint8_t getRepRegClassCostFor(MVT VT) const {
603  return RepRegClassCostForVT[VT.SimpleTy];
604  }
605 
606  /// Return true if the target has native support for the specified value type.
607  /// This means that it has a register that directly holds it without
608  /// promotions or expansions.
609  bool isTypeLegal(EVT VT) const {
610  assert(!VT.isSimple() ||
611  (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
612  return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != nullptr;
613  }
614 
616  /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
617  /// that indicates how instruction selection should deal with the type.
618  LegalizeTypeAction ValueTypeActions[MVT::LAST_VALUETYPE];
619 
620  public:
622  std::fill(std::begin(ValueTypeActions), std::end(ValueTypeActions),
623  TypeLegal);
624  }
625 
627  return ValueTypeActions[VT.SimpleTy];
628  }
629 
631  ValueTypeActions[VT.SimpleTy] = Action;
632  }
633  };
634 
636  return ValueTypeActions;
637  }
638 
639  /// Return how we should legalize values of this type, either it is already
640  /// legal (return 'Legal') or we need to promote it to a larger type (return
641  /// 'Promote'), or we need to expand it into multiple registers of smaller
642  /// integer type (return 'Expand'). 'Custom' is not an option.
644  return getTypeConversion(Context, VT).first;
645  }
647  return ValueTypeActions.getTypeAction(VT);
648  }
649 
650  /// For types supported by the target, this is an identity function. For
651  /// types that must be promoted to larger types, this returns the larger type
652  /// to promote to. For integer types that are larger than the largest integer
653  /// register, this contains one step in the expansion to get to the smaller
654  /// register. For illegal floating point types, this returns the integer type
655  /// to transform to.
656  EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
657  return getTypeConversion(Context, VT).second;
658  }
659 
660  /// For types supported by the target, this is an identity function. For
661  /// types that must be expanded (i.e. integer types that are larger than the
662  /// largest integer register or illegal floating point types), this returns
663  /// the largest legal type it will be expanded to.
664  EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
665  assert(!VT.isVector());
666  while (true) {
667  switch (getTypeAction(Context, VT)) {
668  case TypeLegal:
669  return VT;
670  case TypeExpandInteger:
671  VT = getTypeToTransformTo(Context, VT);
672  break;
673  default:
674  llvm_unreachable("Type is not legal nor is it to be expanded!");
675  }
676  }
677  }
678 
679  /// Vector types are broken down into some number of legal first class types.
680  /// For example, EVT::v8f32 maps to 2 EVT::v4f32 with Altivec or SSE1, or 8
681  /// promoted EVT::f64 values with the X86 FP stack. Similarly, EVT::v2i64
682  /// turns into 4 EVT::i32 values with both PPC and X86.
683  ///
684  /// This method returns the number of registers needed, and the VT for each
685  /// register. It also returns the VT and quantity of the intermediate values
686  /// before they are promoted/expanded.
687  unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
688  EVT &IntermediateVT,
689  unsigned &NumIntermediates,
690  MVT &RegisterVT) const;
691 
692  /// Certain targets such as MIPS require that some types such as vectors are
693  /// always broken down into scalars in some contexts. This occurs even if the
694  /// vector type is legal.
696  LLVMContext &Context, EVT VT, EVT &IntermediateVT,
697  unsigned &NumIntermediates, MVT &RegisterVT) const {
698  return getVectorTypeBreakdown(Context, VT, IntermediateVT, NumIntermediates,
699  RegisterVT);
700  }
701 
702  struct IntrinsicInfo {
703  unsigned opc = 0; // target opcode
704  EVT memVT; // memory VT
705  const Value* ptrVal = nullptr; // value representing memory location
706  int offset = 0; // offset off of ptrVal
707  unsigned size = 0; // the size of the memory location
708  // (taken from memVT if zero)
709  unsigned align = 1; // alignment
710  bool vol = false; // is volatile?
711  bool readMem = false; // reads memory?
712  bool writeMem = false; // writes memory?
713 
714  IntrinsicInfo() = default;
715  };
716 
717  /// Given an intrinsic, checks if on the target the intrinsic will need to map
718  /// to a MemIntrinsicNode (touches memory). If this is the case, it returns
719  /// true and store the intrinsic information into the IntrinsicInfo that was
720  /// passed to the function.
721  virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
722  unsigned /*Intrinsic*/) const {
723  return false;
724  }
725 
726  /// Returns true if the target can instruction select the specified FP
727  /// immediate natively. If false, the legalizer will materialize the FP
728  /// immediate as a load from a constant pool.
729  virtual bool isFPImmLegal(const APFloat &/*Imm*/, EVT /*VT*/) const {
730  return false;
731  }
732 
733  /// Targets can use this to indicate that they only support *some*
734  /// VECTOR_SHUFFLE operations, those with specific masks. By default, if a
735  /// target supports the VECTOR_SHUFFLE node, all mask values are assumed to be
736  /// legal.
737  virtual bool isShuffleMaskLegal(ArrayRef<int> /*Mask*/, EVT /*VT*/) const {
738  return true;
739  }
740 
741  /// Returns true if the operation can trap for the value type.
742  ///
743  /// VT must be a legal type. By default, we optimistically assume most
744  /// operations don't trap except for integer divide and remainder.
745  virtual bool canOpTrap(unsigned Op, EVT VT) const;
746 
747  /// Similar to isShuffleMaskLegal. This is used by Targets can use this to
748  /// indicate if there is a suitable VECTOR_SHUFFLE that can be used to replace
749  /// a VAND with a constant pool entry.
750  virtual bool isVectorClearMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
751  EVT /*VT*/) const {
752  return false;
753  }
754 
755  /// Return how this operation should be treated: either it is legal, needs to
756  /// be promoted to a larger size, needs to be expanded to some other code
757  /// sequence, or the target has a custom expander for it.
758  LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
759  if (VT.isExtended()) return Expand;
760  // If a target-specific SDNode requires legalization, require the target
761  // to provide custom legalization for it.
762  if (Op >= array_lengthof(OpActions[0])) return Custom;
763  return OpActions[(unsigned)VT.getSimpleVT().SimpleTy][Op];
764  }
765 
766  /// Return true if the specified operation is legal on this target or can be
767  /// made legal with custom lowering. This is used to help guide high-level
768  /// lowering decisions.
769  bool isOperationLegalOrCustom(unsigned Op, EVT VT) const {
770  return (VT == MVT::Other || isTypeLegal(VT)) &&
771  (getOperationAction(Op, VT) == Legal ||
772  getOperationAction(Op, VT) == Custom);
773  }
774 
775  /// Return true if the specified operation is legal on this target or can be
776  /// made legal using promotion. This is used to help guide high-level lowering
777  /// decisions.
778  bool isOperationLegalOrPromote(unsigned Op, EVT VT) const {
779  return (VT == MVT::Other || isTypeLegal(VT)) &&
780  (getOperationAction(Op, VT) == Legal ||
781  getOperationAction(Op, VT) == Promote);
782  }
783 
784  /// Return true if the specified operation is legal on this target or can be
785  /// made legal with custom lowering or using promotion. This is used to help
786  /// guide high-level lowering decisions.
787  bool isOperationLegalOrCustomOrPromote(unsigned Op, EVT VT) const {
788  return (VT == MVT::Other || isTypeLegal(VT)) &&
789  (getOperationAction(Op, VT) == Legal ||
790  getOperationAction(Op, VT) == Custom ||
791  getOperationAction(Op, VT) == Promote);
792  }
793 
794  /// Return true if the operation uses custom lowering, regardless of whether
795  /// the type is legal or not.
796  bool isOperationCustom(unsigned Op, EVT VT) const {
797  return getOperationAction(Op, VT) == Custom;
798  }
799 
800  /// Return true if lowering to a jump table is allowed.
801  bool areJTsAllowed(const Function *Fn) const {
802  if (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true")
803  return false;
804 
805  return isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
806  isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
807  }
808 
809  /// Check whether the range [Low,High] fits in a machine word.
810  bool rangeFitsInWord(const APInt &Low, const APInt &High,
811  const DataLayout &DL) const {
812  // FIXME: Using the pointer type doesn't seem ideal.
813  uint64_t BW = DL.getPointerSizeInBits();
814  uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1;
815  return Range <= BW;
816  }
817 
818  /// Return true if lowering to a jump table is suitable for a set of case
819  /// clusters which may contain \p NumCases cases, \p Range range of values.
820  /// FIXME: This function check the maximum table size and density, but the
821  /// minimum size is not checked. It would be nice if the the minimum size is
822  /// also combined within this function. Currently, the minimum size check is
823  /// performed in findJumpTable() in SelectionDAGBuiler and
824  /// getEstimatedNumberOfCaseClusters() in BasicTTIImpl.
825  bool isSuitableForJumpTable(const SwitchInst *SI, uint64_t NumCases,
826  uint64_t Range) const {
827  const bool OptForSize = SI->getParent()->getParent()->optForSize();
828  const unsigned MinDensity = getMinimumJumpTableDensity(OptForSize);
829  const unsigned MaxJumpTableSize =
830  OptForSize || getMaximumJumpTableSize() == 0
831  ? UINT_MAX
832  : getMaximumJumpTableSize();
833  // Check whether a range of clusters is dense enough for a jump table.
834  if (Range <= MaxJumpTableSize &&
835  (NumCases * 100 >= Range * MinDensity)) {
836  return true;
837  }
838  return false;
839  }
840 
841  /// Return true if lowering to a bit test is suitable for a set of case
842  /// clusters which contains \p NumDests unique destinations, \p Low and
843  /// \p High as its lowest and highest case values, and expects \p NumCmps
844  /// case value comparisons. Check if the number of destinations, comparison
845  /// metric, and range are all suitable.
846  bool isSuitableForBitTests(unsigned NumDests, unsigned NumCmps,
847  const APInt &Low, const APInt &High,
848  const DataLayout &DL) const {
849  // FIXME: I don't think NumCmps is the correct metric: a single case and a
850  // range of cases both require only one branch to lower. Just looking at the
851  // number of clusters and destinations should be enough to decide whether to
852  // build bit tests.
853 
854  // To lower a range with bit tests, the range must fit the bitwidth of a
855  // machine word.
856  if (!rangeFitsInWord(Low, High, DL))
857  return false;
858 
859  // Decide whether it's profitable to lower this range with bit tests. Each
860  // destination requires a bit test and branch, and there is an overall range
861  // check branch. For a small number of clusters, separate comparisons might
862  // be cheaper, and for many destinations, splitting the range might be
863  // better.
864  return (NumDests == 1 && NumCmps >= 3) || (NumDests == 2 && NumCmps >= 5) ||
865  (NumDests == 3 && NumCmps >= 6);
866  }
867 
868  /// Return true if the specified operation is illegal on this target or
869  /// unlikely to be made legal with custom lowering. This is used to help guide
870  /// high-level lowering decisions.
871  bool isOperationExpand(unsigned Op, EVT VT) const {
872  return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
873  }
874 
875  /// Return true if the specified operation is legal on this target.
876  bool isOperationLegal(unsigned Op, EVT VT) const {
877  return (VT == MVT::Other || isTypeLegal(VT)) &&
878  getOperationAction(Op, VT) == Legal;
879  }
880 
881  /// Return how this load with extension should be treated: either it is legal,
882  /// needs to be promoted to a larger size, needs to be expanded to some other
883  /// code sequence, or the target has a custom expander for it.
884  LegalizeAction getLoadExtAction(unsigned ExtType, EVT ValVT,
885  EVT MemVT) const {
886  if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
887  unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
888  unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
889  assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValI < MVT::LAST_VALUETYPE &&
890  MemI < MVT::LAST_VALUETYPE && "Table isn't big enough!");
891  unsigned Shift = 4 * ExtType;
892  return (LegalizeAction)((LoadExtActions[ValI][MemI] >> Shift) & 0xf);
893  }
894 
895  /// Return true if the specified load with extension is legal on this target.
896  bool isLoadExtLegal(unsigned ExtType, EVT ValVT, EVT MemVT) const {
897  return getLoadExtAction(ExtType, ValVT, MemVT) == Legal;
898  }
899 
900  /// Return true if the specified load with extension is legal or custom
901  /// on this target.
902  bool isLoadExtLegalOrCustom(unsigned ExtType, EVT ValVT, EVT MemVT) const {
903  return getLoadExtAction(ExtType, ValVT, MemVT) == Legal ||
904  getLoadExtAction(ExtType, ValVT, MemVT) == Custom;
905  }
906 
907  /// Return how this store with truncation should be treated: either it is
908  /// legal, needs to be promoted to a larger size, needs to be expanded to some
909  /// other code sequence, or the target has a custom expander for it.
911  if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
912  unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
913  unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
915  "Table isn't big enough!");
916  return TruncStoreActions[ValI][MemI];
917  }
918 
919  /// Return true if the specified store with truncation is legal on this
920  /// target.
921  bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
922  return isTypeLegal(ValVT) && getTruncStoreAction(ValVT, MemVT) == Legal;
923  }
924 
925  /// Return true if the specified store with truncation has solution on this
926  /// target.
927  bool isTruncStoreLegalOrCustom(EVT ValVT, EVT MemVT) const {
928  return isTypeLegal(ValVT) &&
929  (getTruncStoreAction(ValVT, MemVT) == Legal ||
930  getTruncStoreAction(ValVT, MemVT) == Custom);
931  }
932 
933  /// Return how the indexed load should be treated: either it is legal, needs
934  /// to be promoted to a larger size, needs to be expanded to some other code
935  /// sequence, or the target has a custom expander for it.
937  getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
938  assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&
939  "Table isn't big enough!");
940  unsigned Ty = (unsigned)VT.SimpleTy;
941  return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] & 0xf0) >> 4);
942  }
943 
944  /// Return true if the specified indexed load is legal on this target.
945  bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
946  return VT.isSimple() &&
947  (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
948  getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
949  }
950 
951  /// Return how the indexed store should be treated: either it is legal, needs
952  /// to be promoted to a larger size, needs to be expanded to some other code
953  /// sequence, or the target has a custom expander for it.
955  getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
956  assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&
957  "Table isn't big enough!");
958  unsigned Ty = (unsigned)VT.SimpleTy;
959  return (LegalizeAction)(IndexedModeActions[Ty][IdxMode] & 0x0f);
960  }
961 
962  /// Return true if the specified indexed load is legal on this target.
963  bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
964  return VT.isSimple() &&
965  (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
966  getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
967  }
968 
969  /// Return how the condition code should be treated: either it is legal, needs
970  /// to be expanded to some other code sequence, or the target has a custom
971  /// expander for it.
974  assert((unsigned)CC < array_lengthof(CondCodeActions) &&
975  ((unsigned)VT.SimpleTy >> 3) < array_lengthof(CondCodeActions[0]) &&
976  "Table isn't big enough!");
977  // See setCondCodeAction for how this is encoded.
978  uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
979  uint32_t Value = CondCodeActions[CC][VT.SimpleTy >> 3];
980  LegalizeAction Action = (LegalizeAction) ((Value >> Shift) & 0xF);
981  assert(Action != Promote && "Can't promote condition code!");
982  return Action;
983  }
984 
985  /// Return true if the specified condition code is legal on this target.
986  bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
987  return
988  getCondCodeAction(CC, VT) == Legal ||
989  getCondCodeAction(CC, VT) == Custom;
990  }
991 
992  /// If the action for this operation is to promote, this method returns the
993  /// ValueType to promote to.
994  MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
995  assert(getOperationAction(Op, VT) == Promote &&
996  "This operation isn't promoted!");
997 
998  // See if this has an explicit type specified.
999  std::map<std::pair<unsigned, MVT::SimpleValueType>,
1000  MVT::SimpleValueType>::const_iterator PTTI =
1001  PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
1002  if (PTTI != PromoteToType.end()) return PTTI->second;
1003 
1004  assert((VT.isInteger() || VT.isFloatingPoint()) &&
1005  "Cannot autopromote this type, add it with AddPromotedToType.");
1006 
1007  MVT NVT = VT;
1008  do {
1009  NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
1010  assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
1011  "Didn't find type to promote to!");
1012  } while (!isTypeLegal(NVT) ||
1013  getOperationAction(Op, NVT) == Promote);
1014  return NVT;
1015  }
1016 
1017  /// Return the EVT corresponding to this LLVM type. This is fixed by the LLVM
1018  /// operations except for the pointer size. If AllowUnknown is true, this
1019  /// will return MVT::Other for types with no EVT counterpart (e.g. structs),
1020  /// otherwise it will assert.
1022  bool AllowUnknown = false) const {
1023  // Lower scalar pointers to native pointer types.
1024  if (PointerType *PTy = dyn_cast<PointerType>(Ty))
1025  return getPointerTy(DL, PTy->getAddressSpace());
1026 
1027  if (Ty->isVectorTy()) {
1028  VectorType *VTy = cast<VectorType>(Ty);
1029  Type *Elm = VTy->getElementType();
1030  // Lower vectors of pointers to native pointer types.
1031  if (PointerType *PT = dyn_cast<PointerType>(Elm)) {
1032  EVT PointerTy(getPointerTy(DL, PT->getAddressSpace()));
1033  Elm = PointerTy.getTypeForEVT(Ty->getContext());
1034  }
1035 
1036  return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
1037  VTy->getNumElements());
1038  }
1039  return EVT::getEVT(Ty, AllowUnknown);
1040  }
1041 
1042  /// Return the MVT corresponding to this LLVM type. See getValueType.
1044  bool AllowUnknown = false) const {
1045  return getValueType(DL, Ty, AllowUnknown).getSimpleVT();
1046  }
1047 
1048  /// Return the desired alignment for ByVal or InAlloca aggregate function
1049  /// arguments in the caller parameter area. This is the actual alignment, not
1050  /// its logarithm.
1051  virtual unsigned getByValTypeAlignment(Type *Ty, const DataLayout &DL) const;
1052 
1053  /// Return the type of registers that this ValueType will eventually require.
1055  assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
1056  return RegisterTypeForVT[VT.SimpleTy];
1057  }
1058 
1059  /// Return the type of registers that this ValueType will eventually require.
1060  MVT getRegisterType(LLVMContext &Context, EVT VT) const {
1061  if (VT.isSimple()) {
1062  assert((unsigned)VT.getSimpleVT().SimpleTy <
1063  array_lengthof(RegisterTypeForVT));
1064  return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
1065  }
1066  if (VT.isVector()) {
1067  EVT VT1;
1068  MVT RegisterVT;
1069  unsigned NumIntermediates;
1070  (void)getVectorTypeBreakdown(Context, VT, VT1,
1071  NumIntermediates, RegisterVT);
1072  return RegisterVT;
1073  }
1074  if (VT.isInteger()) {
1075  return getRegisterType(Context, getTypeToTransformTo(Context, VT));
1076  }
1077  llvm_unreachable("Unsupported extended type!");
1078  }
1079 
1080  /// Return the number of registers that this ValueType will eventually
1081  /// require.
1082  ///
1083  /// This is one for any types promoted to live in larger registers, but may be
1084  /// more than one for types (like i64) that are split into pieces. For types
1085  /// like i140, which are first promoted then expanded, it is the number of
1086  /// registers needed to hold all the bits of the original type. For an i140
1087  /// on a 32 bit machine this means 5 registers.
1088  unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
1089  if (VT.isSimple()) {
1090  assert((unsigned)VT.getSimpleVT().SimpleTy <
1091  array_lengthof(NumRegistersForVT));
1092  return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
1093  }
1094  if (VT.isVector()) {
1095  EVT VT1;
1096  MVT VT2;
1097  unsigned NumIntermediates;
1098  return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
1099  }
1100  if (VT.isInteger()) {
1101  unsigned BitWidth = VT.getSizeInBits();
1102  unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
1103  return (BitWidth + RegWidth - 1) / RegWidth;
1104  }
1105  llvm_unreachable("Unsupported extended type!");
1106  }
1107 
1108  /// Certain combinations of ABIs, Targets and features require that types
1109  /// are legal for some operations and not for other operations.
1110  /// For MIPS all vector types must be passed through the integer register set.
1112  return getRegisterType(VT);
1113  }
1114 
1116  EVT VT) const {
1117  return getRegisterType(Context, VT);
1118  }
1119 
1120  /// Certain targets require unusual breakdowns of certain types. For MIPS,
1121  /// this occurs when a vector type is used, as vector are passed through the
1122  /// integer register set.
1123  virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context,
1124  EVT VT) const {
1125  return getNumRegisters(Context, VT);
1126  }
1127 
1128  /// Certain targets have context senstive alignment requirements, where one
1129  /// type has the alignment requirement of another type.
1130  virtual unsigned getABIAlignmentForCallingConv(Type *ArgTy,
1131  DataLayout DL) const {
1132  return DL.getABITypeAlignment(ArgTy);
1133  }
1134 
1135  /// If true, then instruction selection should seek to shrink the FP constant
1136  /// of the specified type to a smaller type in order to save space and / or
1137  /// reduce runtime.
1138  virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
1139 
1140  // Return true if it is profitable to reduce the given load node to a smaller
1141  // type.
1142  //
1143  // e.g. (i16 (trunc (i32 (load x))) -> i16 load x should be performed
1145  ISD::LoadExtType ExtTy,
1146  EVT NewVT) const {
1147  return true;
1148  }
1149 
1150  /// When splitting a value of the specified type into parts, does the Lo
1151  /// or Hi part come first? This usually follows the endianness, except
1152  /// for ppcf128, where the Hi part always comes first.
1153  bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const {
1154  return DL.isBigEndian() || VT == MVT::ppcf128;
1155  }
1156 
1157  /// If true, the target has custom DAG combine transformations that it can
1158  /// perform for the specified node.
1160  assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1161  return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
1162  }
1163 
1164  unsigned getGatherAllAliasesMaxDepth() const {
1165  return GatherAllAliasesMaxDepth;
1166  }
1167 
1168  /// Returns the size of the platform's va_list object.
1169  virtual unsigned getVaListSizeInBits(const DataLayout &DL) const {
1170  return getPointerTy(DL).getSizeInBits();
1171  }
1172 
1173  /// \brief Get maximum # of store operations permitted for llvm.memset
1174  ///
1175  /// This function returns the maximum number of store operations permitted
1176  /// to replace a call to llvm.memset. The value is set by the target at the
1177  /// performance threshold for such a replacement. If OptSize is true,
1178  /// return the limit for functions that have OptSize attribute.
1179  unsigned getMaxStoresPerMemset(bool OptSize) const {
1180  return OptSize ? MaxStoresPerMemsetOptSize : MaxStoresPerMemset;
1181  }
1182 
1183  /// \brief Get maximum # of store operations permitted for llvm.memcpy
1184  ///
1185  /// This function returns the maximum number of store operations permitted
1186  /// to replace a call to llvm.memcpy. The value is set by the target at the
1187  /// performance threshold for such a replacement. If OptSize is true,
1188  /// return the limit for functions that have OptSize attribute.
1189  unsigned getMaxStoresPerMemcpy(bool OptSize) const {
1190  return OptSize ? MaxStoresPerMemcpyOptSize : MaxStoresPerMemcpy;
1191  }
1192 
1193  /// Get maximum # of load operations permitted for memcmp
1194  ///
1195  /// This function returns the maximum number of load operations permitted
1196  /// to replace a call to memcmp. The value is set by the target at the
1197  /// performance threshold for such a replacement. If OptSize is true,
1198  /// return the limit for functions that have OptSize attribute.
1199  unsigned getMaxExpandSizeMemcmp(bool OptSize) const {
1200  return OptSize ? MaxLoadsPerMemcmpOptSize : MaxLoadsPerMemcmp;
1201  }
1202 
1203  /// \brief Get maximum # of store operations permitted for llvm.memmove
1204  ///
1205  /// This function returns the maximum number of store operations permitted
1206  /// to replace a call to llvm.memmove. The value is set by the target at the
1207  /// performance threshold for such a replacement. If OptSize is true,
1208  /// return the limit for functions that have OptSize attribute.
1209  unsigned getMaxStoresPerMemmove(bool OptSize) const {
1210  return OptSize ? MaxStoresPerMemmoveOptSize : MaxStoresPerMemmove;
1211  }
1212 
1213  /// \brief Determine if the target supports unaligned memory accesses.
1214  ///
1215  /// This function returns true if the target allows unaligned memory accesses
1216  /// of the specified type in the given address space. If true, it also returns
1217  /// whether the unaligned memory access is "fast" in the last argument by
1218  /// reference. This is used, for example, in situations where an array
1219  /// copy/move/set is converted to a sequence of store operations. Its use
1220  /// helps to ensure that such replacements don't generate code that causes an
1221  /// alignment error (trap) on the target machine.
1223  unsigned AddrSpace = 0,
1224  unsigned Align = 1,
1225  bool * /*Fast*/ = nullptr) const {
1226  return false;
1227  }
1228 
1229  /// Return true if the target supports a memory access of this type for the
1230  /// given address space and alignment. If the access is allowed, the optional
1231  /// final parameter returns if the access is also fast (as defined by the
1232  /// target).
1233  bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT,
1234  unsigned AddrSpace = 0, unsigned Alignment = 1,
1235  bool *Fast = nullptr) const;
1236 
1237  /// Returns the target specific optimal type for load and store operations as
1238  /// a result of memset, memcpy, and memmove lowering.
1239  ///
1240  /// If DstAlign is zero that means it's safe to destination alignment can
1241  /// satisfy any constraint. Similarly if SrcAlign is zero it means there isn't
1242  /// a need to check it against alignment requirement, probably because the
1243  /// source does not need to be loaded. If 'IsMemset' is true, that means it's
1244  /// expanding a memset. If 'ZeroMemset' is true, that means it's a memset of
1245  /// zero. 'MemcpyStrSrc' indicates whether the memcpy source is constant so it
1246  /// does not need to be loaded. It returns EVT::Other if the type should be
1247  /// determined using generic target-independent logic.
1248  virtual EVT getOptimalMemOpType(uint64_t /*Size*/,
1249  unsigned /*DstAlign*/, unsigned /*SrcAlign*/,
1250  bool /*IsMemset*/,
1251  bool /*ZeroMemset*/,
1252  bool /*MemcpyStrSrc*/,
1253  MachineFunction &/*MF*/) const {
1254  return MVT::Other;
1255  }
1256 
1257  /// Returns true if it's safe to use load / store of the specified type to
1258  /// expand memcpy / memset inline.
1259  ///
1260  /// This is mostly true for all types except for some special cases. For
1261  /// example, on X86 targets without SSE2 f64 load / store are done with fldl /
1262  /// fstpl which also does type conversion. Note the specified type doesn't
1263  /// have to be legal as the hook is used before type legalization.
1264  virtual bool isSafeMemOpType(MVT /*VT*/) const { return true; }
1265 
1266  /// Determine if we should use _setjmp or setjmp to implement llvm.setjmp.
1267  bool usesUnderscoreSetJmp() const {
1268  return UseUnderscoreSetJmp;
1269  }
1270 
1271  /// Determine if we should use _longjmp or longjmp to implement llvm.longjmp.
1272  bool usesUnderscoreLongJmp() const {
1273  return UseUnderscoreLongJmp;
1274  }
1275 
1276  /// Return lower limit for number of blocks in a jump table.
1277  unsigned getMinimumJumpTableEntries() const;
1278 
1279  /// Return lower limit of the density in a jump table.
1280  unsigned getMinimumJumpTableDensity(bool OptForSize) const;
1281 
1282  /// Return upper limit for number of entries in a jump table.
1283  /// Zero if no limit.
1284  unsigned getMaximumJumpTableSize() const;
1285 
1286  virtual bool isJumpTableRelative() const {
1287  return TM.isPositionIndependent();
1288  }
1289 
1290  /// If a physical register, this specifies the register that
1291  /// llvm.savestack/llvm.restorestack should save and restore.
1293  return StackPointerRegisterToSaveRestore;
1294  }
1295 
1296  /// If a physical register, this returns the register that receives the
1297  /// exception address on entry to an EH pad.
1298  virtual unsigned
1299  getExceptionPointerRegister(const Constant *PersonalityFn) const {
1300  // 0 is guaranteed to be the NoRegister value on all targets
1301  return 0;
1302  }
1303 
1304  /// If a physical register, this returns the register that receives the
1305  /// exception typeid on entry to a landing pad.
1306  virtual unsigned
1307  getExceptionSelectorRegister(const Constant *PersonalityFn) const {
1308  // 0 is guaranteed to be the NoRegister value on all targets
1309  return 0;
1310  }
1311 
1312  virtual bool needsFixedCatchObjects() const {
1313  report_fatal_error("Funclet EH is not implemented for this target");
1314  }
1315 
1316  /// Returns the target's jmp_buf size in bytes (if never set, the default is
1317  /// 200)
1318  unsigned getJumpBufSize() const {
1319  return JumpBufSize;
1320  }
1321 
1322  /// Returns the target's jmp_buf alignment in bytes (if never set, the default
1323  /// is 0)
1324  unsigned getJumpBufAlignment() const {
1325  return JumpBufAlignment;
1326  }
1327 
1328  /// Return the minimum stack alignment of an argument.
1329  unsigned getMinStackArgumentAlignment() const {
1330  return MinStackArgumentAlignment;
1331  }
1332 
1333  /// Return the minimum function alignment.
1334  unsigned getMinFunctionAlignment() const {
1335  return MinFunctionAlignment;
1336  }
1337 
1338  /// Return the preferred function alignment.
1339  unsigned getPrefFunctionAlignment() const {
1340  return PrefFunctionAlignment;
1341  }
1342 
1343  /// Return the preferred loop alignment.
1344  virtual unsigned getPrefLoopAlignment(MachineLoop *ML = nullptr) const {
1345  return PrefLoopAlignment;
1346  }
1347 
1348  /// If the target has a standard location for the stack protector guard,
1349  /// returns the address of that location. Otherwise, returns nullptr.
1350  /// DEPRECATED: please override useLoadStackGuardNode and customize
1351  /// LOAD_STACK_GUARD, or customize @llvm.stackguard().
1352  virtual Value *getIRStackGuard(IRBuilder<> &IRB) const;
1353 
1354  /// Inserts necessary declarations for SSP (stack protection) purpose.
1355  /// Should be used only when getIRStackGuard returns nullptr.
1356  virtual void insertSSPDeclarations(Module &M) const;
1357 
1358  /// Return the variable that's previously inserted by insertSSPDeclarations,
1359  /// if any, otherwise return nullptr. Should be used only when
1360  /// getIRStackGuard returns nullptr.
1361  virtual Value *getSDagStackGuard(const Module &M) const;
1362 
1363  /// If the target has a standard stack protection check function that
1364  /// performs validation and error handling, returns the function. Otherwise,
1365  /// returns nullptr. Must be previously inserted by insertSSPDeclarations.
1366  /// Should be used only when getIRStackGuard returns nullptr.
1367  virtual Value *getSSPStackGuardCheck(const Module &M) const;
1368 
1369 protected:
1370  Value *getDefaultSafeStackPointerLocation(IRBuilder<> &IRB,
1371  bool UseTLS) const;
1372 
1373 public:
1374  /// Returns the target-specific address of the unsafe stack pointer.
1375  virtual Value *getSafeStackPointerLocation(IRBuilder<> &IRB) const;
1376 
1377  /// Returns the name of the symbol used to emit stack probes or the empty
1378  /// string if not applicable.
1380  return "";
1381  }
1382 
1383  /// Returns true if a cast between SrcAS and DestAS is a noop.
1384  virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const {
1385  return false;
1386  }
1387 
1388  /// Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g. we
1389  /// are happy to sink it into basic blocks.
1390  virtual bool isCheapAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const {
1391  return isNoopAddrSpaceCast(SrcAS, DestAS);
1392  }
1393 
1394  /// Return true if the pointer arguments to CI should be aligned by aligning
1395  /// the object whose address is being passed. If so then MinSize is set to the
1396  /// minimum size the object must be to be aligned and PrefAlign is set to the
1397  /// preferred alignment.
1398  virtual bool shouldAlignPointerArgs(CallInst * /*CI*/, unsigned & /*MinSize*/,
1399  unsigned & /*PrefAlign*/) const {
1400  return false;
1401  }
1402 
1403  //===--------------------------------------------------------------------===//
1404  /// \name Helpers for TargetTransformInfo implementations
1405  /// @{
1406 
1407  /// Get the ISD node that corresponds to the Instruction class opcode.
1408  int InstructionOpcodeToISD(unsigned Opcode) const;
1409 
1410  /// Estimate the cost of type-legalization and the legalized type.
1411  std::pair<int, MVT> getTypeLegalizationCost(const DataLayout &DL,
1412  Type *Ty) const;
1413 
1414  /// @}
1415 
1416  //===--------------------------------------------------------------------===//
1417  /// \name Helpers for atomic expansion.
1418  /// @{
1419 
1420  /// Returns the maximum atomic operation size (in bits) supported by
1421  /// the backend. Atomic operations greater than this size (as well
1422  /// as ones that are not naturally aligned), will be expanded by
1423  /// AtomicExpandPass into an __atomic_* library call.
1425  return MaxAtomicSizeInBitsSupported;
1426  }
1427 
1428  /// Returns the size of the smallest cmpxchg or ll/sc instruction
1429  /// the backend supports. Any smaller operations are widened in
1430  /// AtomicExpandPass.
1431  ///
1432  /// Note that *unlike* operations above the maximum size, atomic ops
1433  /// are still natively supported below the minimum; they just
1434  /// require a more complex expansion.
1435  unsigned getMinCmpXchgSizeInBits() const { return MinCmpXchgSizeInBits; }
1436 
1437  /// Whether AtomicExpandPass should automatically insert fences and reduce
1438  /// ordering for this atomic. This should be true for most architectures with
1439  /// weak memory ordering. Defaults to false.
1440  virtual bool shouldInsertFencesForAtomic(const Instruction *I) const {
1441  return false;
1442  }
1443 
1444  /// Perform a load-linked operation on Addr, returning a "Value *" with the
1445  /// corresponding pointee type. This may entail some non-trivial operations to
1446  /// truncate or reconstruct types that will be illegal in the backend. See
1447  /// ARMISelLowering for an example implementation.
1448  virtual Value *emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
1449  AtomicOrdering Ord) const {
1450  llvm_unreachable("Load linked unimplemented on this target");
1451  }
1452 
1453  /// Perform a store-conditional operation to Addr. Return the status of the
1454  /// store. This should be 0 if the store succeeded, non-zero otherwise.
1455  virtual Value *emitStoreConditional(IRBuilder<> &Builder, Value *Val,
1456  Value *Addr, AtomicOrdering Ord) const {
1457  llvm_unreachable("Store conditional unimplemented on this target");
1458  }
1459 
1460  /// Inserts in the IR a target-specific intrinsic specifying a fence.
1461  /// It is called by AtomicExpandPass before expanding an
1462  /// AtomicRMW/AtomicCmpXchg/AtomicStore/AtomicLoad
1463  /// if shouldInsertFencesForAtomic returns true.
1464  ///
1465  /// Inst is the original atomic instruction, prior to other expansions that
1466  /// may be performed.
1467  ///
1468  /// This function should either return a nullptr, or a pointer to an IR-level
1469  /// Instruction*. Even complex fence sequences can be represented by a
1470  /// single Instruction* through an intrinsic to be lowered later.
1471  /// Backends should override this method to produce target-specific intrinsic
1472  /// for their fences.
1473  /// FIXME: Please note that the default implementation here in terms of
1474  /// IR-level fences exists for historical/compatibility reasons and is
1475  /// *unsound* ! Fences cannot, in general, be used to restore sequential
1476  /// consistency. For example, consider the following example:
1477  /// atomic<int> x = y = 0;
1478  /// int r1, r2, r3, r4;
1479  /// Thread 0:
1480  /// x.store(1);
1481  /// Thread 1:
1482  /// y.store(1);
1483  /// Thread 2:
1484  /// r1 = x.load();
1485  /// r2 = y.load();
1486  /// Thread 3:
1487  /// r3 = y.load();
1488  /// r4 = x.load();
1489  /// r1 = r3 = 1 and r2 = r4 = 0 is impossible as long as the accesses are all
1490  /// seq_cst. But if they are lowered to monotonic accesses, no amount of
1491  /// IR-level fences can prevent it.
1492  /// @{
1494  AtomicOrdering Ord) const {
1495  if (isReleaseOrStronger(Ord) && Inst->hasAtomicStore())
1496  return Builder.CreateFence(Ord);
1497  else
1498  return nullptr;
1499  }
1500 
1502  Instruction *Inst,
1503  AtomicOrdering Ord) const {
1504  if (isAcquireOrStronger(Ord))
1505  return Builder.CreateFence(Ord);
1506  else
1507  return nullptr;
1508  }
1509  /// @}
1510 
1511  // Emits code that executes when the comparison result in the ll/sc
1512  // expansion of a cmpxchg instruction is such that the store-conditional will
1513  // not execute. This makes it possible to balance out the load-linked with
1514  // a dedicated instruction, if desired.
1515  // E.g., on ARM, if ldrex isn't followed by strex, the exclusive monitor would
1516  // be unnecessarily held, except if clrex, inserted by this hook, is executed.
1517  virtual void emitAtomicCmpXchgNoStoreLLBalance(IRBuilder<> &Builder) const {}
1518 
1519  /// Returns true if the given (atomic) store should be expanded by the
1520  /// IR-level AtomicExpand pass into an "atomic xchg" which ignores its input.
1522  return false;
1523  }
1524 
1525  /// Returns true if arguments should be sign-extended in lib calls.
1526  virtual bool shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
1527  return IsSigned;
1528  }
1529 
1530  /// Returns how the given (atomic) load should be expanded by the
1531  /// IR-level AtomicExpand pass.
1534  }
1535 
1536  /// Returns true if the given atomic cmpxchg should be expanded by the
1537  /// IR-level AtomicExpand pass into a load-linked/store-conditional sequence
1538  /// (through emitLoadLinked() and emitStoreConditional()).
1540  return false;
1541  }
1542 
1543  /// Returns how the IR-level AtomicExpand pass should expand the given
1544  /// AtomicRMW, if at all. Default is to never expand.
1547  }
1548 
1549  /// On some platforms, an AtomicRMW that never actually modifies the value
1550  /// (such as fetch_add of 0) can be turned into a fence followed by an
1551  /// atomic load. This may sound useless, but it makes it possible for the
1552  /// processor to keep the cacheline shared, dramatically improving
1553  /// performance. And such idempotent RMWs are useful for implementing some
1554  /// kinds of locks, see for example (justification + benchmarks):
1555  /// http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf
1556  /// This method tries doing that transformation, returning the atomic load if
1557  /// it succeeds, and nullptr otherwise.
1558  /// If shouldExpandAtomicLoadInIR returns true on that load, it will undergo
1559  /// another round of expansion.
1560  virtual LoadInst *
1562  return nullptr;
1563  }
1564 
1565  /// Returns how the platform's atomic operations are extended (ZERO_EXTEND,
1566  /// SIGN_EXTEND, or ANY_EXTEND).
1568  return ISD::ZERO_EXTEND;
1569  }
1570 
1571  /// @}
1572 
1573  /// Returns true if we should normalize
1574  /// select(N0&N1, X, Y) => select(N0, select(N1, X, Y), Y) and
1575  /// select(N0|N1, X, Y) => select(N0, select(N1, X, Y, Y)) if it is likely
1576  /// that it saves us from materializing N0 and N1 in an integer register.
1577  /// Targets that are able to perform and/or on flags should return false here.
1579  EVT VT) const {
1580  // If a target has multiple condition registers, then it likely has logical
1581  // operations on those registers.
1582  if (hasMultipleConditionRegisters())
1583  return false;
1584  // Only do the transform if the value won't be split into multiple
1585  // registers.
1586  LegalizeTypeAction Action = getTypeAction(Context, VT);
1587  return Action != TypeExpandInteger && Action != TypeExpandFloat &&
1588  Action != TypeSplitVector;
1589  }
1590 
1591  /// Return true if a select of constants (select Cond, C1, C2) should be
1592  /// transformed into simple math ops with the condition value. For example:
1593  /// select Cond, C1, C1-1 --> add (zext Cond), C1-1
1594  virtual bool convertSelectOfConstantsToMath(EVT VT) const {
1595  return false;
1596  }
1597 
1598  //===--------------------------------------------------------------------===//
1599  // TargetLowering Configuration Methods - These methods should be invoked by
1600  // the derived class constructor to configure this object for the target.
1601  //
1602 protected:
1603  /// Specify how the target extends the result of integer and floating point
1604  /// boolean values from i1 to a wider type. See getBooleanContents.
1606  BooleanContents = Ty;
1607  BooleanFloatContents = Ty;
1608  }
1609 
1610  /// Specify how the target extends the result of integer and floating point
1611  /// boolean values from i1 to a wider type. See getBooleanContents.
1613  BooleanContents = IntTy;
1614  BooleanFloatContents = FloatTy;
1615  }
1616 
1617  /// Specify how the target extends the result of a vector boolean value from a
1618  /// vector of i1 to a wider type. See getBooleanContents.
1620  BooleanVectorContents = Ty;
1621  }
1622 
1623  /// Specify the target scheduling preference.
1625  SchedPreferenceInfo = Pref;
1626  }
1627 
1628  /// Indicate whether this target prefers to use _setjmp to implement
1629  /// llvm.setjmp or the version without _. Defaults to false.
1630  void setUseUnderscoreSetJmp(bool Val) {
1631  UseUnderscoreSetJmp = Val;
1632  }
1633 
1634  /// Indicate whether this target prefers to use _longjmp to implement
1635  /// llvm.longjmp or the version without _. Defaults to false.
1636  void setUseUnderscoreLongJmp(bool Val) {
1637  UseUnderscoreLongJmp = Val;
1638  }
1639 
1640  /// Indicate the minimum number of blocks to generate jump tables.
1641  void setMinimumJumpTableEntries(unsigned Val);
1642 
1643  /// Indicate the maximum number of entries in jump tables.
1644  /// Set to zero to generate unlimited jump tables.
1645  void setMaximumJumpTableSize(unsigned);
1646 
1647  /// If set to a physical register, this specifies the register that
1648  /// llvm.savestack/llvm.restorestack should save and restore.
1650  StackPointerRegisterToSaveRestore = R;
1651  }
1652 
1653  /// Tells the code generator that the target has multiple (allocatable)
1654  /// condition registers that can be used to store the results of comparisons
1655  /// for use by selects and conditional branches. With multiple condition
1656  /// registers, the code generator will not aggressively sink comparisons into
1657  /// the blocks of their users.
1658  void setHasMultipleConditionRegisters(bool hasManyRegs = true) {
1659  HasMultipleConditionRegisters = hasManyRegs;
1660  }
1661 
1662  /// Tells the code generator that the target has BitExtract instructions.
1663  /// The code generator will aggressively sink "shift"s into the blocks of
1664  /// their users if the users will generate "and" instructions which can be
1665  /// combined with "shift" to BitExtract instructions.
1666  void setHasExtractBitsInsn(bool hasExtractInsn = true) {
1667  HasExtractBitsInsn = hasExtractInsn;
1668  }
1669 
1670  /// Tells the code generator not to expand logic operations on comparison
1671  /// predicates into separate sequences that increase the amount of flow
1672  /// control.
1673  void setJumpIsExpensive(bool isExpensive = true);
1674 
1675  /// Tells the code generator that this target supports floating point
1676  /// exceptions and cares about preserving floating point exception behavior.
1677  void setHasFloatingPointExceptions(bool FPExceptions = true) {
1678  HasFloatingPointExceptions = FPExceptions;
1679  }
1680 
1681  /// Tells the code generator which bitwidths to bypass.
1682  void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
1683  BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
1684  }
1685 
1686  /// Add the specified register class as an available regclass for the
1687  /// specified value type. This indicates the selector can handle values of
1688  /// that class natively.
1690  assert((unsigned)VT.SimpleTy < array_lengthof(RegClassForVT));
1691  RegClassForVT[VT.SimpleTy] = RC;
1692  }
1693 
1694  /// Return the largest legal super-reg register class of the register class
1695  /// for the specified type and its associated "cost".
1696  virtual std::pair<const TargetRegisterClass *, uint8_t>
1697  findRepresentativeClass(const TargetRegisterInfo *TRI, MVT VT) const;
1698 
1699  /// Once all of the register classes are added, this allows us to compute
1700  /// derived properties we expose.
1701  void computeRegisterProperties(const TargetRegisterInfo *TRI);
1702 
1703  /// Indicate that the specified operation does not work with the specified
1704  /// type and indicate what to do about it. Note that VT may refer to either
1705  /// the type of a result or that of an operand of Op.
1706  void setOperationAction(unsigned Op, MVT VT,
1707  LegalizeAction Action) {
1708  assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
1709  OpActions[(unsigned)VT.SimpleTy][Op] = Action;
1710  }
1711 
1712  /// Indicate that the specified load with extension does not work with the
1713  /// specified type and indicate what to do about it.
1714  void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT,
1715  LegalizeAction Action) {
1716  assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() &&
1717  MemVT.isValid() && "Table isn't big enough!");
1718  assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
1719  unsigned Shift = 4 * ExtType;
1720  LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] &= ~((uint16_t)0xF << Shift);
1721  LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] |= (uint16_t)Action << Shift;
1722  }
1723 
1724  /// Indicate that the specified truncating store does not work with the
1725  /// specified type and indicate what to do about it.
1726  void setTruncStoreAction(MVT ValVT, MVT MemVT,
1727  LegalizeAction Action) {
1728  assert(ValVT.isValid() && MemVT.isValid() && "Table isn't big enough!");
1729  TruncStoreActions[(unsigned)ValVT.SimpleTy][MemVT.SimpleTy] = Action;
1730  }
1731 
1732  /// Indicate that the specified indexed load does or does not work with the
1733  /// specified type and indicate what to do abort it.
1734  ///
1735  /// NOTE: All indexed mode loads are initialized to Expand in
1736  /// TargetLowering.cpp
1737  void setIndexedLoadAction(unsigned IdxMode, MVT VT,
1738  LegalizeAction Action) {
1739  assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&
1740  (unsigned)Action < 0xf && "Table isn't big enough!");
1741  // Load action are kept in the upper half.
1742  IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0xf0;
1743  IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action) <<4;
1744  }
1745 
1746  /// Indicate that the specified indexed store does or does not work with the
1747  /// specified type and indicate what to do about it.
1748  ///
1749  /// NOTE: All indexed mode stores are initialized to Expand in
1750  /// TargetLowering.cpp
1751  void setIndexedStoreAction(unsigned IdxMode, MVT VT,
1752  LegalizeAction Action) {
1753  assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&
1754  (unsigned)Action < 0xf && "Table isn't big enough!");
1755  // Store action are kept in the lower half.
1756  IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0x0f;
1757  IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action);
1758  }
1759 
1760  /// Indicate that the specified condition code is or isn't supported on the
1761  /// target and indicate what to do about it.
1763  LegalizeAction Action) {
1764  assert(VT.isValid() && (unsigned)CC < array_lengthof(CondCodeActions) &&
1765  "Table isn't big enough!");
1766  assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
1767  /// The lower 3 bits of the SimpleTy index into Nth 4bit set from the 32-bit
1768  /// value and the upper 29 bits index into the second dimension of the array
1769  /// to select what 32-bit value to use.
1770  uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
1771  CondCodeActions[CC][VT.SimpleTy >> 3] &= ~((uint32_t)0xF << Shift);
1772  CondCodeActions[CC][VT.SimpleTy >> 3] |= (uint32_t)Action << Shift;
1773  }
1774 
1775  /// If Opc/OrigVT is specified as being promoted, the promotion code defaults
1776  /// to trying a larger integer/fp until it can find one that works. If that
1777  /// default is insufficient, this method can be used by the target to override
1778  /// the default.
1779  void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1780  PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
1781  }
1782 
1783  /// Convenience method to set an operation to Promote and specify the type
1784  /// in a single call.
1785  void setOperationPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1786  setOperationAction(Opc, OrigVT, Promote);
1787  AddPromotedToType(Opc, OrigVT, DestVT);
1788  }
1789 
1790  /// Targets should invoke this method for each target independent node that
1791  /// they want to provide a custom DAG combiner for by implementing the
1792  /// PerformDAGCombine virtual method.
1794  assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1795  TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
1796  }
1797 
1798  /// Set the target's required jmp_buf buffer size (in bytes); default is 200
1799  void setJumpBufSize(unsigned Size) {
1800  JumpBufSize = Size;
1801  }
1802 
1803  /// Set the target's required jmp_buf buffer alignment (in bytes); default is
1804  /// 0
1805  void setJumpBufAlignment(unsigned Align) {
1806  JumpBufAlignment = Align;
1807  }
1808 
1809  /// Set the target's minimum function alignment (in log2(bytes))
1811  MinFunctionAlignment = Align;
1812  }
1813 
1814  /// Set the target's preferred function alignment. This should be set if
1815  /// there is a performance benefit to higher-than-minimum alignment (in
1816  /// log2(bytes))
1818  PrefFunctionAlignment = Align;
1819  }
1820 
1821  /// Set the target's preferred loop alignment. Default alignment is zero, it
1822  /// means the target does not care about loop alignment. The alignment is
1823  /// specified in log2(bytes). The target may also override
1824  /// getPrefLoopAlignment to provide per-loop values.
1825  void setPrefLoopAlignment(unsigned Align) {
1826  PrefLoopAlignment = Align;
1827  }
1828 
1829  /// Set the minimum stack alignment of an argument (in log2(bytes)).
1831  MinStackArgumentAlignment = Align;
1832  }
1833 
1834  /// Set the maximum atomic operation size supported by the
1835  /// backend. Atomic operations greater than this size (as well as
1836  /// ones that are not naturally aligned), will be expanded by
1837  /// AtomicExpandPass into an __atomic_* library call.
1838  void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits) {
1839  MaxAtomicSizeInBitsSupported = SizeInBits;
1840  }
1841 
1842  // Sets the minimum cmpxchg or ll/sc size supported by the backend.
1843  void setMinCmpXchgSizeInBits(unsigned SizeInBits) {
1844  MinCmpXchgSizeInBits = SizeInBits;
1845  }
1846 
1847 public:
1848  //===--------------------------------------------------------------------===//
1849  // Addressing mode description hooks (used by LSR etc).
1850  //
1851 
1852  /// CodeGenPrepare sinks address calculations into the same BB as Load/Store
1853  /// instructions reading the address. This allows as much computation as
1854  /// possible to be done in the address mode for that operand. This hook lets
1855  /// targets also pass back when this should be done on intrinsics which
1856  /// load/store.
1857  virtual bool getAddrModeArguments(IntrinsicInst * /*I*/,
1858  SmallVectorImpl<Value*> &/*Ops*/,
1859  Type *&/*AccessTy*/) const {
1860  return false;
1861  }
1862 
1863  /// This represents an addressing mode of:
1864  /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
1865  /// If BaseGV is null, there is no BaseGV.
1866  /// If BaseOffs is zero, there is no base offset.
1867  /// If HasBaseReg is false, there is no base register.
1868  /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
1869  /// no scale.
1870  struct AddrMode {
1871  GlobalValue *BaseGV = nullptr;
1872  int64_t BaseOffs = 0;
1873  bool HasBaseReg = false;
1874  int64_t Scale = 0;
1875  AddrMode() = default;
1876  };
1877 
1878  /// Return true if the addressing mode represented by AM is legal for this
1879  /// target, for a load/store of the specified type.
1880  ///
1881  /// The type may be VoidTy, in which case only return true if the addressing
1882  /// mode is legal for a load/store of any legal type. TODO: Handle
1883  /// pre/postinc as well.
1884  ///
1885  /// If the address space cannot be determined, it will be -1.
1886  ///
1887  /// TODO: Remove default argument
1888  virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM,
1889  Type *Ty, unsigned AddrSpace,
1890  Instruction *I = nullptr) const;
1891 
1892  /// \brief Return the cost of the scaling factor used in the addressing mode
1893  /// represented by AM for this target, for a load/store of the specified type.
1894  ///
1895  /// If the AM is supported, the return value must be >= 0.
1896  /// If the AM is not supported, it returns a negative value.
1897  /// TODO: Handle pre/postinc as well.
1898  /// TODO: Remove default argument
1899  virtual int getScalingFactorCost(const DataLayout &DL, const AddrMode &AM,
1900  Type *Ty, unsigned AS = 0) const {
1901  // Default: assume that any scaling factor used in a legal AM is free.
1902  if (isLegalAddressingMode(DL, AM, Ty, AS))
1903  return 0;
1904  return -1;
1905  }
1906 
1907  /// Return true if the specified immediate is legal icmp immediate, that is
1908  /// the target has icmp instructions which can compare a register against the
1909  /// immediate without having to materialize the immediate into a register.
1910  virtual bool isLegalICmpImmediate(int64_t) const {
1911  return true;
1912  }
1913 
1914  /// Return true if the specified immediate is legal add immediate, that is the
1915  /// target has add instructions which can add a register with the immediate
1916  /// without having to materialize the immediate into a register.
1917  virtual bool isLegalAddImmediate(int64_t) const {
1918  return true;
1919  }
1920 
1921  /// Return true if it's significantly cheaper to shift a vector by a uniform
1922  /// scalar than by an amount which will vary across each lane. On x86, for
1923  /// example, there is a "psllw" instruction for the former case, but no simple
1924  /// instruction for a general "a << b" operation on vectors.
1925  virtual bool isVectorShiftByScalarCheap(Type *Ty) const {
1926  return false;
1927  }
1928 
1929  /// Returns true if the opcode is a commutative binary operation.
1930  virtual bool isCommutativeBinOp(unsigned Opcode) const {
1931  // FIXME: This should get its info from the td file.
1932  switch (Opcode) {
1933  case ISD::ADD:
1934  case ISD::SMIN:
1935  case ISD::SMAX:
1936  case ISD::UMIN:
1937  case ISD::UMAX:
1938  case ISD::MUL:
1939  case ISD::MULHU:
1940  case ISD::MULHS:
1941  case ISD::SMUL_LOHI:
1942  case ISD::UMUL_LOHI:
1943  case ISD::FADD:
1944  case ISD::FMUL:
1945  case ISD::AND:
1946  case ISD::OR:
1947  case ISD::XOR:
1948  case ISD::SADDO:
1949  case ISD::UADDO:
1950  case ISD::ADDC:
1951  case ISD::ADDE:
1952  case ISD::FMINNUM:
1953  case ISD::FMAXNUM:
1954  case ISD::FMINNAN:
1955  case ISD::FMAXNAN:
1956  return true;
1957  default: return false;
1958  }
1959  }
1960 
1961  /// Return true if it's free to truncate a value of type FromTy to type
1962  /// ToTy. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
1963  /// by referencing its sub-register AX.
1964  /// Targets must return false when FromTy <= ToTy.
1965  virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const {
1966  return false;
1967  }
1968 
1969  /// Return true if a truncation from FromTy to ToTy is permitted when deciding
1970  /// whether a call is in tail position. Typically this means that both results
1971  /// would be assigned to the same register or stack slot, but it could mean
1972  /// the target performs adequate checks of its own before proceeding with the
1973  /// tail call. Targets must return false when FromTy <= ToTy.
1974  virtual bool allowTruncateForTailCall(Type *FromTy, Type *ToTy) const {
1975  return false;
1976  }
1977 
1978  virtual bool isTruncateFree(EVT FromVT, EVT ToVT) const {
1979  return false;
1980  }
1981 
1982  virtual bool isProfitableToHoist(Instruction *I) const { return true; }
1983 
1984  /// Return true if the extension represented by \p I is free.
1985  /// Unlikely the is[Z|FP]ExtFree family which is based on types,
1986  /// this method can use the context provided by \p I to decide
1987  /// whether or not \p I is free.
1988  /// This method extends the behavior of the is[Z|FP]ExtFree family.
1989  /// In other words, if is[Z|FP]Free returns true, then this method
1990  /// returns true as well. The converse is not true.
1991  /// The target can perform the adequate checks by overriding isExtFreeImpl.
1992  /// \pre \p I must be a sign, zero, or fp extension.
1993  bool isExtFree(const Instruction *I) const {
1994  switch (I->getOpcode()) {
1995  case Instruction::FPExt:
1996  if (isFPExtFree(EVT::getEVT(I->getType()),
1997  EVT::getEVT(I->getOperand(0)->getType())))
1998  return true;
1999  break;
2000  case Instruction::ZExt:
2001  if (isZExtFree(I->getOperand(0)->getType(), I->getType()))
2002  return true;
2003  break;
2004  case Instruction::SExt:
2005  break;
2006  default:
2007  llvm_unreachable("Instruction is not an extension");
2008  }
2009  return isExtFreeImpl(I);
2010  }
2011 
2012  /// Return true if \p Load and \p Ext can form an ExtLoad.
2013  /// For example, in AArch64
2014  /// %L = load i8, i8* %ptr
2015  /// %E = zext i8 %L to i32
2016  /// can be lowered into one load instruction
2017  /// ldrb w0, [x0]
2018  bool isExtLoad(const LoadInst *Load, const Instruction *Ext,
2019  const DataLayout &DL) const {
2020  EVT VT = getValueType(DL, Ext->getType());
2021  EVT LoadVT = getValueType(DL, Load->getType());
2022 
2023  // If the load has other users and the truncate is not free, the ext
2024  // probably isn't free.
2025  if (!Load->hasOneUse() && (isTypeLegal(LoadVT) || !isTypeLegal(VT)) &&
2026  !isTruncateFree(Ext->getType(), Load->getType()))
2027  return false;
2028 
2029  // Check whether the target supports casts folded into loads.
2030  unsigned LType;
2031  if (isa<ZExtInst>(Ext))
2032  LType = ISD::ZEXTLOAD;
2033  else {
2034  assert(isa<SExtInst>(Ext) && "Unexpected ext type!");
2035  LType = ISD::SEXTLOAD;
2036  }
2037 
2038  return isLoadExtLegal(LType, VT, LoadVT);
2039  }
2040 
2041  /// Return true if any actual instruction that defines a value of type FromTy
2042  /// implicitly zero-extends the value to ToTy in the result register.
2043  ///
2044  /// The function should return true when it is likely that the truncate can
2045  /// be freely folded with an instruction defining a value of FromTy. If
2046  /// the defining instruction is unknown (because you're looking at a
2047  /// function argument, PHI, etc.) then the target may require an
2048  /// explicit truncate, which is not necessarily free, but this function
2049  /// does not deal with those cases.
2050  /// Targets must return false when FromTy >= ToTy.
2051  virtual bool isZExtFree(Type *FromTy, Type *ToTy) const {
2052  return false;
2053  }
2054 
2055  virtual bool isZExtFree(EVT FromTy, EVT ToTy) const {
2056  return false;
2057  }
2058 
2059  /// Return true if the target supplies and combines to a paired load
2060  /// two loaded values of type LoadedType next to each other in memory.
2061  /// RequiredAlignment gives the minimal alignment constraints that must be met
2062  /// to be able to select this paired load.
2063  ///
2064  /// This information is *not* used to generate actual paired loads, but it is
2065  /// used to generate a sequence of loads that is easier to combine into a
2066  /// paired load.
2067  /// For instance, something like this:
2068  /// a = load i64* addr
2069  /// b = trunc i64 a to i32
2070  /// c = lshr i64 a, 32
2071  /// d = trunc i64 c to i32
2072  /// will be optimized into:
2073  /// b = load i32* addr1
2074  /// d = load i32* addr2
2075  /// Where addr1 = addr2 +/- sizeof(i32).
2076  ///
2077  /// In other words, unless the target performs a post-isel load combining,
2078  /// this information should not be provided because it will generate more
2079  /// loads.
2080  virtual bool hasPairedLoad(EVT /*LoadedType*/,
2081  unsigned & /*RequiredAlignment*/) const {
2082  return false;
2083  }
2084 
2085  /// \brief Get the maximum supported factor for interleaved memory accesses.
2086  /// Default to be the minimum interleave factor: 2.
2087  virtual unsigned getMaxSupportedInterleaveFactor() const { return 2; }
2088 
2089  /// \brief Lower an interleaved load to target specific intrinsics. Return
2090  /// true on success.
2091  ///
2092  /// \p LI is the vector load instruction.
2093  /// \p Shuffles is the shufflevector list to DE-interleave the loaded vector.
2094  /// \p Indices is the corresponding indices for each shufflevector.
2095  /// \p Factor is the interleave factor.
2096  virtual bool lowerInterleavedLoad(LoadInst *LI,
2098  ArrayRef<unsigned> Indices,
2099  unsigned Factor) const {
2100  return false;
2101  }
2102 
2103  /// \brief Lower an interleaved store to target specific intrinsics. Return
2104  /// true on success.
2105  ///
2106  /// \p SI is the vector store instruction.
2107  /// \p SVI is the shufflevector to RE-interleave the stored vector.
2108  /// \p Factor is the interleave factor.
2110  unsigned Factor) const {
2111  return false;
2112  }
2113 
2114  /// Return true if zero-extending the specific node Val to type VT2 is free
2115  /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
2116  /// because it's folded such as X86 zero-extending loads).
2117  virtual bool isZExtFree(SDValue Val, EVT VT2) const {
2118  return isZExtFree(Val.getValueType(), VT2);
2119  }
2120 
2121  /// Return true if an fpext operation is free (for instance, because
2122  /// single-precision floating-point numbers are implicitly extended to
2123  /// double-precision).
2124  virtual bool isFPExtFree(EVT DestVT, EVT SrcVT) const {
2125  assert(SrcVT.isFloatingPoint() && DestVT.isFloatingPoint() &&
2126  "invalid fpext types");
2127  return false;
2128  }
2129 
2130  /// Return true if an fpext operation input to an \p Opcode operation is free
2131  /// (for instance, because half-precision floating-point numbers are
2132  /// implicitly extended to float-precision) for an FMA instruction.
2133  virtual bool isFPExtFoldable(unsigned Opcode, EVT DestVT, EVT SrcVT) const {
2134  assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
2135  "invalid fpext types");
2136  return isFPExtFree(DestVT, SrcVT);
2137  }
2138 
2139  /// Return true if folding a vector load into ExtVal (a sign, zero, or any
2140  /// extend node) is profitable.
2141  virtual bool isVectorLoadExtDesirable(SDValue ExtVal) const { return false; }
2142 
2143  /// Return true if an fneg operation is free to the point where it is never
2144  /// worthwhile to replace it with a bitwise operation.
2145  virtual bool isFNegFree(EVT VT) const {
2146  assert(VT.isFloatingPoint());
2147  return false;
2148  }
2149 
2150  /// Return true if an fabs operation is free to the point where it is never
2151  /// worthwhile to replace it with a bitwise operation.
2152  virtual bool isFAbsFree(EVT VT) const {
2153  assert(VT.isFloatingPoint());
2154  return false;
2155  }
2156 
2157  /// Return true if an FMA operation is faster than a pair of fmul and fadd
2158  /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
2159  /// returns true, otherwise fmuladd is expanded to fmul + fadd.
2160  ///
2161  /// NOTE: This may be called before legalization on types for which FMAs are
2162  /// not legal, but should return true if those types will eventually legalize
2163  /// to types that support FMAs. After legalization, it will only be called on
2164  /// types that support FMAs (via Legal or Custom actions)
2165  virtual bool isFMAFasterThanFMulAndFAdd(EVT) const {
2166  return false;
2167  }
2168 
2169  /// Return true if it's profitable to narrow operations of type VT1 to
2170  /// VT2. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
2171  /// i32 to i16.
2172  virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
2173  return false;
2174  }
2175 
2176  /// \brief Return true if it is beneficial to convert a load of a constant to
2177  /// just the constant itself.
2178  /// On some targets it might be more efficient to use a combination of
2179  /// arithmetic instructions to materialize the constant instead of loading it
2180  /// from a constant pool.
2181  virtual bool shouldConvertConstantLoadToIntImm(const APInt &Imm,
2182  Type *Ty) const {
2183  return false;
2184  }
2185 
2186  /// Return true if EXTRACT_SUBVECTOR is cheap for extracting this result type
2187  /// from this source type with this index. This is needed because
2188  /// EXTRACT_SUBVECTOR usually has custom lowering that depends on the index of
2189  /// the first element, and only the target knows which lowering is cheap.
2190  virtual bool isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
2191  unsigned Index) const {
2192  return false;
2193  }
2194 
2195  // Return true if it is profitable to use a scalar input to a BUILD_VECTOR
2196  // even if the vector itself has multiple uses.
2197  virtual bool aggressivelyPreferBuildVectorSources(EVT VecVT) const {
2198  return false;
2199  }
2200 
2201  //===--------------------------------------------------------------------===//
2202  // Runtime Library hooks
2203  //
2204 
2205  /// Rename the default libcall routine name for the specified libcall.
2206  void setLibcallName(RTLIB::Libcall Call, const char *Name) {
2207  LibcallRoutineNames[Call] = Name;
2208  }
2209 
2210  /// Get the libcall routine name for the specified libcall.
2211  const char *getLibcallName(RTLIB::Libcall Call) const {
2212  return LibcallRoutineNames[Call];
2213  }
2214 
2215  /// Override the default CondCode to be used to test the result of the
2216  /// comparison libcall against zero.
2218  CmpLibcallCCs[Call] = CC;
2219  }
2220 
2221  /// Get the CondCode that's to be used to test the result of the comparison
2222  /// libcall against zero.
2224  return CmpLibcallCCs[Call];
2225  }
2226 
2227  /// Set the CallingConv that should be used for the specified libcall.
2229  LibcallCallingConvs[Call] = CC;
2230  }
2231 
2232  /// Get the CallingConv that should be used for the specified libcall.
2234  return LibcallCallingConvs[Call];
2235  }
2236 
2237  /// Execute target specific actions to finalize target lowering.
2238  /// This is used to set extra flags in MachineFrameInformation and freezing
2239  /// the set of reserved registers.
2240  /// The default implementation just freezes the set of reserved registers.
2241  virtual void finalizeLowering(MachineFunction &MF) const;
2242 
2243 private:
2244  const TargetMachine &TM;
2245 
2246  /// Tells the code generator that the target has multiple (allocatable)
2247  /// condition registers that can be used to store the results of comparisons
2248  /// for use by selects and conditional branches. With multiple condition
2249  /// registers, the code generator will not aggressively sink comparisons into
2250  /// the blocks of their users.
2251  bool HasMultipleConditionRegisters;
2252 
2253  /// Tells the code generator that the target has BitExtract instructions.
2254  /// The code generator will aggressively sink "shift"s into the blocks of
2255  /// their users if the users will generate "and" instructions which can be
2256  /// combined with "shift" to BitExtract instructions.
2257  bool HasExtractBitsInsn;
2258 
2259  /// Tells the code generator to bypass slow divide or remainder
2260  /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
2261  /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
2262  /// div/rem when the operands are positive and less than 256.
2263  DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
2264 
2265  /// Tells the code generator that it shouldn't generate extra flow control
2266  /// instructions and should attempt to combine flow control instructions via
2267  /// predication.
2268  bool JumpIsExpensive;
2269 
2270  /// Whether the target supports or cares about preserving floating point
2271  /// exception behavior.
2272  bool HasFloatingPointExceptions;
2273 
2274  /// This target prefers to use _setjmp to implement llvm.setjmp.
2275  ///
2276  /// Defaults to false.
2277  bool UseUnderscoreSetJmp;
2278 
2279  /// This target prefers to use _longjmp to implement llvm.longjmp.
2280  ///
2281  /// Defaults to false.
2282  bool UseUnderscoreLongJmp;
2283 
2284  /// Information about the contents of the high-bits in boolean values held in
2285  /// a type wider than i1. See getBooleanContents.
2286  BooleanContent BooleanContents;
2287 
2288  /// Information about the contents of the high-bits in boolean values held in
2289  /// a type wider than i1. See getBooleanContents.
2290  BooleanContent BooleanFloatContents;
2291 
2292  /// Information about the contents of the high-bits in boolean vector values
2293  /// when the element type is wider than i1. See getBooleanContents.
2294  BooleanContent BooleanVectorContents;
2295 
2296  /// The target scheduling preference: shortest possible total cycles or lowest
2297  /// register usage.
2298  Sched::Preference SchedPreferenceInfo;
2299 
2300  /// The size, in bytes, of the target's jmp_buf buffers
2301  unsigned JumpBufSize;
2302 
2303  /// The alignment, in bytes, of the target's jmp_buf buffers
2304  unsigned JumpBufAlignment;
2305 
2306  /// The minimum alignment that any argument on the stack needs to have.
2307  unsigned MinStackArgumentAlignment;
2308 
2309  /// The minimum function alignment (used when optimizing for size, and to
2310  /// prevent explicitly provided alignment from leading to incorrect code).
2311  unsigned MinFunctionAlignment;
2312 
2313  /// The preferred function alignment (used when alignment unspecified and
2314  /// optimizing for speed).
2315  unsigned PrefFunctionAlignment;
2316 
2317  /// The preferred loop alignment.
2318  unsigned PrefLoopAlignment;
2319 
2320  /// Size in bits of the maximum atomics size the backend supports.
2321  /// Accesses larger than this will be expanded by AtomicExpandPass.
2322  unsigned MaxAtomicSizeInBitsSupported;
2323 
2324  /// Size in bits of the minimum cmpxchg or ll/sc operation the
2325  /// backend supports.
2326  unsigned MinCmpXchgSizeInBits;
2327 
2328  /// If set to a physical register, this specifies the register that
2329  /// llvm.savestack/llvm.restorestack should save and restore.
2330  unsigned StackPointerRegisterToSaveRestore;
2331 
2332  /// This indicates the default register class to use for each ValueType the
2333  /// target supports natively.
2334  const TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
2335  unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
2336  MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
2337 
2338  /// This indicates the "representative" register class to use for each
2339  /// ValueType the target supports natively. This information is used by the
2340  /// scheduler to track register pressure. By default, the representative
2341  /// register class is the largest legal super-reg register class of the
2342  /// register class of the specified type. e.g. On x86, i8, i16, and i32's
2343  /// representative class would be GR32.
2344  const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
2345 
2346  /// This indicates the "cost" of the "representative" register class for each
2347  /// ValueType. The cost is used by the scheduler to approximate register
2348  /// pressure.
2349  uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
2350 
2351  /// For any value types we are promoting or expanding, this contains the value
2352  /// type that we are changing to. For Expanded types, this contains one step
2353  /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
2354  /// (e.g. i64 -> i16). For types natively supported by the system, this holds
2355  /// the same type (e.g. i32 -> i32).
2356  MVT TransformToType[MVT::LAST_VALUETYPE];
2357 
2358  /// For each operation and each value type, keep a LegalizeAction that
2359  /// indicates how instruction selection should deal with the operation. Most
2360  /// operations are Legal (aka, supported natively by the target), but
2361  /// operations that are not should be described. Note that operations on
2362  /// non-legal value types are not described here.
2364 
2365  /// For each load extension type and each value type, keep a LegalizeAction
2366  /// that indicates how instruction selection should deal with a load of a
2367  /// specific value type and extension type. Uses 4-bits to store the action
2368  /// for each of the 4 load ext types.
2369  uint16_t LoadExtActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
2370 
2371  /// For each value type pair keep a LegalizeAction that indicates whether a
2372  /// truncating store of a specific value type and truncating type is legal.
2374 
2375  /// For each indexed mode and each value type, keep a pair of LegalizeAction
2376  /// that indicates how instruction selection should deal with the load /
2377  /// store.
2378  ///
2379  /// The first dimension is the value_type for the reference. The second
2380  /// dimension represents the various modes for load store.
2381  uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
2382 
2383  /// For each condition code (ISD::CondCode) keep a LegalizeAction that
2384  /// indicates how instruction selection should deal with the condition code.
2385  ///
2386  /// Because each CC action takes up 4 bits, we need to have the array size be
2387  /// large enough to fit all of the value types. This can be done by rounding
2388  /// up the MVT::LAST_VALUETYPE value to the next multiple of 8.
2389  uint32_t CondCodeActions[ISD::SETCC_INVALID][(MVT::LAST_VALUETYPE + 7) / 8];
2390 
2391 protected:
2393 
2394 private:
2395  LegalizeKind getTypeConversion(LLVMContext &Context, EVT VT) const;
2396 
2397  /// Targets can specify ISD nodes that they would like PerformDAGCombine
2398  /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
2399  /// array.
2400  unsigned char
2401  TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
2402 
2403  /// For operations that must be promoted to a specific type, this holds the
2404  /// destination type. This map should be sparse, so don't hold it as an
2405  /// array.
2406  ///
2407  /// Targets add entries to this map with AddPromotedToType(..), clients access
2408  /// this with getTypeToPromoteTo(..).
2409  std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
2410  PromoteToType;
2411 
2412  /// Stores the name each libcall.
2413  const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
2414 
2415  /// The ISD::CondCode that should be used to test the result of each of the
2416  /// comparison libcall against zero.
2417  ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
2418 
2419  /// Stores the CallingConv that should be used for each libcall.
2420  CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
2421 
2422 protected:
2423  /// Return true if the extension represented by \p I is free.
2424  /// \pre \p I is a sign, zero, or fp extension and
2425  /// is[Z|FP]ExtFree of the related types is not true.
2426  virtual bool isExtFreeImpl(const Instruction *I) const { return false; }
2427 
2428  /// Depth that GatherAllAliases should should continue looking for chain
2429  /// dependencies when trying to find a more preferable chain. As an
2430  /// approximation, this should be more than the number of consecutive stores
2431  /// expected to be merged.
2433 
2434  /// \brief Specify maximum number of store instructions per memset call.
2435  ///
2436  /// When lowering \@llvm.memset this field specifies the maximum number of
2437  /// store operations that may be substituted for the call to memset. Targets
2438  /// must set this value based on the cost threshold for that target. Targets
2439  /// should assume that the memset will be done using as many of the largest
2440  /// store operations first, followed by smaller ones, if necessary, per
2441  /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
2442  /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
2443  /// store. This only applies to setting a constant array of a constant size.
2445 
2446  /// Maximum number of stores operations that may be substituted for the call
2447  /// to memset, used for functions with OptSize attribute.
2449 
2450  /// \brief Specify maximum bytes of store instructions per memcpy call.
2451  ///
2452  /// When lowering \@llvm.memcpy this field specifies the maximum number of
2453  /// store operations that may be substituted for a call to memcpy. Targets
2454  /// must set this value based on the cost threshold for that target. Targets
2455  /// should assume that the memcpy will be done using as many of the largest
2456  /// store operations first, followed by smaller ones, if necessary, per
2457  /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
2458  /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
2459  /// and one 1-byte store. This only applies to copying a constant array of
2460  /// constant size.
2462 
2463  /// Maximum number of store operations that may be substituted for a call to
2464  /// memcpy, used for functions with OptSize attribute.
2468 
2469  /// \brief Specify maximum bytes of store instructions per memmove call.
2470  ///
2471  /// When lowering \@llvm.memmove this field specifies the maximum number of
2472  /// store instructions that may be substituted for a call to memmove. Targets
2473  /// must set this value based on the cost threshold for that target. Targets
2474  /// should assume that the memmove will be done using as many of the largest
2475  /// store operations first, followed by smaller ones, if necessary, per
2476  /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
2477  /// with 8-bit alignment would result in nine 1-byte stores. This only
2478  /// applies to copying a constant array of constant size.
2480 
2481  /// Maximum number of store instructions that may be substituted for a call to
2482  /// memmove, used for functions with OptSize attribute.
2484 
2485  /// Tells the code generator that select is more expensive than a branch if
2486  /// the branch is usually predicted right.
2488 
2489  /// \see enableExtLdPromotion.
2491 
2492  /// Return true if the value types that can be represented by the specified
2493  /// register class are all legal.
2494  bool isLegalRC(const TargetRegisterInfo &TRI,
2495  const TargetRegisterClass &RC) const;
2496 
2497  /// Replace/modify any TargetFrameIndex operands with a targte-dependent
2498  /// sequence of memory operands that is recognized by PrologEpilogInserter.
2499  MachineBasicBlock *emitPatchPoint(MachineInstr &MI,
2500  MachineBasicBlock *MBB) const;
2501 };
2502 
2503 /// This class defines information used to lower LLVM code to legal SelectionDAG
2504 /// operators that the target instruction selector can accept natively.
2505 ///
2506 /// This class also defines callbacks that targets must implement to lower
2507 /// target-specific constructs to SelectionDAG operators.
2509 public:
2510  struct DAGCombinerInfo;
2511 
2512  TargetLowering(const TargetLowering &) = delete;
2513  TargetLowering &operator=(const TargetLowering &) = delete;
2514 
2515  /// NOTE: The TargetMachine owns TLOF.
2516  explicit TargetLowering(const TargetMachine &TM);
2517 
2518  bool isPositionIndependent() const;
2519 
2520  /// Returns true by value, base pointer and offset pointer and addressing mode
2521  /// by reference if the node's address can be legally represented as
2522  /// pre-indexed load / store address.
2523  virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
2524  SDValue &/*Offset*/,
2525  ISD::MemIndexedMode &/*AM*/,
2526  SelectionDAG &/*DAG*/) const {
2527  return false;
2528  }
2529 
2530  /// Returns true by value, base pointer and offset pointer and addressing mode
2531  /// by reference if this node can be combined with a load / store to form a
2532  /// post-indexed load / store.
2533  virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
2534  SDValue &/*Base*/,
2535  SDValue &/*Offset*/,
2536  ISD::MemIndexedMode &/*AM*/,
2537  SelectionDAG &/*DAG*/) const {
2538  return false;
2539  }
2540 
2541  /// Return the entry encoding for a jump table in the current function. The
2542  /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
2543  virtual unsigned getJumpTableEncoding() const;
2544 
2545  virtual const MCExpr *
2547  const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
2548  MCContext &/*Ctx*/) const {
2549  llvm_unreachable("Need to implement this hook if target has custom JTIs");
2550  }
2551 
2552  /// Returns relocation base for the given PIC jumptable.
2553  virtual SDValue getPICJumpTableRelocBase(SDValue Table,
2554  SelectionDAG &DAG) const;
2555 
2556  /// This returns the relocation base for the given PIC jumptable, the same as
2557  /// getPICJumpTableRelocBase, but as an MCExpr.
2558  virtual const MCExpr *
2559  getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2560  unsigned JTI, MCContext &Ctx) const;
2561 
2562  /// Return true if folding a constant offset with the given GlobalAddress is
2563  /// legal. It is frequently not legal in PIC relocation models.
2564  virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
2565 
2566  bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
2567  SDValue &Chain) const;
2568 
2569  void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
2570  SDValue &NewRHS, ISD::CondCode &CCCode,
2571  const SDLoc &DL) const;
2572 
2573  /// Returns a pair of (return value, chain).
2574  /// It is an error to pass RTLIB::UNKNOWN_LIBCALL as \p LC.
2575  std::pair<SDValue, SDValue> makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC,
2576  EVT RetVT, ArrayRef<SDValue> Ops,
2577  bool isSigned, const SDLoc &dl,
2578  bool doesNotReturn = false,
2579  bool isReturnValueUsed = true) const;
2580 
2581  /// Check whether parameters to a call that are passed in callee saved
2582  /// registers are the same as from the calling function. This needs to be
2583  /// checked for tail call eligibility.
2584  bool parametersInCSRMatch(const MachineRegisterInfo &MRI,
2585  const uint32_t *CallerPreservedMask,
2586  const SmallVectorImpl<CCValAssign> &ArgLocs,
2587  const SmallVectorImpl<SDValue> &OutVals) const;
2588 
2589  //===--------------------------------------------------------------------===//
2590  // TargetLowering Optimization Methods
2591  //
2592 
2593  /// A convenience struct that encapsulates a DAG, and two SDValues for
2594  /// returning information from TargetLowering to its clients that want to
2595  /// combine.
2598  bool LegalTys;
2599  bool LegalOps;
2602 
2604  bool LT, bool LO) :
2605  DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
2606 
2607  bool LegalTypes() const { return LegalTys; }
2608  bool LegalOperations() const { return LegalOps; }
2609 
2611  Old = O;
2612  New = N;
2613  return true;
2614  }
2615  };
2616 
2617  /// Check to see if the specified operand of the specified instruction is a
2618  /// constant integer. If so, check to see if there are any bits set in the
2619  /// constant that are not demanded. If so, shrink the constant and return
2620  /// true.
2621  bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded,
2622  TargetLoweringOpt &TLO) const;
2623 
2624  // Target hook to do target-specific const optimization, which is called by
2625  // ShrinkDemandedConstant. This function should return true if the target
2626  // doesn't want ShrinkDemandedConstant to further optimize the constant.
2627  virtual bool targetShrinkDemandedConstant(SDValue Op, const APInt &Demanded,
2628  TargetLoweringOpt &TLO) const {
2629  return false;
2630  }
2631 
2632  /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. This
2633  /// uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
2634  /// generalized for targets with other types of implicit widening casts.
2635  bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
2636  TargetLoweringOpt &TLO) const;
2637 
2638  /// Helper for SimplifyDemandedBits that can simplify an operation with
2639  /// multiple uses. This function simplifies operand \p OpIdx of \p User and
2640  /// then updates \p User with the simplified version. No other uses of
2641  /// \p OpIdx are updated. If \p User is the only user of \p OpIdx, this
2642  /// function behaves exactly like function SimplifyDemandedBits declared
2643  /// below except that it also updates the DAG by calling
2644  /// DCI.CommitTargetLoweringOpt.
2645  bool SimplifyDemandedBits(SDNode *User, unsigned OpIdx, const APInt &Demanded,
2646  DAGCombinerInfo &DCI, TargetLoweringOpt &TLO) const;
2647 
2648  /// Look at Op. At this point, we know that only the DemandedMask bits of the
2649  /// result of Op are ever used downstream. If we can use this information to
2650  /// simplify Op, create a new simplified DAG node and return true, returning
2651  /// the original and new nodes in Old and New. Otherwise, analyze the
2652  /// expression and return a mask of KnownOne and KnownZero bits for the
2653  /// expression (used to simplify the caller). The KnownZero/One bits may only
2654  /// be accurate for those bits in the DemandedMask.
2655  /// \p AssumeSingleUse When this parameter is true, this function will
2656  /// attempt to simplify \p Op even if there are multiple uses.
2657  /// Callers are responsible for correctly updating the DAG based on the
2658  /// results of this function, because simply replacing replacing TLO.Old
2659  /// with TLO.New will be incorrect when this parameter is true and TLO.Old
2660  /// has multiple uses.
2661  bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
2662  KnownBits &Known,
2663  TargetLoweringOpt &TLO,
2664  unsigned Depth = 0,
2665  bool AssumeSingleUse = false) const;
2666 
2667  /// Helper wrapper around SimplifyDemandedBits
2668  bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
2669  DAGCombinerInfo &DCI) const;
2670 
2671  /// Determine which of the bits specified in Mask are known to be either zero
2672  /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
2673  /// argument allows us to only collect the known bits that are shared by the
2674  /// requested vector elements.
2675  virtual void computeKnownBitsForTargetNode(const SDValue Op,
2676  KnownBits &Known,
2677  const APInt &DemandedElts,
2678  const SelectionDAG &DAG,
2679  unsigned Depth = 0) const;
2680 
2681  /// Determine which of the bits of FrameIndex \p FIOp are known to be 0.
2682  /// Default implementation computes low bits based on alignment
2683  /// information. This should preserve known bits passed into it.
2684  virtual void computeKnownBitsForFrameIndex(const SDValue FIOp,
2685  KnownBits &Known,
2686  const APInt &DemandedElts,
2687  const SelectionDAG &DAG,
2688  unsigned Depth = 0) const;
2689 
2690  /// This method can be implemented by targets that want to expose additional
2691  /// information about sign bits to the DAG Combiner. The DemandedElts
2692  /// argument allows us to only collect the minimum sign bits that are shared
2693  /// by the requested vector elements.
2694  virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
2695  const APInt &DemandedElts,
2696  const SelectionDAG &DAG,
2697  unsigned Depth = 0) const;
2698 
2700  void *DC; // The DAG Combiner object.
2703 
2704  public:
2706 
2707  DAGCombinerInfo(SelectionDAG &dag, CombineLevel level, bool cl, void *dc)
2708  : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
2709 
2710  bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
2711  bool isBeforeLegalizeOps() const { return Level < AfterLegalizeVectorOps; }
2713  return Level == AfterLegalizeDAG;
2714  }
2716  bool isCalledByLegalizer() const { return CalledByLegalizer; }
2717 
2718  void AddToWorklist(SDNode *N);
2719  SDValue CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo = true);
2720  SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
2721  SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
2722 
2723  void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
2724  };
2725 
2726  /// Return if the N is a constant or constant vector equal to the true value
2727  /// from getBooleanContents().
2728  bool isConstTrueVal(const SDNode *N) const;
2729 
2730  /// Return if the N is a constant or constant vector equal to the false value
2731  /// from getBooleanContents().
2732  bool isConstFalseVal(const SDNode *N) const;
2733 
2734  /// Return a constant of type VT that contains a true value that respects
2735  /// getBooleanContents()
2736  SDValue getConstTrueVal(SelectionDAG &DAG, EVT VT, const SDLoc &DL) const;
2737 
2738  /// Return if \p N is a True value when extended to \p VT.
2739  bool isExtendedTrueVal(const ConstantSDNode *N, EVT VT, bool Signed) const;
2740 
2741  /// Try to simplify a setcc built with the specified operands and cc. If it is
2742  /// unable to simplify it, return a null SDValue.
2743  SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
2744  bool foldBooleans, DAGCombinerInfo &DCI,
2745  const SDLoc &dl) const;
2746 
2747  // For targets which wrap address, unwrap for analysis.
2748  virtual SDValue unwrapAddress(SDValue N) const { return N; }
2749 
2750  /// Returns true (and the GlobalValue and the offset) if the node is a
2751  /// GlobalAddress + offset.
2752  virtual bool
2753  isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
2754 
2755  /// This method will be invoked for all target nodes and for any
2756  /// target-independent nodes that the target has registered with invoke it
2757  /// for.
2758  ///
2759  /// The semantics are as follows:
2760  /// Return Value:
2761  /// SDValue.Val == 0 - No change was made
2762  /// SDValue.Val == N - N was replaced, is dead, and is already handled.
2763  /// otherwise - N should be replaced by the returned Operand.
2764  ///
2765  /// In addition, methods provided by DAGCombinerInfo may be used to perform
2766  /// more complex transformations.
2767  ///
2768  virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
2769 
2770  /// Return true if it is profitable to move a following shift through this
2771  // node, adjusting any immediate operands as necessary to preserve semantics.
2772  // This transformation may not be desirable if it disrupts a particularly
2773  // auspicious target-specific tree (e.g. bitfield extraction in AArch64).
2774  // By default, it returns true.
2775  virtual bool isDesirableToCommuteWithShift(const SDNode *N) const {
2776  return true;
2777  }
2778 
2779  // Return true if it is profitable to combine a BUILD_VECTOR with a stride-pattern
2780  // to a shuffle and a truncate.
2781  // Example of such a combine:
2782  // v4i32 build_vector((extract_elt V, 1),
2783  // (extract_elt V, 3),
2784  // (extract_elt V, 5),
2785  // (extract_elt V, 7))
2786  // -->
2787  // v4i32 truncate (bitcast (shuffle<1,u,3,u,5,u,7,u> V, u) to v4i64)
2789  ArrayRef<int> ShuffleMask, EVT SrcVT, EVT TruncVT) const {
2790  return false;
2791  }
2792 
2793  /// Return true if the target has native support for the specified value type
2794  /// and it is 'desirable' to use the type for the given node type. e.g. On x86
2795  /// i16 is legal, but undesirable since i16 instruction encodings are longer
2796  /// and some i16 instructions are slow.
2797  virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
2798  // By default, assume all legal types are desirable.
2799  return isTypeLegal(VT);
2800  }
2801 
2802  /// Return true if it is profitable for dag combiner to transform a floating
2803  /// point op of specified opcode to a equivalent op of an integer
2804  /// type. e.g. f32 load -> i32 load can be profitable on ARM.
2805  virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
2806  EVT /*VT*/) const {
2807  return false;
2808  }
2809 
2810  /// This method query the target whether it is beneficial for dag combiner to
2811  /// promote the specified node. If true, it should return the desired
2812  /// promotion type by reference.
2813  virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
2814  return false;
2815  }
2816 
2817  /// Return true if the target supports swifterror attribute. It optimizes
2818  /// loads and stores to reading and writing a specific register.
2819  virtual bool supportSwiftError() const {
2820  return false;
2821  }
2822 
2823  /// Return true if the target supports that a subset of CSRs for the given
2824  /// machine function is handled explicitly via copies.
2825  virtual bool supportSplitCSR(MachineFunction *MF) const {
2826  return false;
2827  }
2828 
2829  /// Perform necessary initialization to handle a subset of CSRs explicitly
2830  /// via copies. This function is called at the beginning of instruction
2831  /// selection.
2832  virtual void initializeSplitCSR(MachineBasicBlock *Entry) const {
2833  llvm_unreachable("Not Implemented");
2834  }
2835 
2836  /// Insert explicit copies in entry and exit blocks. We copy a subset of
2837  /// CSRs to virtual registers in the entry block, and copy them back to
2838  /// physical registers in the exit blocks. This function is called at the end
2839  /// of instruction selection.
2840  virtual void insertCopiesSplitCSR(
2841  MachineBasicBlock *Entry,
2842  const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2843  llvm_unreachable("Not Implemented");
2844  }
2845 
2846  //===--------------------------------------------------------------------===//
2847  // Lowering methods - These methods must be implemented by targets so that
2848  // the SelectionDAGBuilder code knows how to lower these.
2849  //
2850 
2851  /// This hook must be implemented to lower the incoming (formal) arguments,
2852  /// described by the Ins array, into the specified DAG. The implementation
2853  /// should fill in the InVals array with legal-type argument values, and
2854  /// return the resulting token chain value.
2856  SDValue /*Chain*/, CallingConv::ID /*CallConv*/, bool /*isVarArg*/,
2857  const SmallVectorImpl<ISD::InputArg> & /*Ins*/, const SDLoc & /*dl*/,
2858  SelectionDAG & /*DAG*/, SmallVectorImpl<SDValue> & /*InVals*/) const {
2859  llvm_unreachable("Not Implemented");
2860  }
2861 
2862  /// This structure contains all information that is necessary for lowering
2863  /// calls. It is passed to TLI::LowerCallTo when the SelectionDAG builder
2864  /// needs to lower a call, and targets will see this struct in their LowerCall
2865  /// implementation.
2868  Type *RetTy = nullptr;
2869  bool RetSExt : 1;
2870  bool RetZExt : 1;
2871  bool IsVarArg : 1;
2872  bool IsInReg : 1;
2873  bool DoesNotReturn : 1;
2875  bool IsConvergent : 1;
2876  bool IsPatchPoint : 1;
2877 
2878  // IsTailCall should be modified by implementations of
2879  // TargetLowering::LowerCall that perform tail call conversions.
2880  bool IsTailCall = false;
2881 
2882  // Is Call lowering done post SelectionDAG type legalization.
2883  bool IsPostTypeLegalization = false;
2884 
2885  unsigned NumFixedArgs = -1;
2888  ArgListTy Args;
2896 
2898  : RetSExt(false), RetZExt(false), IsVarArg(false), IsInReg(false),
2899  DoesNotReturn(false), IsReturnValueUsed(true), IsConvergent(false),
2900  IsPatchPoint(false), DAG(DAG) {}
2901 
2903  DL = dl;
2904  return *this;
2905  }
2906 
2908  Chain = InChain;
2909  return *this;
2910  }
2911 
2912  // setCallee with target/module-specific attributes
2914  SDValue Target, ArgListTy &&ArgsList) {
2915  RetTy = ResultType;
2916  Callee = Target;
2917  CallConv = CC;
2918  NumFixedArgs = ArgsList.size();
2919  Args = std::move(ArgsList);
2920 
2922  &(DAG.getMachineFunction()), CC, Args);
2923  return *this;
2924  }
2925 
2927  SDValue Target, ArgListTy &&ArgsList) {
2928  RetTy = ResultType;
2929  Callee = Target;
2930  CallConv = CC;
2931  NumFixedArgs = ArgsList.size();
2932  Args = std::move(ArgsList);
2933  return *this;
2934  }
2935 
2937  SDValue Target, ArgListTy &&ArgsList,
2938  ImmutableCallSite Call) {
2939  RetTy = ResultType;
2940 
2941  IsInReg = Call.hasRetAttr(Attribute::InReg);
2942  DoesNotReturn =
2943  Call.doesNotReturn() ||
2944  (!Call.isInvoke() &&
2945  isa<UnreachableInst>(Call.getInstruction()->getNextNode()));
2946  IsVarArg = FTy->isVarArg();
2947  IsReturnValueUsed = !Call.getInstruction()->use_empty();
2948  RetSExt = Call.hasRetAttr(Attribute::SExt);
2949  RetZExt = Call.hasRetAttr(Attribute::ZExt);
2950 
2951  Callee = Target;
2952 
2953  CallConv = Call.getCallingConv();
2954  NumFixedArgs = FTy->getNumParams();
2955  Args = std::move(ArgsList);
2956 
2957  CS = Call;
2958 
2959  return *this;
2960  }
2961 
2963  IsInReg = Value;
2964  return *this;
2965  }
2966 
2968  DoesNotReturn = Value;
2969  return *this;
2970  }
2971 
2973  IsVarArg = Value;
2974  return *this;
2975  }
2976 
2978  IsTailCall = Value;
2979  return *this;
2980  }
2981 
2983  IsReturnValueUsed = !Value;
2984  return *this;
2985  }
2986 
2988  IsConvergent = Value;
2989  return *this;
2990  }
2991 
2993  RetSExt = Value;
2994  return *this;
2995  }
2996 
2998  RetZExt = Value;
2999  return *this;
3000  }
3001 
3003  IsPatchPoint = Value;
3004  return *this;
3005  }
3006 
3008  IsPostTypeLegalization = Value;
3009  return *this;
3010  }
3011 
3012  ArgListTy &getArgs() {
3013  return Args;
3014  }
3015  };
3016 
3017  /// This function lowers an abstract call to a function into an actual call.
3018  /// This returns a pair of operands. The first element is the return value
3019  /// for the function (if RetTy is not VoidTy). The second element is the
3020  /// outgoing token chain. It calls LowerCall to do the actual lowering.
3021  std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
3022 
3023  /// This hook must be implemented to lower calls into the specified
3024  /// DAG. The outgoing arguments to the call are described by the Outs array,
3025  /// and the values to be returned by the call are described by the Ins
3026  /// array. The implementation should fill in the InVals array with legal-type
3027  /// return values from the call, and return the resulting token chain value.
3028  virtual SDValue
3030  SmallVectorImpl<SDValue> &/*InVals*/) const {
3031  llvm_unreachable("Not Implemented");
3032  }
3033 
3034  /// Target-specific cleanup for formal ByVal parameters.
3035  virtual void HandleByVal(CCState *, unsigned &, unsigned) const {}
3036 
3037  /// This hook should be implemented to check whether the return values
3038  /// described by the Outs array can fit into the return registers. If false
3039  /// is returned, an sret-demotion is performed.
3040  virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
3041  MachineFunction &/*MF*/, bool /*isVarArg*/,
3042  const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
3043  LLVMContext &/*Context*/) const
3044  {
3045  // Return true by default to get preexisting behavior.
3046  return true;
3047  }
3048 
3049  /// This hook must be implemented to lower outgoing return values, described
3050  /// by the Outs array, into the specified DAG. The implementation should
3051  /// return the resulting token chain value.
3052  virtual SDValue LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
3053  bool /*isVarArg*/,
3054  const SmallVectorImpl<ISD::OutputArg> & /*Outs*/,
3055  const SmallVectorImpl<SDValue> & /*OutVals*/,
3056  const SDLoc & /*dl*/,
3057  SelectionDAG & /*DAG*/) const {
3058  llvm_unreachable("Not Implemented");
3059  }
3060 
3061  /// Return true if result of the specified node is used by a return node
3062  /// only. It also compute and return the input chain for the tail call.
3063  ///
3064  /// This is used to determine whether it is possible to codegen a libcall as
3065  /// tail call at legalization time.
3066  virtual bool isUsedByReturnOnly(SDNode *, SDValue &/*Chain*/) const {
3067  return false;
3068  }
3069 
3070  /// Return true if the target may be able emit the call instruction as a tail
3071  /// call. This is used by optimization passes to determine if it's profitable
3072  /// to duplicate return instructions to enable tailcall optimization.
3073  virtual bool mayBeEmittedAsTailCall(const CallInst *) const {
3074  return false;
3075  }
3076 
3077  /// Return the builtin name for the __builtin___clear_cache intrinsic
3078  /// Default is to invoke the clear cache library call
3079  virtual const char * getClearCacheBuiltinName() const {
3080  return "__clear_cache";
3081  }
3082 
3083  /// Return the register ID of the name passed in. Used by named register
3084  /// global variables extension. There is no target-independent behaviour
3085  /// so the default action is to bail.
3086  virtual unsigned getRegisterByName(const char* RegName, EVT VT,
3087  SelectionDAG &DAG) const {
3088  report_fatal_error("Named registers not implemented for this target");
3089  }
3090 
3091  /// Return the type that should be used to zero or sign extend a
3092  /// zeroext/signext integer return value. FIXME: Some C calling conventions
3093  /// require the return type to be promoted, but this is not true all the time,
3094  /// e.g. i1/i8/i16 on x86/x86_64. It is also not necessary for non-C calling
3095  /// conventions. The frontend should handle this and include all of the
3096  /// necessary information.
3098  ISD::NodeType /*ExtendKind*/) const {
3099  EVT MinVT = getRegisterType(Context, MVT::i32);
3100  return VT.bitsLT(MinVT) ? MinVT : VT;
3101  }
3102 
3103  /// For some targets, an LLVM struct type must be broken down into multiple
3104  /// simple types, but the calling convention specifies that the entire struct
3105  /// must be passed in a block of consecutive registers.
3106  virtual bool
3108  bool isVarArg) const {
3109  return false;
3110  }
3111 
3112  /// Returns a 0 terminated array of registers that can be safely used as
3113  /// scratch registers.
3114  virtual const MCPhysReg *getScratchRegisters(CallingConv::ID CC) const {
3115  return nullptr;
3116  }
3117 
3118  /// This callback is used to prepare for a volatile or atomic load.
3119  /// It takes a chain node as input and returns the chain for the load itself.
3120  ///
3121  /// Having a callback like this is necessary for targets like SystemZ,
3122  /// which allows a CPU to reuse the result of a previous load indefinitely,
3123  /// even if a cache-coherent store is performed by another CPU. The default
3124  /// implementation does nothing.
3126  SelectionDAG &DAG) const {
3127  return Chain;
3128  }
3129 
3130  /// This callback is used to inspect load/store instructions and add
3131  /// target-specific MachineMemOperand flags to them. The default
3132  /// implementation does nothing.
3135  }
3136 
3137  /// This callback is invoked by the type legalizer to legalize nodes with an
3138  /// illegal operand type but legal result types. It replaces the
3139  /// LowerOperation callback in the type Legalizer. The reason we can not do
3140  /// away with LowerOperation entirely is that LegalizeDAG isn't yet ready to
3141  /// use this callback.
3142  ///
3143  /// TODO: Consider merging with ReplaceNodeResults.
3144  ///
3145  /// The target places new result values for the node in Results (their number
3146  /// and types must exactly match those of the original return values of
3147  /// the node), or leaves Results empty, which indicates that the node is not
3148  /// to be custom lowered after all.
3149  /// The default implementation calls LowerOperation.
3150  virtual void LowerOperationWrapper(SDNode *N,
3152  SelectionDAG &DAG) const;
3153 
3154  /// This callback is invoked for operations that are unsupported by the
3155  /// target, which are registered to use 'custom' lowering, and whose defined
3156  /// values are all legal. If the target has no operations that require custom
3157  /// lowering, it need not implement this. The default implementation of this
3158  /// aborts.
3159  virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
3160 
3161  /// This callback is invoked when a node result type is illegal for the
3162  /// target, and the operation was registered to use 'custom' lowering for that
3163  /// result type. The target places new result values for the node in Results
3164  /// (their number and types must exactly match those of the original return
3165  /// values of the node), or leaves Results empty, which indicates that the
3166  /// node is not to be custom lowered after all.
3167  ///
3168  /// If the target has no operations that require custom lowering, it need not
3169  /// implement this. The default implementation aborts.
3170  virtual void ReplaceNodeResults(SDNode * /*N*/,
3171  SmallVectorImpl<SDValue> &/*Results*/,
3172  SelectionDAG &/*DAG*/) const {
3173  llvm_unreachable("ReplaceNodeResults not implemented for this target!");
3174  }
3175 
3176  /// This method returns the name of a target specific DAG node.
3177  virtual const char *getTargetNodeName(unsigned Opcode) const;
3178 
3179  /// This method returns a target specific FastISel object, or null if the
3180  /// target does not support "fast" ISel.
3182  const TargetLibraryInfo *) const {
3183  return nullptr;
3184  }
3185 
3186  bool verifyReturnAddressArgumentIsConstant(SDValue Op,
3187  SelectionDAG &DAG) const;
3188 
3189  //===--------------------------------------------------------------------===//
3190  // Inline Asm Support hooks
3191  //
3192 
3193  /// This hook allows the target to expand an inline asm call to be explicit
3194  /// llvm code if it wants to. This is useful for turning simple inline asms
3195  /// into LLVM intrinsics, which gives the compiler more information about the
3196  /// behavior of the code.
3197  virtual bool ExpandInlineAsm(CallInst *) const {
3198  return false;
3199  }
3200 
3202  C_Register, // Constraint represents specific register(s).
3203  C_RegisterClass, // Constraint represents any of register(s) in class.
3204  C_Memory, // Memory constraint.
3205  C_Other, // Something else.
3206  C_Unknown // Unsupported constraint.
3207  };
3208 
3210  // Generic weights.
3211  CW_Invalid = -1, // No match.
3212  CW_Okay = 0, // Acceptable.
3213  CW_Good = 1, // Good weight.
3214  CW_Better = 2, // Better weight.
3215  CW_Best = 3, // Best weight.
3216 
3217  // Well-known weights.
3218  CW_SpecificReg = CW_Okay, // Specific register operands.
3219  CW_Register = CW_Good, // Register operands.
3220  CW_Memory = CW_Better, // Memory operands.
3221  CW_Constant = CW_Best, // Constant operand.
3222  CW_Default = CW_Okay // Default or don't know type.
3223  };
3224 
3225  /// This contains information for each constraint that we are lowering.
3227  /// This contains the actual string for the code, like "m". TargetLowering
3228  /// picks the 'best' code from ConstraintInfo::Codes that most closely
3229  /// matches the operand.
3230  std::string ConstraintCode;
3231 
3232  /// Information about the constraint code, e.g. Register, RegisterClass,
3233  /// Memory, Other, Unknown.
3235 
3236  /// If this is the result output operand or a clobber, this is null,
3237  /// otherwise it is the incoming operand to the CallInst. This gets
3238  /// modified as the asm is processed.
3239  Value *CallOperandVal = nullptr;
3240 
3241  /// The ValueType for the operand value.
3242  MVT ConstraintVT = MVT::Other;
3243 
3244  /// Copy constructor for copying from a ConstraintInfo.
3246  : InlineAsm::ConstraintInfo(std::move(Info)) {}
3247 
3248  /// Return true of this is an input operand that is a matching constraint
3249  /// like "4".
3250  bool isMatchingInputConstraint() const;
3251 
3252  /// If this is an input matching constraint, this method returns the output
3253  /// operand it matches.
3254  unsigned getMatchedOperand() const;
3255  };
3256 
3257  using AsmOperandInfoVector = std::vector<AsmOperandInfo>;
3258 
3259  /// Split up the constraint string from the inline assembly value into the
3260  /// specific constraints and their prefixes, and also tie in the associated
3261  /// operand values. If this returns an empty vector, and if the constraint
3262  /// string itself isn't empty, there was an error parsing.
3263  virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL,
3264  const TargetRegisterInfo *TRI,
3265  ImmutableCallSite CS) const;
3266 
3267  /// Examine constraint type and operand type and determine a weight value.
3268  /// The operand object must already have been set up with the operand type.
3269  virtual ConstraintWeight getMultipleConstraintMatchWeight(
3270  AsmOperandInfo &info, int maIndex) const;
3271 
3272  /// Examine constraint string and operand type and determine a weight value.
3273  /// The operand object must already have been set up with the operand type.
3274  virtual ConstraintWeight getSingleConstraintMatchWeight(
3275  AsmOperandInfo &info, const char *constraint) const;
3276 
3277  /// Determines the constraint code and constraint type to use for the specific
3278  /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
3279  /// If the actual operand being passed in is available, it can be passed in as
3280  /// Op, otherwise an empty SDValue can be passed.
3281  virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
3282  SDValue Op,
3283  SelectionDAG *DAG = nullptr) const;
3284 
3285  /// Given a constraint, return the type of constraint it is for this target.
3286  virtual ConstraintType getConstraintType(StringRef Constraint) const;
3287 
3288  /// Given a physical register constraint (e.g. {edx}), return the register
3289  /// number and the register class for the register.
3290  ///
3291  /// Given a register class constraint, like 'r', if this corresponds directly
3292  /// to an LLVM register class, return a register of 0 and the register class
3293  /// pointer.
3294  ///
3295  /// This should only be used for C_Register constraints. On error, this
3296  /// returns a register number of 0 and a null register class pointer.
3297  virtual std::pair<unsigned, const TargetRegisterClass *>
3298  getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
3299  StringRef Constraint, MVT VT) const;
3300 
3301  virtual unsigned getInlineAsmMemConstraint(StringRef ConstraintCode) const {
3302  if (ConstraintCode == "i")
3303  return InlineAsm::Constraint_i;
3304  else if (ConstraintCode == "m")
3305  return InlineAsm::Constraint_m;
3307  }
3308 
3309  /// Try to replace an X constraint, which matches anything, with another that
3310  /// has more specific requirements based on the type of the corresponding
3311  /// operand. This returns null if there is no replacement to make.
3312  virtual const char *LowerXConstraint(EVT ConstraintVT) const;
3313 
3314  /// Lower the specified operand into the Ops vector. If it is invalid, don't
3315  /// add anything to Ops.
3316  virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
3317  std::vector<SDValue> &Ops,
3318  SelectionDAG &DAG) const;
3319 
3320  //===--------------------------------------------------------------------===//
3321  // Div utility functions
3322  //
3323  SDValue BuildSDIV(SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
3324  bool IsAfterLegalization,
3325  std::vector<SDNode *> *Created) const;
3326  SDValue BuildUDIV(SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
3327  bool IsAfterLegalization,
3328  std::vector<SDNode *> *Created) const;
3329 
3330  /// Targets may override this function to provide custom SDIV lowering for
3331  /// power-of-2 denominators. If the target returns an empty SDValue, LLVM
3332  /// assumes SDIV is expensive and replaces it with a series of other integer
3333  /// operations.
3334  virtual SDValue BuildSDIVPow2(SDNode *N, const APInt &Divisor,
3335  SelectionDAG &DAG,
3336  std::vector<SDNode *> *Created) const;
3337 
3338  /// Indicate whether this target prefers to combine FDIVs with the same
3339  /// divisor. If the transform should never be done, return zero. If the
3340  /// transform should be done, return the minimum number of divisor uses
3341  /// that must exist.
3342  virtual unsigned combineRepeatedFPDivisors() const {
3343  return 0;
3344  }
3345 
3346  /// Hooks for building estimates in place of slower divisions and square
3347  /// roots.
3348 
3349  /// Return either a square root or its reciprocal estimate value for the input
3350  /// operand.
3351  /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
3352  /// 'Enabled' as set by a potential default override attribute.
3353  /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
3354  /// refinement iterations required to generate a sufficient (though not
3355  /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
3356  /// The boolean UseOneConstNR output is used to select a Newton-Raphson
3357  /// algorithm implementation that uses either one or two constants.
3358  /// The boolean Reciprocal is used to select whether the estimate is for the
3359  /// square root of the input operand or the reciprocal of its square root.
3360  /// A target may choose to implement its own refinement within this function.
3361  /// If that's true, then return '0' as the number of RefinementSteps to avoid
3362  /// any further refinement of the estimate.
3363  /// An empty SDValue return means no estimate sequence can be created.
3365  int Enabled, int &RefinementSteps,
3366  bool &UseOneConstNR, bool Reciprocal) const {
3367  return SDValue();
3368  }
3369 
3370  /// Return a reciprocal estimate value for the input operand.
3371  /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
3372  /// 'Enabled' as set by a potential default override attribute.
3373  /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
3374  /// refinement iterations required to generate a sufficient (though not
3375  /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
3376  /// A target may choose to implement its own refinement within this function.
3377  /// If that's true, then return '0' as the number of RefinementSteps to avoid
3378  /// any further refinement of the estimate.
3379  /// An empty SDValue return means no estimate sequence can be created.
3381  int Enabled, int &RefinementSteps) const {
3382  return SDValue();
3383  }
3384 
3385  //===--------------------------------------------------------------------===//
3386  // Legalization utility functions
3387  //
3388 
3389  /// Expand a MUL or [US]MUL_LOHI of n-bit values into two or four nodes,
3390  /// respectively, each computing an n/2-bit part of the result.
3391  /// \param Result A vector that will be filled with the parts of the result
3392  /// in little-endian order.
3393  /// \param LL Low bits of the LHS of the MUL. You can use this parameter
3394  /// if you want to control how low bits are extracted from the LHS.
3395  /// \param LH High bits of the LHS of the MUL. See LL for meaning.
3396  /// \param RL Low bits of the RHS of the MUL. See LL for meaning
3397  /// \param RH High bits of the RHS of the MUL. See LL for meaning.
3398  /// \returns true if the node has been expanded, false if it has not
3399  bool expandMUL_LOHI(unsigned Opcode, EVT VT, SDLoc dl, SDValue LHS,
3400  SDValue RHS, SmallVectorImpl<SDValue> &Result, EVT HiLoVT,
3402  SDValue LL = SDValue(), SDValue LH = SDValue(),
3403  SDValue RL = SDValue(), SDValue RH = SDValue()) const;
3404 
3405  /// Expand a MUL into two nodes. One that computes the high bits of
3406  /// the result and one that computes the low bits.
3407  /// \param HiLoVT The value type to use for the Lo and Hi nodes.
3408  /// \param LL Low bits of the LHS of the MUL. You can use this parameter
3409  /// if you want to control how low bits are extracted from the LHS.
3410  /// \param LH High bits of the LHS of the MUL. See LL for meaning.
3411  /// \param RL Low bits of the RHS of the MUL. See LL for meaning
3412  /// \param RH High bits of the RHS of the MUL. See LL for meaning.
3413  /// \returns true if the node has been expanded. false if it has not
3414  bool expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
3415  SelectionDAG &DAG, MulExpansionKind Kind,
3416  SDValue LL = SDValue(), SDValue LH = SDValue(),
3417  SDValue RL = SDValue(), SDValue RH = SDValue()) const;
3418 
3419  /// Expand float(f32) to SINT(i64) conversion
3420  /// \param N Node to expand
3421  /// \param Result output after conversion
3422  /// \returns True, if the expansion was successful, false otherwise
3423  bool expandFP_TO_SINT(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
3424 
3425  /// Turn load of vector type into a load of the individual elements.
3426  /// \param LD load to expand
3427  /// \returns MERGE_VALUEs of the scalar loads with their chains.
3428  SDValue scalarizeVectorLoad(LoadSDNode *LD, SelectionDAG &DAG) const;
3429 
3430  // Turn a store of a vector type into stores of the individual elements.
3431  /// \param ST Store with a vector value type
3432  /// \returns MERGE_VALUs of the individual store chains.
3433  SDValue scalarizeVectorStore(StoreSDNode *ST, SelectionDAG &DAG) const;
3434 
3435  /// Expands an unaligned load to 2 half-size loads for an integer, and
3436  /// possibly more for vectors.
3437  std::pair<SDValue, SDValue> expandUnalignedLoad(LoadSDNode *LD,
3438  SelectionDAG &DAG) const;
3439 
3440  /// Expands an unaligned store to 2 half-size stores for integer values, and
3441  /// possibly more for vectors.
3442  SDValue expandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG) const;
3443 
3444  /// Increments memory address \p Addr according to the type of the value
3445  /// \p DataVT that should be stored. If the data is stored in compressed
3446  /// form, the memory address should be incremented according to the number of
3447  /// the stored elements. This number is equal to the number of '1's bits
3448  /// in the \p Mask.
3449  /// \p DataVT is a vector type. \p Mask is a vector value.
3450  /// \p DataVT and \p Mask have the same number of vector elements.
3451  SDValue IncrementMemoryAddress(SDValue Addr, SDValue Mask, const SDLoc &DL,
3452  EVT DataVT, SelectionDAG &DAG,
3453  bool IsCompressedMemory) const;
3454 
3455  /// Get a pointer to vector element \p Idx located in memory for a vector of
3456  /// type \p VecVT starting at a base address of \p VecPtr. If \p Idx is out of
3457  /// bounds the returned pointer is unspecified, but will be within the vector
3458  /// bounds.
3459  SDValue getVectorElementPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT,
3460  SDValue Idx) const;
3461 
3462  //===--------------------------------------------------------------------===//
3463  // Instruction Emitting Hooks
3464  //
3465 
3466  /// This method should be implemented by targets that mark instructions with
3467  /// the 'usesCustomInserter' flag. These instructions are special in various
3468  /// ways, which require special support to insert. The specified MachineInstr
3469  /// is created but not inserted into any basic blocks, and this method is
3470  /// called to expand it into a sequence of instructions, potentially also
3471  /// creating new basic blocks and control flow.
3472  /// As long as the returned basic block is different (i.e., we created a new
3473  /// one), the custom inserter is free to modify the rest of \p MBB.
3474  virtual MachineBasicBlock *
3475  EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const;
3476 
3477  /// This method should be implemented by targets that mark instructions with
3478  /// the 'hasPostISelHook' flag. These instructions must be adjusted after
3479  /// instruction selection by target hooks. e.g. To fill in optional defs for
3480  /// ARM 's' setting instructions.
3481  virtual void AdjustInstrPostInstrSelection(MachineInstr &MI,
3482  SDNode *Node) const;
3483 
3484  /// If this function returns true, SelectionDAGBuilder emits a
3485  /// LOAD_STACK_GUARD node when it is lowering Intrinsic::stackprotector.
3486  virtual bool useLoadStackGuardNode() const {
3487  return false;
3488  }
3489 
3490  /// Lower TLS global address SDNode for target independent emulated TLS model.
3491  virtual SDValue LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
3492  SelectionDAG &DAG) const;
3493 
3494  // seteq(x, 0) -> truncate(srl(ctlz(zext(x)), log2(#bits)))
3495  // If we're comparing for equality to zero and isCtlzFast is true, expose the
3496  // fact that this can be implemented as a ctlz/srl pair, so that the dag
3497  // combiner can fold the new nodes.
3498  SDValue lowerCmpEqZeroToCtlzSrl(SDValue Op, SelectionDAG &DAG) const;
3499 
3500 private:
3501  SDValue simplifySetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
3502  ISD::CondCode Cond, DAGCombinerInfo &DCI,
3503  const SDLoc &DL) const;
3504 };
3505 
3506 /// Given an LLVM IR type and return type attributes, compute the return value
3507 /// EVTs and flags, and optionally also the offsets, if the return value is
3508 /// being lowered to memory.
3511  const TargetLowering &TLI, const DataLayout &DL);
3512 
3513 } // end namespace llvm
3514 
3515 #endif // LLVM_CODEGEN_TARGETLOWERING_H
LegalizeAction getLoadExtAction(unsigned ExtType, EVT ValVT, EVT MemVT) const
Return how this load with extension should be treated: either it is legal, needs to be promoted to a ...
Fast - This calling convention attempts to make calls as fast as possible (e.g.
Definition: CallingConv.h:43
virtual bool isJumpTableRelative() const
virtual MVT getRegisterTypeForCallingConv(MVT VT) const
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
static MVT getIntegerVT(unsigned BitWidth)
BUILTIN_OP_END - This must be the last enum value in this list.
Definition: ISDOpcodes.h:834
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:109
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:244
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
FMINNUM/FMAXNUM - Perform floating-point minimum or maximum on two values.
Definition: ISDOpcodes.h:569
virtual MVT getVectorIdxTy(const DataLayout &DL) const
Returns the type to be used for the index operand of: ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT...
EVT getValueType() const
Return the ValueType of the referenced return value.
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg If BaseGV is null...
bool isInteger() const
Return true if this is an integer or a vector integer type.
virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context, EVT VT) const
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified load with extension does not work with the specified type and indicate wh...
virtual bool canMergeStoresTo(unsigned AS, EVT MemVT, const SelectionDAG &DAG) const
Returns if it&#39;s reasonable to merge stores to MemVT size.
virtual bool isCheapAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const
Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g.
bool usesUnderscoreLongJmp() const
Determine if we should use _longjmp or longjmp to implement llvm.longjmp.
LLVMContext & Context
virtual bool shouldInsertFencesForAtomic(const Instruction *I) const
Whether AtomicExpandPass should automatically insert fences and reduce ordering for this atomic...
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
Definition: Path.cpp:235
CallingConv::ID getCallingConv() const
Get the calling convention of the call.
Definition: CallSite.h:312
Atomic ordering constants.
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:289
virtual bool isFPImmLegal(const APFloat &, EVT) const
Returns true if the target can instruction select the specified FP immediate natively.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:115
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
bool isOperationCustom(unsigned Op, EVT VT) const
Return true if the operation uses custom lowering, regardless of whether the type is legal or not...
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
virtual const TargetRegisterClass * getRepRegClassFor(MVT VT) const
Return the &#39;representative&#39; register class for the specified value type.
virtual bool shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const
Returns true if the given atomic cmpxchg should be expanded by the IR-level AtomicExpand pass into a ...
virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const
Return if the target supports combining a chain like:
an instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
Definition: Instructions.h:514
CallLoweringInfo & setIsPostTypeLegalization(bool Value=true)
Sched::Preference getSchedulingPreference() const
Return target scheduling preference.
void setJumpBufAlignment(unsigned Align)
Set the target&#39;s required jmp_buf buffer alignment (in bytes); default is 0.
virtual unsigned getVectorTypeBreakdownForCallingConv(LLVMContext &Context, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const
Certain targets such as MIPS require that some types such as vectors are always broken down into scal...
bool usesUnderscoreSetJmp() const
Determine if we should use _setjmp or setjmp to implement llvm.setjmp.
virtual unsigned getRegisterByName(const char *RegName, EVT VT, SelectionDAG &DAG) const
Return the register ID of the name passed in.
Carry-setting nodes for multiple precision addition and subtraction.
Definition: ISDOpcodes.h:222
virtual bool enableAggressiveFMAFusion(EVT VT) const
Return true if target always beneficiates from combining into FMA for a given value type...
virtual bool getPreIndexedAddressParts(SDNode *, SDValue &, SDValue &, ISD::MemIndexedMode &, SelectionDAG &) const
Returns true by value, base pointer and offset pointer and addressing mode by reference if the node&#39;s...
virtual SDValue getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, int Enabled, int &RefinementSteps, bool &UseOneConstNR, bool Reciprocal) const
Hooks for building estimates in place of slower divisions and square roots.
This class represents a function call, abstracting a target machine&#39;s calling convention.
virtual bool isFNegFree(EVT VT) const
Return true if an fneg operation is free to the point where it is never worthwhile to replace it with...
void setHasFloatingPointExceptions(bool FPExceptions=true)
Tells the code generator that this target supports floating point exceptions and cares about preservi...
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition: ValueTypes.h:253
virtual unsigned combineRepeatedFPDivisors() const
Indicate whether this target prefers to combine FDIVs with the same divisor.
Libcall
RTLIB::Libcall enum - This enum defines all of the runtime library calls the backend can emit...
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition: ISDOpcodes.h:250
static ISD::NodeType getExtendForContent(BooleanContent Content)
virtual bool isSelectSupported(SelectSupportKind) const
Function Alias Analysis Results
bool isSuitableForBitTests(unsigned NumDests, unsigned NumCmps, const APInt &Low, const APInt &High, const DataLayout &DL) const
Return true if lowering to a bit test is suitable for a set of case clusters which contains NumDests ...
This instruction constructs a fixed permutation of two input vectors.
virtual bool isCommutativeBinOp(unsigned Opcode) const
Returns true if the opcode is a commutative binary operation.
virtual void markLibCallAttributes(MachineFunction *MF, unsigned CC, ArgListTy &Args) const
unsigned getMaxStoresPerMemset(bool OptSize) const
Get maximum # of store operations permitted for llvm.memset.
virtual void HandleByVal(CCState *, unsigned &, unsigned) const
Target-specific cleanup for formal ByVal parameters.
CallLoweringInfo & setNoReturn(bool Value=true)
virtual bool isSafeMemOpType(MVT) const
Returns true if it&#39;s safe to use load / store of the specified type to expand memcpy / memset inline...
void setBooleanVectorContents(BooleanContent Ty)
Specify how the target extends the result of a vector boolean value from a vector of i1 to a wider ty...
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
Definition: DataLayout.h:344
LegalizeAction getIndexedStoreAction(unsigned IdxMode, MVT VT) const
Return how the indexed store should be treated: either it is legal, needs to be promoted to a larger ...
bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const
Return true if the specified store with truncation is legal on this target.
virtual const TargetRegisterClass * getRegClassFor(MVT VT) const
Return the register class that should be used for the specified value type.
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition: ValueTypes.h:141
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
bool hasMultipleConditionRegisters() const
Return true if multiple condition registers are available.
An instruction for reading from memory.
Definition: Instructions.h:164
virtual AtomicExpansionKind shouldExpandAtomicLoadInIR(LoadInst *LI) const
Returns how the given (atomic) load should be expanded by the IR-level AtomicExpand pass...
virtual bool mayBeEmittedAsTailCall(const CallInst *) const
Return true if the target may be able emit the call instruction as a tail call.
virtual bool isTypeDesirableForOp(unsigned, EVT VT) const
Return true if the target has native support for the specified value type and it is &#39;desirable&#39; to us...
[US]{MIN/MAX} - Binary minimum or maximum or signed or unsigned integers.
Definition: ISDOpcodes.h:359
bool hasExtractBitsInsn() const
Return true if the target has BitExtract instructions.
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
Definition: Instructions.h:677
BooleanContent getBooleanContents(bool isVec, bool isFloat) const
For targets without i1 registers, this gives the nature of the high-bits of boolean values held in ty...
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:227
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
AtomicExpansionKind
Enum that specifies what an atomic load/AtomicRMWInst is expanded to, if at all.
virtual bool storeOfVectorConstantIsCheap(EVT MemVT, unsigned NumElem, unsigned AddrSpace) const
Return true if it is expected to be cheaper to do a store of a non-zero vector constant with the give...
bool isOperationLegalOrCustom(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
unsigned getJumpBufAlignment() const
Returns the target&#39;s jmp_buf alignment in bytes (if never set, the default is 0)
std::pair< LegalizeTypeAction, EVT > LegalizeKind
LegalizeKind holds the legalization kind that needs to happen to EVT in order to type-legalize it...
CallLoweringInfo & setDiscardResult(bool Value=true)
virtual StringRef getStackProbeSymbolName(MachineFunction &MF) const
Returns the name of the symbol used to emit stack probes or the empty string if not applicable...
uint64_t High
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition: ISDOpcodes.h:39
bool isValid() const
Return true if this is a valid simple valuetype.
bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const
Return true if the specified condition code is legal on this target.
CallLoweringInfo & setCallee(Type *ResultType, FunctionType *FTy, SDValue Target, ArgListTy &&ArgsList, ImmutableCallSite Call)
void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified truncating store does not work with the specified type and indicate what ...
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:130
virtual bool isFPExtFree(EVT DestVT, EVT SrcVT) const
Return true if an fpext operation is free (for instance, because single-precision floating-point numb...
virtual bool isStoreBitCastBeneficial(EVT StoreVT, EVT BitcastVT) const
Return true if the following transform is beneficial: (store (y (conv x)), y*)) -> (store x...
virtual bool isCtlzFast() const
Return true if ctlz instruction is fast.
A convenience struct that encapsulates a DAG, and two SDValues for returning information from TargetL...
MVT getRegisterType(MVT VT) const
Return the type of registers that this ValueType will eventually require.
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition: ValueTypes.h:136
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
unsigned getAllocaAddrSpace() const
Definition: DataLayout.h:253
void * PointerTy
Definition: GenericValue.h:22
bool doesNotReturn() const
Determine if the call cannot return.
Definition: CallSite.h:497
Definition: BitVector.h:920
void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits)
Set the maximum atomic operation size supported by the backend.
Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
Definition: ValueTypes.cpp:205
CallLoweringInfo & setVarArg(bool Value=true)
CallLoweringInfo & setChain(SDValue InChain)
virtual uint8_t getRepRegClassCostFor(MVT VT) const
Return the cost of the &#39;representative&#39; register class for the specified value type.
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:36
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:668
virtual bool useLoadStackGuardNode() const
If this function returns true, SelectionDAGBuilder emits a LOAD_STACK_GUARD node when it is lowering ...
void setCondCodeAction(ISD::CondCode CC, MVT VT, LegalizeAction Action)
Indicate that the specified condition code is or isn&#39;t supported on the target and indicate what to d...
This file contains the simple types necessary to represent the attributes associated with functions a...
SimpleValueType SimpleTy
InstrTy * getInstruction() const
Definition: CallSite.h:92
void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth)
Tells the code generator which bitwidths to bypass.
virtual bool isVectorShiftByScalarCheap(Type *Ty) const
Return true if it&#39;s significantly cheaper to shift a vector by a uniform scalar than by an amount whi...
bool isLoadExtLegalOrCustom(unsigned ExtType, EVT ValVT, EVT MemVT) const
Return true if the specified load with extension is legal or custom on this target.
bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const
When splitting a value of the specified type into parts, does the Lo or Hi part come first...
void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action)
Indicate that the specified operation does not work with the specified type and indicate what to do a...
virtual bool convertSetCCLogicToBitwiseLogic(EVT VT) const
Use bitwise logic to make pairs of compares more efficient.
virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const
Return true if it is cheaper to split the store of a merged int val from a pair of smaller values int...
uint64_t getNumElements() const
Definition: DerivedTypes.h:359
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
virtual bool aggressivelyPreferBuildVectorSources(EVT VecVT) const
This file implements a class to represent arbitrary precision integral constant values and operations...
virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const
Return true if it&#39;s free to truncate a value of type FromTy to type ToTy.
SmallVector< ISD::InputArg, 32 > Ins
AtomicOrdering
Atomic ordering for LLVM&#39;s memory model.
virtual bool ShouldShrinkFPConstant(EVT) const
If true, then instruction selection should seek to shrink the FP constant of the specified type to a ...
virtual SDValue prepareVolatileOrAtomicLoad(SDValue Chain, const SDLoc &DL, SelectionDAG &DAG) const
This callback is used to prepare for a volatile or atomic load.
Context object for machine code objects.
Definition: MCContext.h:59
virtual void ReplaceNodeResults(SDNode *, SmallVectorImpl< SDValue > &, SelectionDAG &) const
This callback is invoked when a node result type is illegal for the target, and the operation was reg...
virtual unsigned getABIAlignmentForCallingConv(Type *ArgTy, DataLayout DL) const
Certain targets have context senstive alignment requirements, where one type has the alignment requir...
virtual bool isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT) const
Return true if the following transform is beneficial: fold (conv (load x)) -> (load (conv*)x) On arch...
This is a fast-path instruction selection class that generates poor code and doesn&#39;t support illegal ...
Definition: FastISel.h:67
Class to represent function types.
Definition: DerivedTypes.h:103
unsigned getSizeInBits() const
Return the size of the specified value type in bits.
Definition: ValueTypes.h:292
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
MachineFunction & getMachineFunction() const
Definition: SelectionDAG.h:385
C - The default llvm calling convention, compatible with C.
Definition: CallingConv.h:35
virtual bool supportSwiftError() const
Return true if the target supports swifterror attribute.
virtual TargetLoweringBase::LegalizeTypeAction getPreferredVectorAction(EVT VT) const
Return the preferred vector type legalization action.
CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const
Get the CallingConv that should be used for the specified libcall.
This contains information for each constraint that we are lowering.
Simple integer binary arithmetic operators.
Definition: ISDOpcodes.h:200
bool isVarArg() const
Definition: DerivedTypes.h:123
SmallVector< ISD::OutputArg, 32 > Outs
virtual EVT getOptimalMemOpType(uint64_t, unsigned, unsigned, bool, bool, bool, MachineFunction &) const
Returns the target specific optimal type for load and store operations as a result of memset...
virtual bool isCheapToSpeculateCtlz() const
Return true if it is cheap to speculate a call to intrinsic ctlz.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:125
CallLoweringInfo & setZExtResult(bool Value=true)
BooleanContent getBooleanContents(EVT Type) const
An instruction for storing to memory.
Definition: Instructions.h:306
unsigned getPrefFunctionAlignment() const
Return the preferred function alignment.
MVT getRegisterType(LLVMContext &Context, EVT VT) const
Return the type of registers that this ValueType will eventually require.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out...
Definition: ISDOpcodes.h:916
virtual const MCExpr * LowerCustomJumpTableEntry(const MachineJumpTableInfo *, const MachineBasicBlock *, unsigned, MCContext &) const
virtual bool isCheapToSpeculateCttz() const
Return true if it is cheap to speculate a call to intrinsic cttz.
virtual bool lowerInterleavedStore(StoreInst *SI, ShuffleVectorInst *SVI, unsigned Factor) const
Lower an interleaved store to target specific intrinsics.
virtual unsigned getInlineAsmMemConstraint(StringRef ConstraintCode) const
void setMinCmpXchgSizeInBits(unsigned SizeInBits)
Value * getOperand(unsigned i) const
Definition: User.h:154
Class to represent pointers.
Definition: DerivedTypes.h:467
This class is used to represent ISD::STORE nodes.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
bool isJumpExpensive() const
Return true if Flow Control is an expensive operation that should be avoided.
virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx, unsigned &Cost) const
Return true if the target can combine store(extractelement VectorTy, Idx).
virtual Value * emitStoreConditional(IRBuilder<> &Builder, Value *Val, Value *Addr, AtomicOrdering Ord) const
Perform a store-conditional operation to Addr.
EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
std::vector< AsmOperandInfo > AsmOperandInfoVector
MVT getSimpleValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the MVT corresponding to this LLVM type. See getValueType.
virtual bool getAddrModeArguments(IntrinsicInst *, SmallVectorImpl< Value *> &, Type *&) const
CodeGenPrepare sinks address calculations into the same BB as Load/Store instructions reading the add...
unsigned const MachineRegisterInfo * MRI
MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
virtual unsigned getExceptionPointerRegister(const Constant *PersonalityFn) const
If a physical register, this returns the register that receives the exception address on entry to an ...
Machine Value Type.
DAGCombinerInfo(SelectionDAG &dag, CombineLevel level, bool cl, void *dc)
CallLoweringInfo & setIsPatchPoint(bool Value=true)
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:69
void setJumpBufSize(unsigned Size)
Set the target&#39;s required jmp_buf buffer size (in bytes); default is 200.
void addRegisterClass(MVT VT, const TargetRegisterClass *RC)
Add the specified register class as an available regclass for the specified value type...
Simple binary floating point operators.
Definition: ISDOpcodes.h:259
void setTargetDAGCombine(ISD::NodeType NT)
Targets should invoke this method for each target independent node that they want to provide a custom...
virtual bool isTruncateFree(EVT FromVT, EVT ToVT) const
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition: ValueTypes.h:273
virtual ISD::NodeType getExtendForAtomicOps() const
Returns how the platform&#39;s atomic operations are extended (ZERO_EXTEND, SIGN_EXTEND, or ANY_EXTEND).
This is an important base class in LLVM.
Definition: Constant.h:42
virtual bool shouldConvertConstantLoadToIntImm(const APInt &Imm, Type *Ty) const
Return true if it is beneficial to convert a load of a constant to just the constant itself...
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
Definition: ISDOpcodes.h:891
Carry-using nodes for multiple precision addition and subtraction.
Definition: ISDOpcodes.h:231
bool isSlowDivBypassed() const
Returns true if target has indicated at least one type should be bypassed.
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Definition: DerivedTypes.h:139
virtual Value * emitLoadLinked(IRBuilder<> &Builder, Value *Addr, AtomicOrdering Ord) const
Perform a load-linked operation on Addr, returning a "Value *" with the corresponding pointee type...
virtual unsigned getPrefLoopAlignment(MachineLoop *ML=nullptr) const
Return the preferred loop alignment.
virtual SDValue unwrapAddress(SDValue N) const
void setBooleanContents(BooleanContent Ty)
Specify how the target extends the result of integer and floating point boolean values from i1 to a w...
bool isAcquireOrStronger(AtomicOrdering ao)
virtual bool isFPExtFoldable(unsigned Opcode, EVT DestVT, EVT SrcVT) const
Return true if an fpext operation input to an Opcode operation is free (for instance, because half-precision floating-point numbers are implicitly extended to float-precision) for an FMA instruction.
virtual LoadInst * lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *RMWI) const
On some platforms, an AtomicRMW that never actually modifies the value (such as fetch_add of 0) can b...
virtual unsigned getExceptionSelectorRegister(const Constant *PersonalityFn) const
If a physical register, this returns the register that receives the exception typeid on entry to a la...
CombineLevel
Definition: DAGCombine.h:16
LegalizeAction getCondCodeAction(ISD::CondCode CC, MVT VT) const
Return how the condition code should be treated: either it is legal, needs to be expanded to some oth...
bool optForSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition: Function.h:530
void setOperationPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT)
Convenience method to set an operation to Promote and specify the type in a single call...
bool CombineTo(SDValue O, SDValue N)
bool isOperationLegalOrCustomOrPromote(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
virtual bool targetShrinkDemandedConstant(SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const
virtual bool ExpandInlineAsm(CallInst *) const
This hook allows the target to expand an inline asm call to be explicit llvm code if it wants to...
void setPrefFunctionAlignment(unsigned Align)
Set the target&#39;s preferred function alignment.
virtual bool hasPairedLoad(EVT, unsigned &) const
Return true if the target supplies and combines to a paired load two loaded values of type LoadedType...
virtual MVT getFenceOperandTy(const DataLayout &DL) const
Return the type for operands of fence.
virtual bool isDesirableToCombineBuildVectorToShuffleTruncate(ArrayRef< int > ShuffleMask, EVT SrcVT, EVT TruncVT) const
bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const
Return true if the specified indexed load is legal on this target.
bool isOperationLegal(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target.
virtual bool isDesirableToTransformToIntegerOp(unsigned, EVT) const
Return true if it is profitable for dag combiner to transform a floating point op of specified opcode...
virtual AtomicExpansionKind shouldExpandAtomicRMWInIR(AtomicRMWInst *) const
Returns how the IR-level AtomicExpand pass should expand the given AtomicRMW, if at all...
void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT)
If Opc/OrigVT is specified as being promoted, the promotion code defaults to trying a larger integer/...
lazy value info
unsigned MaxStoresPerMemmove
Specify maximum bytes of store instructions per memmove call.
virtual bool isProfitableToHoist(Instruction *I) const
virtual EVT getTypeForExtReturn(LLVMContext &Context, EVT VT, ISD::NodeType) const
Return the type that should be used to zero or sign extend a zeroext/signext integer return value...
static unsigned NumFixedArgs
std::vector< ArgListEntry > ArgListTy
Extended Value Type.
Definition: ValueTypes.h:34
virtual bool functionArgumentNeedsConsecutiveRegisters(Type *Ty, CallingConv::ID CallConv, bool isVarArg) const
For some targets, an LLVM struct type must be broken down into multiple simple types, but the calling convention specifies that the entire struct must be passed in a block of consecutive registers.
virtual bool allowTruncateForTailCall(Type *FromTy, Type *ToTy) const
Return true if a truncation from FromTy to ToTy is permitted when deciding whether a call is in tail ...
const AMDGPUAS & AS
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual Sched::Preference getSchedulingPreference(SDNode *) const
Some scheduler, e.g.
This structure contains all information that is necessary for lowering calls.
virtual bool isUsedByReturnOnly(SDNode *, SDValue &) const
Return true if result of the specified node is used by a return node only.
bool isExtFree(const Instruction *I) const
Return true if the extension represented by I is free.
const TargetMachine & getTargetMachine() const
void setUseUnderscoreLongJmp(bool Val)
Indicate whether this target prefers to use _longjmp to implement llvm.longjmp or the version without...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC)
Set the CallingConv that should be used for the specified libcall.
AsmOperandInfo(InlineAsm::ConstraintInfo Info)
Copy constructor for copying from a ConstraintInfo.
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
std::string ConstraintCode
This contains the actual string for the code, like "m".
virtual Instruction * emitLeadingFence(IRBuilder<> &Builder, Instruction *Inst, AtomicOrdering Ord) const
Inserts in the IR a target-specific intrinsic specifying a fence.
unsigned getMaxAtomicSizeInBitsSupported() const
Returns the maximum atomic operation size (in bits) supported by the backend.
unsigned GatherAllAliasesMaxDepth
Depth that GatherAllAliases should should continue looking for chain dependencies when trying to find...
bool isInTailCallPosition(ImmutableCallSite CS, const TargetMachine &TM)
Test if the given instruction is in a position to be optimized with a tail-call.
Definition: Analysis.cpp:472
unsigned getMaxStoresPerMemcpy(bool OptSize) const
Get maximum # of store operations permitted for llvm.memcpy.
bool isInvoke() const
Return true if a InvokeInst is enclosed.
Definition: CallSite.h:90
This base class for TargetLowering contains the SelectionDAG-independent parts that can be used from ...
virtual const MCPhysReg * getScratchRegisters(CallingConv::ID CC) const
Returns a 0 terminated array of registers that can be safely used as scratch registers.
void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC)
Override the default CondCode to be used to test the result of the comparison libcall against zero...
virtual bool isExtFreeImpl(const Instruction *I) const
Return true if the extension represented by I is free.
void setHasExtractBitsInsn(bool hasExtractInsn=true)
Tells the code generator that the target has BitExtract instructions.
bool isReleaseOrStronger(AtomicOrdering ao)
LegalizeAction
This enum indicates whether operations are valid for a target, and if not, what action should be used...
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
virtual MVT hasFastEqualityCompare(unsigned NumBits) const
Return the preferred operand type if the target has a quick way to compare integer values of the give...
virtual bool IsDesirableToPromoteOp(SDValue, EVT &) const
This method query the target whether it is beneficial for dag combiner to promote the specified node...
const TargetLowering & getTargetLoweringInfo() const
Definition: SelectionDAG.h:391
virtual bool supportSplitCSR(MachineFunction *MF) const
Return true if the target supports that a subset of CSRs for the given machine function is handled ex...
static const int LAST_LOADEXT_TYPE
Definition: ISDOpcodes.h:898
CCState - This class holds information needed while lowering arguments and return values...
virtual void initializeSplitCSR(MachineBasicBlock *Entry) const
Perform necessary initialization to handle a subset of CSRs explicitly via copies.
ReciprocalEstimate
Reciprocal estimate status values used by the functions below.
virtual bool shouldReduceLoadWidth(SDNode *Load, ISD::LoadExtType ExtTy, EVT NewVT) const
virtual bool shouldNormalizeToSelectSequence(LLVMContext &Context, EVT VT) const
Returns true if we should normalize select(N0&N1, X, Y) => select(N0, select(N1, X, Y), Y) and select(N0|N1, X, Y) => select(N0, select(N1, X, Y, Y)) if it is likely that it saves us from materializing N0 and N1 in an integer register.
virtual bool getPostIndexedAddressParts(SDNode *, SDNode *, SDValue &, SDValue &, ISD::MemIndexedMode &, SelectionDAG &) const
Returns true by value, base pointer and offset pointer and addressing mode by reference if this node ...
virtual bool allowsMisalignedMemoryAccesses(EVT, unsigned AddrSpace=0, unsigned Align=1, bool *=nullptr) const
Determine if the target supports unaligned memory accesses.
virtual const char * getClearCacheBuiltinName() const
Return the builtin name for the __builtin___clear_cache intrinsic Default is to invoke the clear cach...
unsigned getJumpBufSize() const
Returns the target&#39;s jmp_buf size in bytes (if never set, the default is 200)
virtual bool lowerInterleavedLoad(LoadInst *LI, ArrayRef< ShuffleVectorInst *> Shuffles, ArrayRef< unsigned > Indices, unsigned Factor) const
Lower an interleaved load to target specific intrinsics.
bool hasFloatingPointExceptions() const
Return true if target supports floating point exceptions.
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
Definition: SelectionDAG.h:209
virtual unsigned getMaxSupportedInterleaveFactor() const
Get the maximum supported factor for interleaved memory accesses.
CallLoweringInfo & setCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList)
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:864
virtual bool isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, unsigned Index) const
Return true if EXTRACT_SUBVECTOR is cheap for extracting this result type from this source type with ...
bool isSuitableForJumpTable(const SwitchInst *SI, uint64_t NumCases, uint64_t Range) const
Return true if lowering to a jump table is suitable for a set of case clusters which may contain NumC...
Provides information about what library functions are available for the current target.
TargetLoweringOpt(SelectionDAG &InDAG, bool LT, bool LO)
virtual bool isZExtFree(EVT FromTy, EVT ToTy) const
constexpr size_t array_lengthof(T(&)[N])
Find the length of an array.
Definition: STLExtras.h:720
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
Definition: DataLayout.cpp:682
virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &, unsigned) const
Given an intrinsic, checks if on the target the intrinsic will need to map to a MemIntrinsicNode (tou...
LegalizeAction getOperationAction(unsigned Op, EVT VT) const
Return how this operation should be treated: either it is legal, needs to be promoted to a larger siz...
const DenseMap< unsigned int, unsigned int > & getBypassSlowDivWidths() const
Returns map of slow types for division or remainder with corresponding fast types.
virtual bool isVectorLoadExtDesirable(SDValue ExtVal) const
Return true if folding a vector load into ExtVal (a sign, zero, or any extend node) is profitable...
bool rangeFitsInWord(const APInt &Low, const APInt &High, const DataLayout &DL) const
Check whether the range [Low,High] fits in a machine word.
virtual bool isZExtFree(SDValue Val, EVT VT2) const
Return true if zero-extending the specific node Val to type VT2 is free (either because it&#39;s implicit...
bool isTruncStoreLegalOrCustom(EVT ValVT, EVT MemVT) const
Return true if the specified store with truncation has solution on this target.
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
bool areJTsAllowed(const Function *Fn) const
Return true if lowering to a jump table is allowed.
void setHasMultipleConditionRegisters(bool hasManyRegs=true)
Tells the code generator that the target has multiple (allocatable) condition registers that can be u...
CallLoweringInfo & setSExtResult(bool Value=true)
Represents one node in the SelectionDAG.
LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT) const
Return how this store with truncation should be treated: either it is legal, needs to be promoted to ...
static bool Enabled
Definition: Statistic.cpp:49
bool enableExtLdPromotion() const
Return true if the target wants to use the optimization that turns ext(promotableInst1(...(promotableInstN(load)))) into promotedInst1(...(promotedInstN(ext(load)))).
Class to represent vector types.
Definition: DerivedTypes.h:393
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT...
Definition: ValueTypes.h:73
void setIndexedLoadAction(unsigned IdxMode, MVT VT, LegalizeAction Action)
Indicate that the specified indexed load does or does not work with the specified type and indicate w...
Target - Wrapper for Target specific information.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
Class for arbitrary precision integers.
Definition: APInt.h:69
virtual unsigned getVaListSizeInBits(const DataLayout &DL) const
Returns the size of the platform&#39;s va_list object.
virtual bool hasAndNot(SDValue X) const
Return true if the target has a bitwise and-not operation: X = ~A & B This can be used to simplify se...
LegalizeTypeAction getTypeAction(MVT VT) const
void setMinFunctionAlignment(unsigned Align)
Set the target&#39;s minimum function alignment (in log2(bytes))
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition: ValueTypes.h:241
unsigned getMaxExpandSizeMemcmp(bool OptSize) const
Get maximum # of load operations permitted for memcmp.
void setPrefLoopAlignment(unsigned Align)
Set the target&#39;s preferred loop alignment.
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition: ISDOpcodes.h:445
AddrMode
ARM Addressing Modes.
Definition: ARMBaseInfo.h:172
virtual SDValue LowerFormalArguments(SDValue, CallingConv::ID, bool, const SmallVectorImpl< ISD::InputArg > &, const SDLoc &, SelectionDAG &, SmallVectorImpl< SDValue > &) const
This hook must be implemented to lower the incoming (formal) arguments, described by the Ins array...
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition: ISDOpcodes.h:448
ValueTypeActionImpl ValueTypeActions
MulExpansionKind
Enum that specifies when a multiplication should be expanded.
virtual bool needsFixedCatchObjects() const
virtual bool isFMAFasterThanFMulAndFAdd(EVT) const
Return true if an FMA operation is faster than a pair of fmul and fadd instructions.
FMINNAN/FMAXNAN - Behave identically to FMINNUM/FMAXNUM, except that when a single input is NaN...
Definition: ISDOpcodes.h:572
Flags
Flags values. These may be or&#39;d together.
MVT getTypeToPromoteTo(unsigned Op, MVT VT) const
If the action for this operation is to promote, this method returns the ValueType to promote to...
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
virtual bool hasAndNotCompare(SDValue Y) const
Return true if the target should transform: (X & Y) == Y —> (~X & Y) == 0 (X & Y) != Y —> (~X & Y) ...
virtual bool hasStandaloneRem(EVT VT) const
Return true if the target can handle a standalone remainder operation.
virtual bool useSoftFloat() const
CallLoweringInfo & setTailCall(bool Value=true)
virtual bool isLegalICmpImmediate(int64_t) const
Return true if the specified immediate is legal icmp immediate, that is the target has icmp instructi...
BR_JT - Jumptable branch.
Definition: ISDOpcodes.h:605
virtual bool isVectorClearMaskLegal(const SmallVectorImpl< int > &, EVT) const
Similar to isShuffleMaskLegal.
Representation of each machine instruction.
Definition: MachineInstr.h:59
Basic Alias true
CallLoweringInfo & setConvergent(bool Value=true)
SmallVector< SDValue, 32 > OutVals
virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context, EVT VT) const
Certain targets require unusual breakdowns of certain types.
bool isVector() const
Return true if this is a vector value type.
Definition: ValueTypes.h:151
virtual bool convertSelectOfConstantsToMath(EVT VT) const
Return true if a select of constants (select Cond, C1, C2) should be transformed into simple math ops...
Bitwise operators - logical and, logical or, logical xor.
Definition: ISDOpcodes.h:362
FenceInst * CreateFence(AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System, const Twine &Name="")
Definition: IRBuilder.h:1209
SelectSupportKind
Enum that describes what type of support for selects the target has.
virtual SDValue LowerCall(CallLoweringInfo &, SmallVectorImpl< SDValue > &) const
This hook must be implemented to lower calls into the specified DAG.
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition: ISDOpcodes.h:205
const ValueTypeActionImpl & getValueTypeActions() const
StringRef getValueAsString() const
Return the attribute&#39;s value as a string.
Definition: Attributes.cpp:195
void setTypeAction(MVT VT, LegalizeTypeAction Action)
bool isPositionIndependent() const
virtual void insertCopiesSplitCSR(MachineBasicBlock *Entry, const SmallVectorImpl< MachineBasicBlock *> &Exits) const
Insert explicit copies in entry and exit blocks.
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
Definition: ISDOpcodes.h:581
Establish a view to a call site for examination.
Definition: CallSite.h:713
LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const
Return how we should legalize values of this type, either it is already legal (return &#39;Legal&#39;) or we ...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:108
virtual SDValue getRecipEstimate(SDValue Operand, SelectionDAG &DAG, int Enabled, int &RefinementSteps) const
Return a reciprocal estimate value for the input operand.
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
unsigned MaxStoresPerMemmoveOptSize
Maximum number of store instructions that may be substituted for a call to memmove, used for functions with OptSize attribute.
unsigned MaxStoresPerMemcpyOptSize
Maximum number of store operations that may be substituted for a call to memcpy, used for functions w...
void setStackPointerRegisterToSaveRestore(unsigned R)
If set to a physical register, this specifies the register that llvm.savestack/llvm.restorestack should save and restore.
ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const
Get the CondCode that&#39;s to be used to test the result of the comparison libcall against zero...
virtual void emitAtomicCmpXchgNoStoreLLBalance(IRBuilder<> &Builder) const
void setLibcallName(RTLIB::Libcall Call, const char *Name)
Rename the default libcall routine name for the specified libcall.
unsigned getMinCmpXchgSizeInBits() const
Returns the size of the smallest cmpxchg or ll/sc instruction the backend supports.
static const int LAST_INDEXED_MODE
Definition: ISDOpcodes.h:879
virtual bool shouldExpandAtomicStoreInIR(StoreInst *SI) const
Returns true if the given (atomic) store should be expanded by the IR-level AtomicExpand pass into an...
unsigned MaxStoresPerMemcpy
Specify maximum bytes of store instructions per memcpy call.
virtual MachineMemOperand::Flags getMMOFlags(const Instruction &I) const
This callback is used to inspect load/store instructions and add target-specific MachineMemOperand fl...
virtual bool isIntDivCheap(EVT VT, AttributeList Attr) const
Return true if integer divide is usually cheaper than a sequence of several shifts, adds, and multiplies for this target.
static EVT getEVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
Definition: ValueTypes.cpp:311
unsigned getNumRegisters(LLVMContext &Context, EVT VT) const
Return the number of registers that this ValueType will eventually require.
unsigned getMaxStoresPerMemmove(bool OptSize) const
Get maximum # of store operations permitted for llvm.memmove.
const unsigned Kind
Multiway switch.
LegalizeAction getIndexedLoadAction(unsigned IdxMode, MVT VT) const
Return how the indexed load should be treated: either it is legal, needs to be promoted to a larger s...
bool hasAtomicStore() const
Return true if this atomic instruction stores to memory.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void GetReturnInfo(Type *ReturnType, AttributeList attr, SmallVectorImpl< ISD::OutputArg > &Outs, const TargetLowering &TLI, const DataLayout &DL)
Given an LLVM IR type and return type attributes, compute the return value EVTs and flags...
unsigned getMinFunctionAlignment() const
Return the minimum function alignment.
LegalizeTypeAction
This enum indicates whether a types are legal for a target, and if not, what action should be used to...
bool isFloat(MCInstrInfo const &MCII, MCInst const &MCI)
Return whether it is a floating-point insn.
virtual bool CanLowerReturn(CallingConv::ID, MachineFunction &, bool, const SmallVectorImpl< ISD::OutputArg > &, LLVMContext &) const
This hook should be implemented to check whether the return values described by the Outs array can fi...
void setMinStackArgumentAlignment(unsigned Align)
Set the minimum stack alignment of an argument (in log2(bytes)).
void setSchedulingPreference(Sched::Preference Pref)
Specify the target scheduling preference.
CallLoweringInfo & setInRegister(bool Value=true)
bool hasRetAttr(Attribute::AttrKind Kind) const
Return true if this return value has the given attribute.
Definition: CallSite.h:372
LLVM Value Representation.
Definition: Value.h:73
void setUseUnderscoreSetJmp(bool Val)
Indicate whether this target prefers to use _setjmp to implement llvm.setjmp or the version without _...
virtual FastISel * createFastISel(FunctionLoweringInfo &, const TargetLibraryInfo *) const
This method returns a target specific FastISel object, or null if the target does not support "fast" ...
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
unsigned getStackPointerRegisterToSaveRestore() const
If a physical register, this specifies the register that llvm.savestack/llvm.restorestack should save...
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E&#39;s largest value.
Definition: BitmaskEnum.h:81
static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, const APInt &Demanded)
Check to see if the specified operand of the specified instruction is a constant integer.
virtual bool isFsqrtCheap(SDValue X, SelectionDAG &DAG) const
Return true if SQRT(X) shouldn&#39;t be replaced with X*RSQRT(X).
bool isOperationLegalOrPromote(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target or can be made legal using promotion...
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:270
virtual bool shouldExpandBuildVectorWithShuffles(EVT, unsigned DefinedValues) const
MVT getFrameIndexTy(const DataLayout &DL) const
Return the type for frame index, which is determined by the alloca address space specified through th...
bool isLoadExtLegal(unsigned ExtType, EVT ValVT, EVT MemVT) const
Return true if the specified load with extension is legal on this target.
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:57
virtual bool mergeStoresAfterLegalization() const
Allow store merging after legalization in addition to before legalization.
Type * getElementType() const
Definition: DerivedTypes.h:360
virtual int getScalingFactorCost(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS=0) const
Return the cost of the scaling factor used in the addressing mode represented by AM for this target...
IRTranslator LLVM IR MI
bool hasOneUse() const
Return true if there is exactly one user of this value.
Definition: Value.h:414
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
unsigned MaxStoresPerMemset
Specify maximum number of store instructions per memset call.
unsigned MaxStoresPerMemsetOptSize
Maximum number of stores operations that may be substituted for the call to memset, used for functions with OptSize attribute.
virtual bool isShuffleMaskLegal(ArrayRef< int >, EVT) const
Targets can use this to indicate that they only support some VECTOR_SHUFFLE operations, those with specific masks.
Conversion operators.
Definition: ISDOpcodes.h:442
BooleanContent
Enum that describes how the target represents true/false values.
unsigned getGatherAllAliasesMaxDepth() const
bool isBigEndian() const
Definition: DataLayout.h:217
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition: ValueTypes.h:126
bool hasTargetDAGCombine(ISD::NodeType NT) const
If true, the target has custom DAG combine transformations that it can perform for the specified node...
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation...
unsigned getMinStackArgumentAlignment() const
Return the minimum stack alignment of an argument.
virtual bool hasBitPreservingFPLogic(EVT VT) const
Return true if it is safe to transform an integer-domain bitwise operation into the equivalent floati...
virtual SDValue LowerReturn(SDValue, CallingConv::ID, bool, const SmallVectorImpl< ISD::OutputArg > &, const SmallVectorImpl< SDValue > &, const SDLoc &, SelectionDAG &) const
This hook must be implemented to lower outgoing return values, described by the Outs array...
virtual bool shouldAlignPointerArgs(CallInst *, unsigned &, unsigned &) const
Return true if the pointer arguments to CI should be aligned by aligning the object whose address is ...
EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
virtual bool isLegalAddImmediate(int64_t) const
Return true if the specified immediate is legal add immediate, that is the target has add instruction...
virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const
Returns true if a cast between SrcAS and DestAS is a noop.
virtual bool isDesirableToCommuteWithShift(const SDNode *N) const
Return true if it is profitable to move a following shift through this.
virtual bool shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const
Returns true if arguments should be sign-extended in lib calls.
bool use_empty() const
Definition: Value.h:328
bool isExtended() const
Test if the given EVT is extended (as opposed to being simple).
Definition: ValueTypes.h:131
void setBooleanContents(BooleanContent IntTy, BooleanContent FloatTy)
Specify how the target extends the result of integer and floating point boolean values from i1 to a w...
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
bool isOperationExpand(unsigned Op, EVT VT) const
Return true if the specified operation is illegal on this target or unlikely to be made legal with cu...
CallLoweringInfo & setLibCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList)
bool PredictableSelectIsExpensive
Tells the code generator that select is more expensive than a branch if the branch is usually predict...
bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const
Return true if the specified indexed load is legal on this target.
LegalizeTypeAction getTypeAction(MVT VT) const
virtual bool isNarrowingProfitable(EVT, EVT) const
Return true if it&#39;s profitable to narrow operations of type VT1 to VT2.
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:44
virtual bool isFAbsFree(EVT VT) const
Return true if an fabs operation is free to the point where it is never worthwhile to replace it with...
const BasicBlock * getParent() const
Definition: Instruction.h:66
const char * getLibcallName(RTLIB::Libcall Call) const
Get the libcall routine name for the specified libcall.
virtual Instruction * emitTrailingFence(IRBuilder<> &Builder, Instruction *Inst, AtomicOrdering Ord) const
void setIndexedStoreAction(unsigned IdxMode, MVT VT, LegalizeAction Action)
Indicate that the specified indexed store does or does not work with the specified type and indicate ...
MemIndexedMode
MemIndexedMode enum - This enum defines the load / store indexed addressing modes.
Definition: ISDOpcodes.h:871
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition: ISDOpcodes.h:355
BRIND - Indirect branch.
Definition: ISDOpcodes.h:601
This class is used to represent ISD::LOAD nodes.
bool isPredictableSelectExpensive() const
Return true if selects are only cheaper than branches if the branch is unlikely to be predicted right...
bool isExtLoad(const LoadInst *Load, const Instruction *Ext, const DataLayout &DL) const
Return true if Load and Ext can form an ExtLoad.