LLVM  16.0.0git
TargetLowering.h
Go to the documentation of this file.
1 //===- llvm/CodeGen/TargetLowering.h - Target Lowering Info -----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file describes how to lower LLVM code to machine code. This has two
11 /// main components:
12 ///
13 /// 1. Which ValueTypes are natively supported by the target.
14 /// 2. Which operations are supported for supported ValueTypes.
15 /// 3. Cost thresholds for alternative implementations of certain operations.
16 ///
17 /// In addition it has a few other components, like information about FP
18 /// immediates.
19 ///
20 //===----------------------------------------------------------------------===//
21 
22 #ifndef LLVM_CODEGEN_TARGETLOWERING_H
23 #define LLVM_CODEGEN_TARGETLOWERING_H
24 
25 #include "llvm/ADT/APInt.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/StringRef.h"
39 #include "llvm/IR/Attributes.h"
40 #include "llvm/IR/CallingConv.h"
41 #include "llvm/IR/DataLayout.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/InlineAsm.h"
45 #include "llvm/IR/Instruction.h"
46 #include "llvm/IR/Instructions.h"
47 #include "llvm/IR/Type.h"
48 #include "llvm/Support/Alignment.h"
50 #include "llvm/Support/Casting.h"
53 #include <algorithm>
54 #include <cassert>
55 #include <climits>
56 #include <cstdint>
57 #include <iterator>
58 #include <map>
59 #include <string>
60 #include <utility>
61 #include <vector>
62 
63 namespace llvm {
64 
65 class CCState;
66 class CCValAssign;
67 class Constant;
68 class FastISel;
69 class FunctionLoweringInfo;
70 class GlobalValue;
71 class Loop;
72 class GISelKnownBits;
73 class IntrinsicInst;
74 class IRBuilderBase;
75 struct KnownBits;
76 class LegacyDivergenceAnalysis;
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 ProfileSummaryInfo;
88 class TargetLibraryInfo;
89 class TargetMachine;
90 class TargetRegisterClass;
91 class TargetRegisterInfo;
92 class TargetTransformInfo;
93 class Value;
94 
95 namespace Sched {
96 
97 enum Preference {
98  None, // No preference
99  Source, // Follow source order.
100  RegPressure, // Scheduling for lowest register pressure.
101  Hybrid, // Scheduling for both latency and register pressure.
102  ILP, // Scheduling for ILP in low register pressure mode.
103  VLIW, // Scheduling for VLIW targets.
104  Fast, // Fast suboptimal list scheduling
105  Linearize // Linearize DAG, no scheduling
106 };
107 
108 } // end namespace Sched
109 
110 // MemOp models a memory operation, either memset or memcpy/memmove.
111 struct MemOp {
112 private:
113  // Shared
114  uint64_t Size;
115  bool DstAlignCanChange; // true if destination alignment can satisfy any
116  // constraint.
117  Align DstAlign; // Specified alignment of the memory operation.
118 
119  bool AllowOverlap;
120  // memset only
121  bool IsMemset; // If setthis memory operation is a memset.
122  bool ZeroMemset; // If set clears out memory with zeros.
123  // memcpy only
124  bool MemcpyStrSrc; // Indicates whether the memcpy source is an in-register
125  // constant so it does not need to be loaded.
126  Align SrcAlign; // Inferred alignment of the source or default value if the
127  // memory operation does not need to load the value.
128 public:
129  static MemOp Copy(uint64_t Size, bool DstAlignCanChange, Align DstAlign,
130  Align SrcAlign, bool IsVolatile,
131  bool MemcpyStrSrc = false) {
132  MemOp Op;
133  Op.Size = Size;
134  Op.DstAlignCanChange = DstAlignCanChange;
135  Op.DstAlign = DstAlign;
136  Op.AllowOverlap = !IsVolatile;
137  Op.IsMemset = false;
138  Op.ZeroMemset = false;
139  Op.MemcpyStrSrc = MemcpyStrSrc;
140  Op.SrcAlign = SrcAlign;
141  return Op;
142  }
143 
144  static MemOp Set(uint64_t Size, bool DstAlignCanChange, Align DstAlign,
145  bool IsZeroMemset, bool IsVolatile) {
146  MemOp Op;
147  Op.Size = Size;
148  Op.DstAlignCanChange = DstAlignCanChange;
149  Op.DstAlign = DstAlign;
150  Op.AllowOverlap = !IsVolatile;
151  Op.IsMemset = true;
152  Op.ZeroMemset = IsZeroMemset;
153  Op.MemcpyStrSrc = false;
154  return Op;
155  }
156 
157  uint64_t size() const { return Size; }
158  Align getDstAlign() const {
159  assert(!DstAlignCanChange);
160  return DstAlign;
161  }
162  bool isFixedDstAlign() const { return !DstAlignCanChange; }
163  bool allowOverlap() const { return AllowOverlap; }
164  bool isMemset() const { return IsMemset; }
165  bool isMemcpy() const { return !IsMemset; }
167  return isMemcpy() && !DstAlignCanChange;
168  }
169  bool isZeroMemset() const { return isMemset() && ZeroMemset; }
170  bool isMemcpyStrSrc() const {
171  assert(isMemcpy() && "Must be a memcpy");
172  return MemcpyStrSrc;
173  }
174  Align getSrcAlign() const {
175  assert(isMemcpy() && "Must be a memcpy");
176  return SrcAlign;
177  }
178  bool isSrcAligned(Align AlignCheck) const {
179  return isMemset() || llvm::isAligned(AlignCheck, SrcAlign.value());
180  }
181  bool isDstAligned(Align AlignCheck) const {
182  return DstAlignCanChange || llvm::isAligned(AlignCheck, DstAlign.value());
183  }
184  bool isAligned(Align AlignCheck) const {
185  return isSrcAligned(AlignCheck) && isDstAligned(AlignCheck);
186  }
187 };
188 
189 /// This base class for TargetLowering contains the SelectionDAG-independent
190 /// parts that can be used from the rest of CodeGen.
192 public:
193  /// This enum indicates whether operations are valid for a target, and if not,
194  /// what action should be used to make them valid.
195  enum LegalizeAction : uint8_t {
196  Legal, // The target natively supports this operation.
197  Promote, // This operation should be executed in a larger type.
198  Expand, // Try to expand this to other ops, otherwise use a libcall.
199  LibCall, // Don't try to expand this to other ops, always use a libcall.
200  Custom // Use the LowerOperation hook to implement custom lowering.
201  };
202 
203  /// This enum indicates whether a types are legal for a target, and if not,
204  /// what action should be used to make them valid.
205  enum LegalizeTypeAction : uint8_t {
206  TypeLegal, // The target natively supports this type.
207  TypePromoteInteger, // Replace this integer with a larger one.
208  TypeExpandInteger, // Split this integer into two of half the size.
209  TypeSoftenFloat, // Convert this float to a same size integer type.
210  TypeExpandFloat, // Split this float into two of half the size.
211  TypeScalarizeVector, // Replace this one-element vector with its element.
212  TypeSplitVector, // Split this vector into two of half the size.
213  TypeWidenVector, // This vector should be widened into a larger vector.
214  TypePromoteFloat, // Replace this float with a larger one.
215  TypeSoftPromoteHalf, // Soften half to i16 and use float to do arithmetic.
216  TypeScalarizeScalableVector, // This action is explicitly left unimplemented.
217  // While it is theoretically possible to
218  // legalize operations on scalable types with a
219  // loop that handles the vscale * #lanes of the
220  // vector, this is non-trivial at SelectionDAG
221  // level and these types are better to be
222  // widened or promoted.
223  };
224 
225  /// LegalizeKind holds the legalization kind that needs to happen to EVT
226  /// in order to type-legalize it.
227  using LegalizeKind = std::pair<LegalizeTypeAction, EVT>;
228 
229  /// Enum that describes how the target represents true/false values.
231  UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
232  ZeroOrOneBooleanContent, // All bits zero except for bit 0.
233  ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
234  };
235 
236  /// Enum that describes what type of support for selects the target has.
238  ScalarValSelect, // The target supports scalar selects (ex: cmov).
239  ScalarCondVectorVal, // The target supports selects with a scalar condition
240  // and vector values (ex: cmov).
241  VectorMaskSelect // The target supports vector selects with a vector
242  // mask (ex: x86 blends).
243  };
244 
245  /// Enum that specifies what an atomic load/AtomicRMWInst is expanded
246  /// to, if at all. Exists because different targets have different levels of
247  /// support for these atomic instructions, and also have different options
248  /// w.r.t. what they should expand to.
249  enum class AtomicExpansionKind {
250  None, // Don't expand the instruction.
251  CastToInteger, // Cast the atomic instruction to another type, e.g. from
252  // floating-point to integer type.
253  LLSC, // Expand the instruction into loadlinked/storeconditional; used
254  // by ARM/AArch64.
255  LLOnly, // Expand the (load) instruction into just a load-linked, which has
256  // greater atomic guarantees than a normal load.
257  CmpXChg, // Expand the instruction into cmpxchg; used by at least X86.
258  MaskedIntrinsic, // Use a target-specific intrinsic for the LL/SC loop.
259  BitTestIntrinsic, // Use a target-specific intrinsic for special bit
260  // operations; used by X86.
261  CmpArithIntrinsic,// Use a target-specific intrinsic for special compare
262  // operations; used by X86.
263  Expand, // Generic expansion in terms of other atomic operations.
264 
265  // Rewrite to a non-atomic form for use in a known non-preemptible
266  // environment.
267  NotAtomic
268  };
269 
270  /// Enum that specifies when a multiplication should be expanded.
271  enum class MulExpansionKind {
272  Always, // Always expand the instruction.
273  OnlyLegalOrCustom, // Only expand when the resulting instructions are legal
274  // or custom.
275  };
276 
277  /// Enum that specifies when a float negation is beneficial.
278  enum class NegatibleCost {
279  Cheaper = 0, // Negated expression is cheaper.
280  Neutral = 1, // Negated expression has the same cost.
281  Expensive = 2 // Negated expression is more expensive.
282  };
283 
284  class ArgListEntry {
285  public:
286  Value *Val = nullptr;
288  Type *Ty = nullptr;
289  bool IsSExt : 1;
290  bool IsZExt : 1;
291  bool IsInReg : 1;
292  bool IsSRet : 1;
293  bool IsNest : 1;
294  bool IsByVal : 1;
295  bool IsByRef : 1;
296  bool IsInAlloca : 1;
297  bool IsPreallocated : 1;
298  bool IsReturned : 1;
299  bool IsSwiftSelf : 1;
300  bool IsSwiftAsync : 1;
301  bool IsSwiftError : 1;
302  bool IsCFGuardTarget : 1;
303  MaybeAlign Alignment = std::nullopt;
304  Type *IndirectType = nullptr;
305 
311 
312  void setAttributes(const CallBase *Call, unsigned ArgIdx);
313  };
314  using ArgListTy = std::vector<ArgListEntry>;
315 
316  virtual void markLibCallAttributes(MachineFunction *MF, unsigned CC,
317  ArgListTy &Args) const {};
318 
320  switch (Content) {
322  // Extend by adding rubbish bits.
323  return ISD::ANY_EXTEND;
325  // Extend by adding zero bits.
326  return ISD::ZERO_EXTEND;
328  // Extend by copying the sign bit.
329  return ISD::SIGN_EXTEND;
330  }
331  llvm_unreachable("Invalid content kind");
332  }
333 
334  explicit TargetLoweringBase(const TargetMachine &TM);
335  TargetLoweringBase(const TargetLoweringBase &) = delete;
337  virtual ~TargetLoweringBase() = default;
338 
339  /// Return true if the target support strict float operation
340  bool isStrictFPEnabled() const {
341  return IsStrictFPEnabled;
342  }
343 
344 protected:
345  /// Initialize all of the actions to default values.
346  void initActions();
347 
348 public:
349  const TargetMachine &getTargetMachine() const { return TM; }
350 
351  virtual bool useSoftFloat() const { return false; }
352 
353  /// Return the pointer type for the given address space, defaults to
354  /// the pointer type from the data layout.
355  /// FIXME: The default needs to be removed once all the code is updated.
356  virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS = 0) const {
357  return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
358  }
359 
360  /// Return the in-memory pointer type for the given address space, defaults to
361  /// the pointer type from the data layout. FIXME: The default needs to be
362  /// removed once all the code is updated.
363  virtual MVT getPointerMemTy(const DataLayout &DL, uint32_t AS = 0) const {
364  return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
365  }
366 
367  /// Return the type for frame index, which is determined by
368  /// the alloca address space specified through the data layout.
370  return getPointerTy(DL, DL.getAllocaAddrSpace());
371  }
372 
373  /// Return the type for code pointers, which is determined by the program
374  /// address space specified through the data layout.
376  return getPointerTy(DL, DL.getProgramAddressSpace());
377  }
378 
379  /// Return the type for operands of fence.
380  /// TODO: Let fence operands be of i32 type and remove this.
381  virtual MVT getFenceOperandTy(const DataLayout &DL) const {
382  return getPointerTy(DL);
383  }
384 
385  /// Return the type to use for a scalar shift opcode, given the shifted amount
386  /// type. Targets should return a legal type if the input type is legal.
387  /// Targets can return a type that is too small if the input type is illegal.
388  virtual MVT getScalarShiftAmountTy(const DataLayout &, EVT) const;
389 
390  /// Returns the type for the shift amount of a shift opcode. For vectors,
391  /// returns the input type. For scalars, behavior depends on \p LegalTypes. If
392  /// \p LegalTypes is true, calls getScalarShiftAmountTy, otherwise uses
393  /// pointer type. If getScalarShiftAmountTy or pointer type cannot represent
394  /// all possible shift amounts, returns MVT::i32. In general, \p LegalTypes
395  /// should be set to true for calls during type legalization and after type
396  /// legalization has been completed.
397  EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL,
398  bool LegalTypes = true) const;
399 
400  /// Return the preferred type to use for a shift opcode, given the shifted
401  /// amount type is \p ShiftValueTy.
403  virtual LLT getPreferredShiftAmountTy(LLT ShiftValueTy) const {
404  return ShiftValueTy;
405  }
406 
407  /// Returns the type to be used for the index operand of:
408  /// ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
409  /// ISD::INSERT_SUBVECTOR, and ISD::EXTRACT_SUBVECTOR
410  virtual MVT getVectorIdxTy(const DataLayout &DL) const {
411  return getPointerTy(DL);
412  }
413 
414  /// Returns the type to be used for the EVL/AVL operand of VP nodes:
415  /// ISD::VP_ADD, ISD::VP_SUB, etc. It must be a legal scalar integer type,
416  /// and must be at least as large as i32. The EVL is implicitly zero-extended
417  /// to any larger type.
418  virtual MVT getVPExplicitVectorLengthTy() const { return MVT::i32; }
419 
420  /// This callback is used to inspect load/store instructions and add
421  /// target-specific MachineMemOperand flags to them. The default
422  /// implementation does nothing.
425  }
426 
428  const DataLayout &DL) const;
430  const DataLayout &DL) const;
432  const DataLayout &DL) const;
433 
434  virtual bool isSelectSupported(SelectSupportKind /*kind*/) const {
435  return true;
436  }
437 
438  /// Return true if the @llvm.get.active.lane.mask intrinsic should be expanded
439  /// using generic code in SelectionDAGBuilder.
440  virtual bool shouldExpandGetActiveLaneMask(EVT VT, EVT OpVT) const {
441  return true;
442  }
443 
444  /// Return true if it is profitable to convert a select of FP constants into
445  /// a constant pool load whose address depends on the select condition. The
446  /// parameter may be used to differentiate a select with FP compare from
447  /// integer compare.
448  virtual bool reduceSelectOfFPConstantLoads(EVT CmpOpVT) const {
449  return true;
450  }
451 
452  /// Return true if multiple condition registers are available.
454  return HasMultipleConditionRegisters;
455  }
456 
457  /// Return true if the target has BitExtract instructions.
458  bool hasExtractBitsInsn() const { return HasExtractBitsInsn; }
459 
460  /// Return the preferred vector type legalization action.
463  // The default action for one element vectors is to scalarize
464  if (VT.getVectorElementCount().isScalar())
465  return TypeScalarizeVector;
466  // The default action for an odd-width vector is to widen.
467  if (!VT.isPow2VectorType())
468  return TypeWidenVector;
469  // The default action for other vectors is to promote
470  return TypePromoteInteger;
471  }
472 
473  // Return true if the half type should be passed around as i16, but promoted
474  // to float around arithmetic. The default behavior is to pass around as
475  // float and convert around loads/stores/bitcasts and other places where
476  // the size matters.
477  virtual bool softPromoteHalfType() const { return false; }
478 
479  // There are two general methods for expanding a BUILD_VECTOR node:
480  // 1. Use SCALAR_TO_VECTOR on the defined scalar values and then shuffle
481  // them together.
482  // 2. Build the vector on the stack and then load it.
483  // If this function returns true, then method (1) will be used, subject to
484  // the constraint that all of the necessary shuffles are legal (as determined
485  // by isShuffleMaskLegal). If this function returns false, then method (2) is
486  // always used. The vector type, and the number of defined values, are
487  // provided.
488  virtual bool
490  unsigned DefinedValues) const {
491  return DefinedValues < 3;
492  }
493 
494  /// Return true if integer divide is usually cheaper than a sequence of
495  /// several shifts, adds, and multiplies for this target.
496  /// The definition of "cheaper" may depend on whether we're optimizing
497  /// for speed or for size.
498  virtual bool isIntDivCheap(EVT VT, AttributeList Attr) const { return false; }
499 
500  /// Return true if the target can handle a standalone remainder operation.
501  virtual bool hasStandaloneRem(EVT VT) const {
502  return true;
503  }
504 
505  /// Return true if SQRT(X) shouldn't be replaced with X*RSQRT(X).
506  virtual bool isFsqrtCheap(SDValue X, SelectionDAG &DAG) const {
507  // Default behavior is to replace SQRT(X) with X*RSQRT(X).
508  return false;
509  }
510 
511  /// Reciprocal estimate status values used by the functions below.
512  enum ReciprocalEstimate : int {
514  Disabled = 0,
516  };
517 
518  /// Return a ReciprocalEstimate enum value for a square root of the given type
519  /// based on the function's attributes. If the operation is not overridden by
520  /// the function's attributes, "Unspecified" is returned and target defaults
521  /// are expected to be used for instruction selection.
523 
524  /// Return a ReciprocalEstimate enum value for a division of the given type
525  /// based on the function's attributes. If the operation is not overridden by
526  /// the function's attributes, "Unspecified" is returned and target defaults
527  /// are expected to be used for instruction selection.
529 
530  /// Return the refinement step count for a square root of the given type based
531  /// on the function's attributes. If the operation is not overridden by
532  /// the function's attributes, "Unspecified" is returned and target defaults
533  /// are expected to be used for instruction selection.
534  int getSqrtRefinementSteps(EVT VT, MachineFunction &MF) const;
535 
536  /// Return the refinement step count for a division of the given type based
537  /// on the function's attributes. If the operation is not overridden by
538  /// the function's attributes, "Unspecified" is returned and target defaults
539  /// are expected to be used for instruction selection.
540  int getDivRefinementSteps(EVT VT, MachineFunction &MF) const;
541 
542  /// Returns true if target has indicated at least one type should be bypassed.
543  bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
544 
545  /// Returns map of slow types for division or remainder with corresponding
546  /// fast types
548  return BypassSlowDivWidths;
549  }
550 
551  /// Return true only if vscale must be a power of two.
552  virtual bool isVScaleKnownToBeAPowerOfTwo() const { return false; }
553 
554  /// Return true if Flow Control is an expensive operation that should be
555  /// avoided.
556  bool isJumpExpensive() const { return JumpIsExpensive; }
557 
558  /// Return true if selects are only cheaper than branches if the branch is
559  /// unlikely to be predicted right.
562  }
563 
564  virtual bool fallBackToDAGISel(const Instruction &Inst) const {
565  return false;
566  }
567 
568  /// Return true if the following transform is beneficial:
569  /// fold (conv (load x)) -> (load (conv*)x)
570  /// On architectures that don't natively support some vector loads
571  /// efficiently, casting the load to a smaller vector of larger types and
572  /// loading is more efficient, however, this can be undone by optimizations in
573  /// dag combiner.
574  virtual bool isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT,
575  const SelectionDAG &DAG,
576  const MachineMemOperand &MMO) const {
577  // Don't do if we could do an indexed load on the original type, but not on
578  // the new one.
579  if (!LoadVT.isSimple() || !BitcastVT.isSimple())
580  return true;
581 
582  MVT LoadMVT = LoadVT.getSimpleVT();
583 
584  // Don't bother doing this if it's just going to be promoted again later, as
585  // doing so might interfere with other combines.
586  if (getOperationAction(ISD::LOAD, LoadMVT) == Promote &&
587  getTypeToPromoteTo(ISD::LOAD, LoadMVT) == BitcastVT.getSimpleVT())
588  return false;
589 
590  unsigned Fast = 0;
591  return allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), BitcastVT,
592  MMO, &Fast) && Fast;
593  }
594 
595  /// Return true if the following transform is beneficial:
596  /// (store (y (conv x)), y*)) -> (store x, (x*))
597  virtual bool isStoreBitCastBeneficial(EVT StoreVT, EVT BitcastVT,
598  const SelectionDAG &DAG,
599  const MachineMemOperand &MMO) const {
600  // Default to the same logic as loads.
601  return isLoadBitCastBeneficial(StoreVT, BitcastVT, DAG, MMO);
602  }
603 
604  /// Return true if it is expected to be cheaper to do a store of a non-zero
605  /// vector constant with the given size and type for the address space than to
606  /// store the individual scalar element constants.
607  virtual bool storeOfVectorConstantIsCheap(EVT MemVT,
608  unsigned NumElem,
609  unsigned AddrSpace) const {
610  return false;
611  }
612 
613  /// Allow store merging for the specified type after legalization in addition
614  /// to before legalization. This may transform stores that do not exist
615  /// earlier (for example, stores created from intrinsics).
616  virtual bool mergeStoresAfterLegalization(EVT MemVT) const {
617  return true;
618  }
619 
620  /// Returns if it's reasonable to merge stores to MemVT size.
621  virtual bool canMergeStoresTo(unsigned AS, EVT MemVT,
622  const MachineFunction &MF) const {
623  return true;
624  }
625 
626  /// Return true if it is cheap to speculate a call to intrinsic cttz.
627  virtual bool isCheapToSpeculateCttz(Type *Ty) const {
628  return false;
629  }
630 
631  /// Return true if it is cheap to speculate a call to intrinsic ctlz.
632  virtual bool isCheapToSpeculateCtlz(Type *Ty) const {
633  return false;
634  }
635 
636  /// Return true if ctlz instruction is fast.
637  virtual bool isCtlzFast() const {
638  return false;
639  }
640 
641  /// Return the maximum number of "x & (x - 1)" operations that can be done
642  /// instead of deferring to a custom CTPOP.
643  virtual unsigned getCustomCtpopCost(EVT VT, ISD::CondCode Cond) const {
644  return 1;
645  }
646 
647  /// Return true if instruction generated for equality comparison is folded
648  /// with instruction generated for signed comparison.
649  virtual bool isEqualityCmpFoldedWithSignedCmp() const { return true; }
650 
651  /// Return true if the heuristic to prefer icmp eq zero should be used in code
652  /// gen prepare.
653  virtual bool preferZeroCompareBranch() const { return false; }
654 
655  /// Return true if it is safe to transform an integer-domain bitwise operation
656  /// into the equivalent floating-point operation. This should be set to true
657  /// if the target has IEEE-754-compliant fabs/fneg operations for the input
658  /// type.
659  virtual bool hasBitPreservingFPLogic(EVT VT) const {
660  return false;
661  }
662 
663  /// Return true if it is cheaper to split the store of a merged int val
664  /// from a pair of smaller values into multiple stores.
665  virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const {
666  return false;
667  }
668 
669  /// Return if the target supports combining a
670  /// chain like:
671  /// \code
672  /// %andResult = and %val1, #mask
673  /// %icmpResult = icmp %andResult, 0
674  /// \endcode
675  /// into a single machine instruction of a form like:
676  /// \code
677  /// cc = test %register, #mask
678  /// \endcode
679  virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
680  return false;
681  }
682 
683  /// Use bitwise logic to make pairs of compares more efficient. For example:
684  /// and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
685  /// This should be true when it takes more than one instruction to lower
686  /// setcc (cmp+set on x86 scalar), when bitwise ops are faster than logic on
687  /// condition bits (crand on PowerPC), and/or when reducing cmp+br is a win.
688  virtual bool convertSetCCLogicToBitwiseLogic(EVT VT) const {
689  return false;
690  }
691 
692  /// Return the preferred operand type if the target has a quick way to compare
693  /// integer values of the given size. Assume that any legal integer type can
694  /// be compared efficiently. Targets may override this to allow illegal wide
695  /// types to return a vector type if there is support to compare that type.
696  virtual MVT hasFastEqualityCompare(unsigned NumBits) const {
697  MVT VT = MVT::getIntegerVT(NumBits);
699  }
700 
701  /// Return true if the target should transform:
702  /// (X & Y) == Y ---> (~X & Y) == 0
703  /// (X & Y) != Y ---> (~X & Y) != 0
704  ///
705  /// This may be profitable if the target has a bitwise and-not operation that
706  /// sets comparison flags. A target may want to limit the transformation based
707  /// on the type of Y or if Y is a constant.
708  ///
709  /// Note that the transform will not occur if Y is known to be a power-of-2
710  /// because a mask and compare of a single bit can be handled by inverting the
711  /// predicate, for example:
712  /// (X & 8) == 8 ---> (X & 8) != 0
713  virtual bool hasAndNotCompare(SDValue Y) const {
714  return false;
715  }
716 
717  /// Return true if the target has a bitwise and-not operation:
718  /// X = ~A & B
719  /// This can be used to simplify select or other instructions.
720  virtual bool hasAndNot(SDValue X) const {
721  // If the target has the more complex version of this operation, assume that
722  // it has this operation too.
723  return hasAndNotCompare(X);
724  }
725 
726  /// Return true if the target has a bit-test instruction:
727  /// (X & (1 << Y)) ==/!= 0
728  /// This knowledge can be used to prevent breaking the pattern,
729  /// or creating it if it could be recognized.
730  virtual bool hasBitTest(SDValue X, SDValue Y) const { return false; }
731 
732  /// There are two ways to clear extreme bits (either low or high):
733  /// Mask: x & (-1 << y) (the instcombine canonical form)
734  /// Shifts: x >> y << y
735  /// Return true if the variant with 2 variable shifts is preferred.
736  /// Return false if there is no preference.
738  // By default, let's assume that no one prefers shifts.
739  return false;
740  }
741 
742  /// Return true if it is profitable to fold a pair of shifts into a mask.
743  /// This is usually true on most targets. But some targets, like Thumb1,
744  /// have immediate shift instructions, but no immediate "and" instruction;
745  /// this makes the fold unprofitable.
747  CombineLevel Level) const {
748  return true;
749  }
750 
751  /// Should we tranform the IR-optimal check for whether given truncation
752  /// down into KeptBits would be truncating or not:
753  /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
754  /// Into it's more traditional form:
755  /// ((%x << C) a>> C) dstcond %x
756  /// Return true if we should transform.
757  /// Return false if there is no preference.
759  unsigned KeptBits) const {
760  // By default, let's assume that no one prefers shifts.
761  return false;
762  }
763 
764  /// Given the pattern
765  /// (X & (C l>>/<< Y)) ==/!= 0
766  /// return true if it should be transformed into:
767  /// ((X <</l>> Y) & C) ==/!= 0
768  /// WARNING: if 'X' is a constant, the fold may deadlock!
769  /// FIXME: we could avoid passing XC, but we can't use isConstOrConstSplat()
770  /// here because it can end up being not linked in.
773  unsigned OldShiftOpcode, unsigned NewShiftOpcode,
774  SelectionDAG &DAG) const {
775  if (hasBitTest(X, Y)) {
776  // One interesting pattern that we'd want to form is 'bit test':
777  // ((1 << Y) & C) ==/!= 0
778  // But we also need to be careful not to try to reverse that fold.
779 
780  // Is this '1 << Y' ?
781  if (OldShiftOpcode == ISD::SHL && CC->isOne())
782  return false; // Keep the 'bit test' pattern.
783 
784  // Will it be '1 << Y' after the transform ?
785  if (XC && NewShiftOpcode == ISD::SHL && XC->isOne())
786  return true; // Do form the 'bit test' pattern.
787  }
788 
789  // If 'X' is a constant, and we transform, then we will immediately
790  // try to undo the fold, thus causing endless combine loop.
791  // So by default, let's assume everyone prefers the fold
792  // iff 'X' is not a constant.
793  return !XC;
794  }
795 
796  /// These two forms are equivalent:
797  /// sub %y, (xor %x, -1)
798  /// add (add %x, 1), %y
799  /// The variant with two add's is IR-canonical.
800  /// Some targets may prefer one to the other.
801  virtual bool preferIncOfAddToSubOfNot(EVT VT) const {
802  // By default, let's assume that everyone prefers the form with two add's.
803  return true;
804  }
805 
806  /// Return true if the target wants to use the optimization that
807  /// turns ext(promotableInst1(...(promotableInstN(load)))) into
808  /// promotedInst1(...(promotedInstN(ext(load)))).
810 
811  /// Return true if the target can combine store(extractelement VectorTy,
812  /// Idx).
813  /// \p Cost[out] gives the cost of that transformation when this is true.
814  virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
815  unsigned &Cost) const {
816  return false;
817  }
818 
819  /// Return true if inserting a scalar into a variable element of an undef
820  /// vector is more efficiently handled by splatting the scalar instead.
821  virtual bool shouldSplatInsEltVarIndex(EVT) const {
822  return false;
823  }
824 
825  /// Return true if target always benefits from combining into FMA for a
826  /// given value type. This must typically return false on targets where FMA
827  /// takes more cycles to execute than FADD.
828  virtual bool enableAggressiveFMAFusion(EVT VT) const { return false; }
829 
830  /// Return true if target always benefits from combining into FMA for a
831  /// given value type. This must typically return false on targets where FMA
832  /// takes more cycles to execute than FADD.
833  virtual bool enableAggressiveFMAFusion(LLT Ty) const { return false; }
834 
835  /// Return the ValueType of the result of SETCC operations.
837  EVT VT) const;
838 
839  /// Return the ValueType for comparison libcalls. Comparison libcalls include
840  /// floating point comparison calls, and Ordered/Unordered check calls on
841  /// floating point numbers.
842  virtual
844 
845  /// For targets without i1 registers, this gives the nature of the high-bits
846  /// of boolean values held in types wider than i1.
847  ///
848  /// "Boolean values" are special true/false values produced by nodes like
849  /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
850  /// Not to be confused with general values promoted from i1. Some cpus
851  /// distinguish between vectors of boolean and scalars; the isVec parameter
852  /// selects between the two kinds. For example on X86 a scalar boolean should
853  /// be zero extended from i1, while the elements of a vector of booleans
854  /// should be sign extended from i1.
855  ///
856  /// Some cpus also treat floating point types the same way as they treat
857  /// vectors instead of the way they treat scalars.
858  BooleanContent getBooleanContents(bool isVec, bool isFloat) const {
859  if (isVec)
860  return BooleanVectorContents;
861  return isFloat ? BooleanFloatContents : BooleanContents;
862  }
863 
865  return getBooleanContents(Type.isVector(), Type.isFloatingPoint());
866  }
867 
868  /// Promote the given target boolean to a target boolean of the given type.
869  /// A target boolean is an integer value, not necessarily of type i1, the bits
870  /// of which conform to getBooleanContents.
871  ///
872  /// ValVT is the type of values that produced the boolean.
874  EVT ValVT) const {
875  SDLoc dl(Bool);
876  EVT BoolVT =
877  getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ValVT);
879  return DAG.getNode(ExtendCode, dl, BoolVT, Bool);
880  }
881 
882  /// Return target scheduling preference.
884  return SchedPreferenceInfo;
885  }
886 
887  /// Some scheduler, e.g. hybrid, can switch to different scheduling heuristics
888  /// for different nodes. This function returns the preference (or none) for
889  /// the given node.
891  return Sched::None;
892  }
893 
894  /// Return the register class that should be used for the specified value
895  /// type.
896  virtual const TargetRegisterClass *getRegClassFor(MVT VT, bool isDivergent = false) const {
897  (void)isDivergent;
898  const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
899  assert(RC && "This value type is not natively supported!");
900  return RC;
901  }
902 
903  /// Allows target to decide about the register class of the
904  /// specific value that is live outside the defining block.
905  /// Returns true if the value needs uniform register class.
907  const Value *) const {
908  return false;
909  }
910 
911  /// Return the 'representative' register class for the specified value
912  /// type.
913  ///
914  /// The 'representative' register class is the largest legal super-reg
915  /// register class for the register class of the value type. For example, on
916  /// i386 the rep register class for i8, i16, and i32 are GR32; while the rep
917  /// register class is GR64 on x86_64.
918  virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
919  const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
920  return RC;
921  }
922 
923  /// Return the cost of the 'representative' register class for the specified
924  /// value type.
925  virtual uint8_t getRepRegClassCostFor(MVT VT) const {
926  return RepRegClassCostForVT[VT.SimpleTy];
927  }
928 
929  /// Return true if SHIFT instructions should be expanded to SHIFT_PARTS
930  /// instructions, and false if a library call is preferred (e.g for code-size
931  /// reasons).
932  virtual bool shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
933  return true;
934  }
935 
936  /// Return true if the target has native support for the specified value type.
937  /// This means that it has a register that directly holds it without
938  /// promotions or expansions.
939  bool isTypeLegal(EVT VT) const {
940  assert(!VT.isSimple() ||
941  (unsigned)VT.getSimpleVT().SimpleTy < std::size(RegClassForVT));
942  return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != nullptr;
943  }
944 
946  /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
947  /// that indicates how instruction selection should deal with the type.
948  LegalizeTypeAction ValueTypeActions[MVT::VALUETYPE_SIZE];
949 
950  public:
952  std::fill(std::begin(ValueTypeActions), std::end(ValueTypeActions),
953  TypeLegal);
954  }
955 
957  return ValueTypeActions[VT.SimpleTy];
958  }
959 
961  ValueTypeActions[VT.SimpleTy] = Action;
962  }
963  };
964 
966  return ValueTypeActions;
967  }
968 
969  /// Return pair that represents the legalization kind (first) that needs to
970  /// happen to EVT (second) in order to type-legalize it.
971  ///
972  /// First: how we should legalize values of this type, either it is already
973  /// legal (return 'Legal') or we need to promote it to a larger type (return
974  /// 'Promote'), or we need to expand it into multiple registers of smaller
975  /// integer type (return 'Expand'). 'Custom' is not an option.
976  ///
977  /// Second: for types supported by the target, this is an identity function.
978  /// For types that must be promoted to larger types, this returns the larger
979  /// type to promote to. For integer types that are larger than the largest
980  /// integer register, this contains one step in the expansion to get to the
981  /// smaller register. For illegal floating point types, this returns the
982  /// integer type to transform to.
984 
985  /// Return how we should legalize values of this type, either it is already
986  /// legal (return 'Legal') or we need to promote it to a larger type (return
987  /// 'Promote'), or we need to expand it into multiple registers of smaller
988  /// integer type (return 'Expand'). 'Custom' is not an option.
990  return getTypeConversion(Context, VT).first;
991  }
993  return ValueTypeActions.getTypeAction(VT);
994  }
995 
996  /// For types supported by the target, this is an identity function. For
997  /// types that must be promoted to larger types, this returns the larger type
998  /// to promote to. For integer types that are larger than the largest integer
999  /// register, this contains one step in the expansion to get to the smaller
1000  /// register. For illegal floating point types, this returns the integer type
1001  /// to transform to.
1003  return getTypeConversion(Context, VT).second;
1004  }
1005 
1006  /// For types supported by the target, this is an identity function. For
1007  /// types that must be expanded (i.e. integer types that are larger than the
1008  /// largest integer register or illegal floating point types), this returns
1009  /// the largest legal type it will be expanded to.
1011  assert(!VT.isVector());
1012  while (true) {
1013  switch (getTypeAction(Context, VT)) {
1014  case TypeLegal:
1015  return VT;
1016  case TypeExpandInteger:
1017  VT = getTypeToTransformTo(Context, VT);
1018  break;
1019  default:
1020  llvm_unreachable("Type is not legal nor is it to be expanded!");
1021  }
1022  }
1023  }
1024 
1025  /// Vector types are broken down into some number of legal first class types.
1026  /// For example, EVT::v8f32 maps to 2 EVT::v4f32 with Altivec or SSE1, or 8
1027  /// promoted EVT::f64 values with the X86 FP stack. Similarly, EVT::v2i64
1028  /// turns into 4 EVT::i32 values with both PPC and X86.
1029  ///
1030  /// This method returns the number of registers needed, and the VT for each
1031  /// register. It also returns the VT and quantity of the intermediate values
1032  /// before they are promoted/expanded.
1034  EVT &IntermediateVT,
1035  unsigned &NumIntermediates,
1036  MVT &RegisterVT) const;
1037 
1038  /// Certain targets such as MIPS require that some types such as vectors are
1039  /// always broken down into scalars in some contexts. This occurs even if the
1040  /// vector type is legal.
1042  LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
1043  unsigned &NumIntermediates, MVT &RegisterVT) const {
1044  return getVectorTypeBreakdown(Context, VT, IntermediateVT, NumIntermediates,
1045  RegisterVT);
1046  }
1047 
1048  struct IntrinsicInfo {
1049  unsigned opc = 0; // target opcode
1050  EVT memVT; // memory VT
1051 
1052  // value representing memory location
1054 
1055  // Fallback address space for use if ptrVal is nullptr. std::nullopt means
1056  // unknown address space.
1057  std::optional<unsigned> fallbackAddressSpace;
1058 
1059  int offset = 0; // offset off of ptrVal
1060  uint64_t size = 0; // the size of the memory location
1061  // (taken from memVT if zero)
1062  MaybeAlign align = Align(1); // alignment
1063 
1065  IntrinsicInfo() = default;
1066  };
1067 
1068  /// Given an intrinsic, checks if on the target the intrinsic will need to map
1069  /// to a MemIntrinsicNode (touches memory). If this is the case, it returns
1070  /// true and store the intrinsic information into the IntrinsicInfo that was
1071  /// passed to the function.
1072  virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
1073  MachineFunction &,
1074  unsigned /*Intrinsic*/) const {
1075  return false;
1076  }
1077 
1078  /// Returns true if the target can instruction select the specified FP
1079  /// immediate natively. If false, the legalizer will materialize the FP
1080  /// immediate as a load from a constant pool.
1081  virtual bool isFPImmLegal(const APFloat & /*Imm*/, EVT /*VT*/,
1082  bool ForCodeSize = false) const {
1083  return false;
1084  }
1085 
1086  /// Targets can use this to indicate that they only support *some*
1087  /// VECTOR_SHUFFLE operations, those with specific masks. By default, if a
1088  /// target supports the VECTOR_SHUFFLE node, all mask values are assumed to be
1089  /// legal.
1090  virtual bool isShuffleMaskLegal(ArrayRef<int> /*Mask*/, EVT /*VT*/) const {
1091  return true;
1092  }
1093 
1094  /// Returns true if the operation can trap for the value type.
1095  ///
1096  /// VT must be a legal type. By default, we optimistically assume most
1097  /// operations don't trap except for integer divide and remainder.
1098  virtual bool canOpTrap(unsigned Op, EVT VT) const;
1099 
1100  /// Similar to isShuffleMaskLegal. Targets can use this to indicate if there
1101  /// is a suitable VECTOR_SHUFFLE that can be used to replace a VAND with a
1102  /// constant pool entry.
1103  virtual bool isVectorClearMaskLegal(ArrayRef<int> /*Mask*/,
1104  EVT /*VT*/) const {
1105  return false;
1106  }
1107 
1108  /// How to legalize this custom operation?
1110  return Legal;
1111  }
1112 
1113  /// Return how this operation should be treated: either it is legal, needs to
1114  /// be promoted to a larger size, needs to be expanded to some other code
1115  /// sequence, or the target has a custom expander for it.
1116  LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
1117  if (VT.isExtended()) return Expand;
1118  // If a target-specific SDNode requires legalization, require the target
1119  // to provide custom legalization for it.
1120  if (Op >= std::size(OpActions[0]))
1121  return Custom;
1122  return OpActions[(unsigned)VT.getSimpleVT().SimpleTy][Op];
1123  }
1124 
1125  /// Custom method defined by each target to indicate if an operation which
1126  /// may require a scale is supported natively by the target.
1127  /// If not, the operation is illegal.
1128  virtual bool isSupportedFixedPointOperation(unsigned Op, EVT VT,
1129  unsigned Scale) const {
1130  return false;
1131  }
1132 
1133  /// Some fixed point operations may be natively supported by the target but
1134  /// only for specific scales. This method allows for checking
1135  /// if the width is supported by the target for a given operation that may
1136  /// depend on scale.
1138  unsigned Scale) const {
1139  auto Action = getOperationAction(Op, VT);
1140  if (Action != Legal)
1141  return Action;
1142 
1143  // This operation is supported in this type but may only work on specific
1144  // scales.
1145  bool Supported;
1146  switch (Op) {
1147  default:
1148  llvm_unreachable("Unexpected fixed point operation.");
1149  case ISD::SMULFIX:
1150  case ISD::SMULFIXSAT:
1151  case ISD::UMULFIX:
1152  case ISD::UMULFIXSAT:
1153  case ISD::SDIVFIX:
1154  case ISD::SDIVFIXSAT:
1155  case ISD::UDIVFIX:
1156  case ISD::UDIVFIXSAT:
1157  Supported = isSupportedFixedPointOperation(Op, VT, Scale);
1158  break;
1159  }
1160 
1161  return Supported ? Action : Expand;
1162  }
1163 
1164  // If Op is a strict floating-point operation, return the result
1165  // of getOperationAction for the equivalent non-strict operation.
1167  unsigned EqOpc;
1168  switch (Op) {
1169  default: llvm_unreachable("Unexpected FP pseudo-opcode");
1170 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
1171  case ISD::STRICT_##DAGN: EqOpc = ISD::DAGN; break;
1172 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
1173  case ISD::STRICT_##DAGN: EqOpc = ISD::SETCC; break;
1174 #include "llvm/IR/ConstrainedOps.def"
1175  }
1176 
1177  return getOperationAction(EqOpc, VT);
1178  }
1179 
1180  /// Return true if the specified operation is legal on this target or can be
1181  /// made legal with custom lowering. This is used to help guide high-level
1182  /// lowering decisions. LegalOnly is an optional convenience for code paths
1183  /// traversed pre and post legalisation.
1184  bool isOperationLegalOrCustom(unsigned Op, EVT VT,
1185  bool LegalOnly = false) const {
1186  if (LegalOnly)
1187  return isOperationLegal(Op, VT);
1188 
1189  return (VT == MVT::Other || isTypeLegal(VT)) &&
1190  (getOperationAction(Op, VT) == Legal ||
1191  getOperationAction(Op, VT) == Custom);
1192  }
1193 
1194  /// Return true if the specified operation is legal on this target or can be
1195  /// made legal using promotion. This is used to help guide high-level lowering
1196  /// decisions. LegalOnly is an optional convenience for code paths traversed
1197  /// pre and post legalisation.
1198  bool isOperationLegalOrPromote(unsigned Op, EVT VT,
1199  bool LegalOnly = false) const {
1200  if (LegalOnly)
1201  return isOperationLegal(Op, VT);
1202 
1203  return (VT == MVT::Other || isTypeLegal(VT)) &&
1204  (getOperationAction(Op, VT) == Legal ||
1205  getOperationAction(Op, VT) == Promote);
1206  }
1207 
1208  /// Return true if the specified operation is legal on this target or can be
1209  /// made legal with custom lowering or using promotion. This is used to help
1210  /// guide high-level lowering decisions. LegalOnly is an optional convenience
1211  /// for code paths traversed pre and post legalisation.
1213  bool LegalOnly = false) const {
1214  if (LegalOnly)
1215  return isOperationLegal(Op, VT);
1216 
1217  return (VT == MVT::Other || isTypeLegal(VT)) &&
1218  (getOperationAction(Op, VT) == Legal ||
1219  getOperationAction(Op, VT) == Custom ||
1220  getOperationAction(Op, VT) == Promote);
1221  }
1222 
1223  /// Return true if the operation uses custom lowering, regardless of whether
1224  /// the type is legal or not.
1225  bool isOperationCustom(unsigned Op, EVT VT) const {
1226  return getOperationAction(Op, VT) == Custom;
1227  }
1228 
1229  /// Return true if lowering to a jump table is allowed.
1230  virtual bool areJTsAllowed(const Function *Fn) const {
1231  if (Fn->getFnAttribute("no-jump-tables").getValueAsBool())
1232  return false;
1233 
1236  }
1237 
1238  /// Check whether the range [Low,High] fits in a machine word.
1239  bool rangeFitsInWord(const APInt &Low, const APInt &High,
1240  const DataLayout &DL) const {
1241  // FIXME: Using the pointer type doesn't seem ideal.
1242  uint64_t BW = DL.getIndexSizeInBits(0u);
1243  uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1;
1244  return Range <= BW;
1245  }
1246 
1247  /// Return true if lowering to a jump table is suitable for a set of case
1248  /// clusters which may contain \p NumCases cases, \p Range range of values.
1249  virtual bool isSuitableForJumpTable(const SwitchInst *SI, uint64_t NumCases,
1250  uint64_t Range, ProfileSummaryInfo *PSI,
1251  BlockFrequencyInfo *BFI) const;
1252 
1253  /// Returns preferred type for switch condition.
1255  EVT ConditionVT) const;
1256 
1257  /// Return true if lowering to a bit test is suitable for a set of case
1258  /// clusters which contains \p NumDests unique destinations, \p Low and
1259  /// \p High as its lowest and highest case values, and expects \p NumCmps
1260  /// case value comparisons. Check if the number of destinations, comparison
1261  /// metric, and range are all suitable.
1262  bool isSuitableForBitTests(unsigned NumDests, unsigned NumCmps,
1263  const APInt &Low, const APInt &High,
1264  const DataLayout &DL) const {
1265  // FIXME: I don't think NumCmps is the correct metric: a single case and a
1266  // range of cases both require only one branch to lower. Just looking at the
1267  // number of clusters and destinations should be enough to decide whether to
1268  // build bit tests.
1269 
1270  // To lower a range with bit tests, the range must fit the bitwidth of a
1271  // machine word.
1272  if (!rangeFitsInWord(Low, High, DL))
1273  return false;
1274 
1275  // Decide whether it's profitable to lower this range with bit tests. Each
1276  // destination requires a bit test and branch, and there is an overall range
1277  // check branch. For a small number of clusters, separate comparisons might
1278  // be cheaper, and for many destinations, splitting the range might be
1279  // better.
1280  return (NumDests == 1 && NumCmps >= 3) || (NumDests == 2 && NumCmps >= 5) ||
1281  (NumDests == 3 && NumCmps >= 6);
1282  }
1283 
1284  /// Return true if the specified operation is illegal on this target or
1285  /// unlikely to be made legal with custom lowering. This is used to help guide
1286  /// high-level lowering decisions.
1287  bool isOperationExpand(unsigned Op, EVT VT) const {
1288  return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
1289  }
1290 
1291  /// Return true if the specified operation is legal on this target.
1292  bool isOperationLegal(unsigned Op, EVT VT) const {
1293  return (VT == MVT::Other || isTypeLegal(VT)) &&
1294  getOperationAction(Op, VT) == Legal;
1295  }
1296 
1297  /// Return how this load with extension should be treated: either it is legal,
1298  /// needs to be promoted to a larger size, needs to be expanded to some other
1299  /// code sequence, or the target has a custom expander for it.
1300  LegalizeAction getLoadExtAction(unsigned ExtType, EVT ValVT,
1301  EVT MemVT) const {
1302  if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
1303  unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
1304  unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
1305  assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValI < MVT::VALUETYPE_SIZE &&
1306  MemI < MVT::VALUETYPE_SIZE && "Table isn't big enough!");
1307  unsigned Shift = 4 * ExtType;
1308  return (LegalizeAction)((LoadExtActions[ValI][MemI] >> Shift) & 0xf);
1309  }
1310 
1311  /// Return true if the specified load with extension is legal on this target.
1312  bool isLoadExtLegal(unsigned ExtType, EVT ValVT, EVT MemVT) const {
1313  return getLoadExtAction(ExtType, ValVT, MemVT) == Legal;
1314  }
1315 
1316  /// Return true if the specified load with extension is legal or custom
1317  /// on this target.
1318  bool isLoadExtLegalOrCustom(unsigned ExtType, EVT ValVT, EVT MemVT) const {
1319  return getLoadExtAction(ExtType, ValVT, MemVT) == Legal ||
1320  getLoadExtAction(ExtType, ValVT, MemVT) == Custom;
1321  }
1322 
1323  /// Return how this store with truncation should be treated: either it is
1324  /// legal, needs to be promoted to a larger size, needs to be expanded to some
1325  /// other code sequence, or the target has a custom expander for it.
1327  if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
1328  unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
1329  unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
1330  assert(ValI < MVT::VALUETYPE_SIZE && MemI < MVT::VALUETYPE_SIZE &&
1331  "Table isn't big enough!");
1332  return TruncStoreActions[ValI][MemI];
1333  }
1334 
1335  /// Return true if the specified store with truncation is legal on this
1336  /// target.
1337  bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
1338  return isTypeLegal(ValVT) && getTruncStoreAction(ValVT, MemVT) == Legal;
1339  }
1340 
1341  /// Return true if the specified store with truncation has solution on this
1342  /// target.
1343  bool isTruncStoreLegalOrCustom(EVT ValVT, EVT MemVT) const {
1344  return isTypeLegal(ValVT) &&
1345  (getTruncStoreAction(ValVT, MemVT) == Legal ||
1346  getTruncStoreAction(ValVT, MemVT) == Custom);
1347  }
1348 
1349  virtual bool canCombineTruncStore(EVT ValVT, EVT MemVT,
1350  bool LegalOnly) const {
1351  if (LegalOnly)
1352  return isTruncStoreLegal(ValVT, MemVT);
1353 
1354  return isTruncStoreLegalOrCustom(ValVT, MemVT);
1355  }
1356 
1357  /// Return how the indexed load should be treated: either it is legal, needs
1358  /// to be promoted to a larger size, needs to be expanded to some other code
1359  /// sequence, or the target has a custom expander for it.
1360  LegalizeAction getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
1361  return getIndexedModeAction(IdxMode, VT, IMAB_Load);
1362  }
1363 
1364  /// Return true if the specified indexed load is legal on this target.
1365  bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
1366  return VT.isSimple() &&
1367  (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
1368  getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
1369  }
1370 
1371  /// Return how the indexed store should be treated: either it is legal, needs
1372  /// to be promoted to a larger size, needs to be expanded to some other code
1373  /// sequence, or the target has a custom expander for it.
1374  LegalizeAction getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
1375  return getIndexedModeAction(IdxMode, VT, IMAB_Store);
1376  }
1377 
1378  /// Return true if the specified indexed load is legal on this target.
1379  bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
1380  return VT.isSimple() &&
1381  (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
1382  getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
1383  }
1384 
1385  /// Return how the indexed load should be treated: either it is legal, needs
1386  /// to be promoted to a larger size, needs to be expanded to some other code
1387  /// sequence, or the target has a custom expander for it.
1388  LegalizeAction getIndexedMaskedLoadAction(unsigned IdxMode, MVT VT) const {
1389  return getIndexedModeAction(IdxMode, VT, IMAB_MaskedLoad);
1390  }
1391 
1392  /// Return true if the specified indexed load is legal on this target.
1393  bool isIndexedMaskedLoadLegal(unsigned IdxMode, EVT VT) const {
1394  return VT.isSimple() &&
1395  (getIndexedMaskedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
1396  getIndexedMaskedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
1397  }
1398 
1399  /// Return how the indexed store should be treated: either it is legal, needs
1400  /// to be promoted to a larger size, needs to be expanded to some other code
1401  /// sequence, or the target has a custom expander for it.
1402  LegalizeAction getIndexedMaskedStoreAction(unsigned IdxMode, MVT VT) const {
1403  return getIndexedModeAction(IdxMode, VT, IMAB_MaskedStore);
1404  }
1405 
1406  /// Return true if the specified indexed load is legal on this target.
1407  bool isIndexedMaskedStoreLegal(unsigned IdxMode, EVT VT) const {
1408  return VT.isSimple() &&
1409  (getIndexedMaskedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
1410  getIndexedMaskedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
1411  }
1412 
1413  /// Returns true if the index type for a masked gather/scatter requires
1414  /// extending
1415  virtual bool shouldExtendGSIndex(EVT VT, EVT &EltTy) const { return false; }
1416 
1417  // Returns true if VT is a legal index type for masked gathers/scatters
1418  // on this target
1419  virtual bool shouldRemoveExtendFromGSIndex(EVT IndexVT, EVT DataVT) const {
1420  return false;
1421  }
1422 
1423  // Return true if the target supports a scatter/gather instruction with
1424  // indices which are scaled by the particular value. Note that all targets
1425  // must by definition support scale of 1.
1427  uint64_t ElemSize) const {
1428  // MGATHER/MSCATTER are only required to support scaling by one or by the
1429  // element size.
1430  if (Scale != ElemSize && Scale != 1)
1431  return false;
1432  return true;
1433  }
1434 
1435  /// Return how the condition code should be treated: either it is legal, needs
1436  /// to be expanded to some other code sequence, or the target has a custom
1437  /// expander for it.
1440  assert((unsigned)CC < std::size(CondCodeActions) &&
1441  ((unsigned)VT.SimpleTy >> 3) < std::size(CondCodeActions[0]) &&
1442  "Table isn't big enough!");
1443  // See setCondCodeAction for how this is encoded.
1444  uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
1445  uint32_t Value = CondCodeActions[CC][VT.SimpleTy >> 3];
1446  LegalizeAction Action = (LegalizeAction) ((Value >> Shift) & 0xF);
1447  assert(Action != Promote && "Can't promote condition code!");
1448  return Action;
1449  }
1450 
1451  /// Return true if the specified condition code is legal on this target.
1453  return getCondCodeAction(CC, VT) == Legal;
1454  }
1455 
1456  /// Return true if the specified condition code is legal or custom on this
1457  /// target.
1459  return getCondCodeAction(CC, VT) == Legal ||
1460  getCondCodeAction(CC, VT) == Custom;
1461  }
1462 
1463  /// If the action for this operation is to promote, this method returns the
1464  /// ValueType to promote to.
1465  MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
1466  assert(getOperationAction(Op, VT) == Promote &&
1467  "This operation isn't promoted!");
1468 
1469  // See if this has an explicit type specified.
1470  std::map<std::pair<unsigned, MVT::SimpleValueType>,
1472  PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
1473  if (PTTI != PromoteToType.end()) return PTTI->second;
1474 
1475  assert((VT.isInteger() || VT.isFloatingPoint()) &&
1476  "Cannot autopromote this type, add it with AddPromotedToType.");
1477 
1478  MVT NVT = VT;
1479  do {
1480  NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
1481  assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
1482  "Didn't find type to promote to!");
1483  } while (!isTypeLegal(NVT) ||
1484  getOperationAction(Op, NVT) == Promote);
1485  return NVT;
1486  }
1487 
1489  bool AllowUnknown = false) const {
1490  return getValueType(DL, Ty, AllowUnknown);
1491  }
1492 
1493  /// Return the EVT corresponding to this LLVM type. This is fixed by the LLVM
1494  /// operations except for the pointer size. If AllowUnknown is true, this
1495  /// will return MVT::Other for types with no EVT counterpart (e.g. structs),
1496  /// otherwise it will assert.
1498  bool AllowUnknown = false) const {
1499  // Lower scalar pointers to native pointer types.
1500  if (auto *PTy = dyn_cast<PointerType>(Ty))
1501  return getPointerTy(DL, PTy->getAddressSpace());
1502 
1503  if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1504  Type *EltTy = VTy->getElementType();
1505  // Lower vectors of pointers to native pointer types.
1506  if (auto *PTy = dyn_cast<PointerType>(EltTy)) {
1507  EVT PointerTy(getPointerTy(DL, PTy->getAddressSpace()));
1508  EltTy = PointerTy.getTypeForEVT(Ty->getContext());
1509  }
1510  return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(EltTy, false),
1511  VTy->getElementCount());
1512  }
1513 
1514  return EVT::getEVT(Ty, AllowUnknown);
1515  }
1516 
1518  bool AllowUnknown = false) const {
1519  // Lower scalar pointers to native pointer types.
1520  if (PointerType *PTy = dyn_cast<PointerType>(Ty))
1521  return getPointerMemTy(DL, PTy->getAddressSpace());
1522  else if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1523  Type *Elm = VTy->getElementType();
1524  if (PointerType *PT = dyn_cast<PointerType>(Elm)) {
1525  EVT PointerTy(getPointerMemTy(DL, PT->getAddressSpace()));
1526  Elm = PointerTy.getTypeForEVT(Ty->getContext());
1527  }
1528  return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
1529  VTy->getElementCount());
1530  }
1531 
1532  return getValueType(DL, Ty, AllowUnknown);
1533  }
1534 
1535 
1536  /// Return the MVT corresponding to this LLVM type. See getValueType.
1538  bool AllowUnknown = false) const {
1539  return getValueType(DL, Ty, AllowUnknown).getSimpleVT();
1540  }
1541 
1542  /// Return the desired alignment for ByVal or InAlloca aggregate function
1543  /// arguments in the caller parameter area. This is the actual alignment, not
1544  /// its logarithm.
1545  virtual uint64_t getByValTypeAlignment(Type *Ty, const DataLayout &DL) const;
1546 
1547  /// Return the type of registers that this ValueType will eventually require.
1549  assert((unsigned)VT.SimpleTy < std::size(RegisterTypeForVT));
1550  return RegisterTypeForVT[VT.SimpleTy];
1551  }
1552 
1553  /// Return the type of registers that this ValueType will eventually require.
1555  if (VT.isSimple()) {
1556  assert((unsigned)VT.getSimpleVT().SimpleTy <
1557  std::size(RegisterTypeForVT));
1558  return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
1559  }
1560  if (VT.isVector()) {
1561  EVT VT1;
1562  MVT RegisterVT;
1563  unsigned NumIntermediates;
1564  (void)getVectorTypeBreakdown(Context, VT, VT1,
1565  NumIntermediates, RegisterVT);
1566  return RegisterVT;
1567  }
1568  if (VT.isInteger()) {
1570  }
1571  llvm_unreachable("Unsupported extended type!");
1572  }
1573 
1574  /// Return the number of registers that this ValueType will eventually
1575  /// require.
1576  ///
1577  /// This is one for any types promoted to live in larger registers, but may be
1578  /// more than one for types (like i64) that are split into pieces. For types
1579  /// like i140, which are first promoted then expanded, it is the number of
1580  /// registers needed to hold all the bits of the original type. For an i140
1581  /// on a 32 bit machine this means 5 registers.
1582  ///
1583  /// RegisterVT may be passed as a way to override the default settings, for
1584  /// instance with i128 inline assembly operands on SystemZ.
1585  virtual unsigned
1587  std::optional<MVT> RegisterVT = std::nullopt) const {
1588  if (VT.isSimple()) {
1589  assert((unsigned)VT.getSimpleVT().SimpleTy <
1590  std::size(NumRegistersForVT));
1591  return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
1592  }
1593  if (VT.isVector()) {
1594  EVT VT1;
1595  MVT VT2;
1596  unsigned NumIntermediates;
1597  return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
1598  }
1599  if (VT.isInteger()) {
1600  unsigned BitWidth = VT.getSizeInBits();
1601  unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
1602  return (BitWidth + RegWidth - 1) / RegWidth;
1603  }
1604  llvm_unreachable("Unsupported extended type!");
1605  }
1606 
1607  /// Certain combinations of ABIs, Targets and features require that types
1608  /// are legal for some operations and not for other operations.
1609  /// For MIPS all vector types must be passed through the integer register set.
1611  CallingConv::ID CC, EVT VT) const {
1612  return getRegisterType(Context, VT);
1613  }
1614 
1615  /// Certain targets require unusual breakdowns of certain types. For MIPS,
1616  /// this occurs when a vector type is used, as vector are passed through the
1617  /// integer register set.
1620  EVT VT) const {
1621  return getNumRegisters(Context, VT);
1622  }
1623 
1624  /// Certain targets have context sensitive alignment requirements, where one
1625  /// type has the alignment requirement of another type.
1627  const DataLayout &DL) const {
1628  return DL.getABITypeAlign(ArgTy);
1629  }
1630 
1631  /// If true, then instruction selection should seek to shrink the FP constant
1632  /// of the specified type to a smaller type in order to save space and / or
1633  /// reduce runtime.
1634  virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
1635 
1636  /// Return true if it is profitable to reduce a load to a smaller type.
1637  /// Example: (i16 (trunc (i32 (load x))) -> i16 load x
1639  EVT NewVT) const {
1640  // By default, assume that it is cheaper to extract a subvector from a wide
1641  // vector load rather than creating multiple narrow vector loads.
1642  if (NewVT.isVector() && !Load->hasOneUse())
1643  return false;
1644 
1645  return true;
1646  }
1647 
1648  /// When splitting a value of the specified type into parts, does the Lo
1649  /// or Hi part come first? This usually follows the endianness, except
1650  /// for ppcf128, where the Hi part always comes first.
1651  bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const {
1652  return DL.isBigEndian() || VT == MVT::ppcf128;
1653  }
1654 
1655  /// If true, the target has custom DAG combine transformations that it can
1656  /// perform for the specified node.
1658  assert(unsigned(NT >> 3) < std::size(TargetDAGCombineArray));
1659  return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
1660  }
1661 
1662  unsigned getGatherAllAliasesMaxDepth() const {
1663  return GatherAllAliasesMaxDepth;
1664  }
1665 
1666  /// Returns the size of the platform's va_list object.
1667  virtual unsigned getVaListSizeInBits(const DataLayout &DL) const {
1668  return getPointerTy(DL).getSizeInBits();
1669  }
1670 
1671  /// Get maximum # of store operations permitted for llvm.memset
1672  ///
1673  /// This function returns the maximum number of store operations permitted
1674  /// to replace a call to llvm.memset. The value is set by the target at the
1675  /// performance threshold for such a replacement. If OptSize is true,
1676  /// return the limit for functions that have OptSize attribute.
1677  unsigned getMaxStoresPerMemset(bool OptSize) const {
1678  return OptSize ? MaxStoresPerMemsetOptSize : MaxStoresPerMemset;
1679  }
1680 
1681  /// Get maximum # of store operations permitted for llvm.memcpy
1682  ///
1683  /// This function returns the maximum number of store operations permitted
1684  /// to replace a call to llvm.memcpy. The value is set by the target at the
1685  /// performance threshold for such a replacement. If OptSize is true,
1686  /// return the limit for functions that have OptSize attribute.
1687  unsigned getMaxStoresPerMemcpy(bool OptSize) const {
1688  return OptSize ? MaxStoresPerMemcpyOptSize : MaxStoresPerMemcpy;
1689  }
1690 
1691  /// \brief Get maximum # of store operations to be glued together
1692  ///
1693  /// This function returns the maximum number of store operations permitted
1694  /// to glue together during lowering of llvm.memcpy. The value is set by
1695  // the target at the performance threshold for such a replacement.
1696  virtual unsigned getMaxGluedStoresPerMemcpy() const {
1697  return MaxGluedStoresPerMemcpy;
1698  }
1699 
1700  /// Get maximum # of load operations permitted for memcmp
1701  ///
1702  /// This function returns the maximum number of load operations permitted
1703  /// to replace a call to memcmp. The value is set by the target at the
1704  /// performance threshold for such a replacement. If OptSize is true,
1705  /// return the limit for functions that have OptSize attribute.
1706  unsigned getMaxExpandSizeMemcmp(bool OptSize) const {
1707  return OptSize ? MaxLoadsPerMemcmpOptSize : MaxLoadsPerMemcmp;
1708  }
1709 
1710  /// Get maximum # of store operations permitted for llvm.memmove
1711  ///
1712  /// This function returns the maximum number of store operations permitted
1713  /// to replace a call to llvm.memmove. The value is set by the target at the
1714  /// performance threshold for such a replacement. If OptSize is true,
1715  /// return the limit for functions that have OptSize attribute.
1716  unsigned getMaxStoresPerMemmove(bool OptSize) const {
1718  }
1719 
1720  /// Determine if the target supports unaligned memory accesses.
1721  ///
1722  /// This function returns true if the target allows unaligned memory accesses
1723  /// of the specified type in the given address space. If true, it also returns
1724  /// a relative speed of the unaligned memory access in the last argument by
1725  /// reference. The higher the speed number the faster the operation comparing
1726  /// to a number returned by another such call. This is used, for example, in
1727  /// situations where an array copy/move/set is converted to a sequence of
1728  /// store operations. Its use helps to ensure that such replacements don't
1729  /// generate code that causes an alignment error (trap) on the target machine.
1731  EVT, unsigned AddrSpace = 0, Align Alignment = Align(1),
1733  unsigned * /*Fast*/ = nullptr) const {
1734  return false;
1735  }
1736 
1737  /// LLT handling variant.
1739  LLT, unsigned AddrSpace = 0, Align Alignment = Align(1),
1741  unsigned * /*Fast*/ = nullptr) const {
1742  return false;
1743  }
1744 
1745  /// This function returns true if the memory access is aligned or if the
1746  /// target allows this specific unaligned memory access. If the access is
1747  /// allowed, the optional final parameter returns a relative speed of the
1748  /// access (as defined by the target).
1750  LLVMContext &Context, const DataLayout &DL, EVT VT,
1751  unsigned AddrSpace = 0, Align Alignment = Align(1),
1753  unsigned *Fast = nullptr) const;
1754 
1755  /// Return true if the memory access of this type is aligned or if the target
1756  /// allows this specific unaligned access for the given MachineMemOperand.
1757  /// If the access is allowed, the optional final parameter returns a relative
1758  /// speed of the access (as defined by the target).
1760  const DataLayout &DL, EVT VT,
1761  const MachineMemOperand &MMO,
1762  unsigned *Fast = nullptr) const;
1763 
1764  /// Return true if the target supports a memory access of this type for the
1765  /// given address space and alignment. If the access is allowed, the optional
1766  /// final parameter returns the relative speed of the access (as defined by
1767  /// the target).
1768  virtual bool
1770  unsigned AddrSpace = 0, Align Alignment = Align(1),
1772  unsigned *Fast = nullptr) const;
1773 
1774  /// Return true if the target supports a memory access of this type for the
1775  /// given MachineMemOperand. If the access is allowed, the optional
1776  /// final parameter returns the relative access speed (as defined by the
1777  /// target).
1779  const MachineMemOperand &MMO,
1780  unsigned *Fast = nullptr) const;
1781 
1782  /// LLT handling variant.
1784  const MachineMemOperand &MMO,
1785  unsigned *Fast = nullptr) const;
1786 
1787  /// Returns the target specific optimal type for load and store operations as
1788  /// a result of memset, memcpy, and memmove lowering.
1789  /// It returns EVT::Other if the type should be determined using generic
1790  /// target-independent logic.
1791  virtual EVT
1793  const AttributeList & /*FuncAttributes*/) const {
1794  return MVT::Other;
1795  }
1796 
1797  /// LLT returning variant.
1798  virtual LLT
1800  const AttributeList & /*FuncAttributes*/) const {
1801  return LLT();
1802  }
1803 
1804  /// Returns true if it's safe to use load / store of the specified type to
1805  /// expand memcpy / memset inline.
1806  ///
1807  /// This is mostly true for all types except for some special cases. For
1808  /// example, on X86 targets without SSE2 f64 load / store are done with fldl /
1809  /// fstpl which also does type conversion. Note the specified type doesn't
1810  /// have to be legal as the hook is used before type legalization.
1811  virtual bool isSafeMemOpType(MVT /*VT*/) const { return true; }
1812 
1813  /// Return lower limit for number of blocks in a jump table.
1814  virtual unsigned getMinimumJumpTableEntries() const;
1815 
1816  /// Return lower limit of the density in a jump table.
1817  unsigned getMinimumJumpTableDensity(bool OptForSize) const;
1818 
1819  /// Return upper limit for number of entries in a jump table.
1820  /// Zero if no limit.
1821  unsigned getMaximumJumpTableSize() const;
1822 
1823  virtual bool isJumpTableRelative() const;
1824 
1825  /// If a physical register, this specifies the register that
1826  /// llvm.savestack/llvm.restorestack should save and restore.
1828  return StackPointerRegisterToSaveRestore;
1829  }
1830 
1831  /// If a physical register, this returns the register that receives the
1832  /// exception address on entry to an EH pad.
1833  virtual Register
1834  getExceptionPointerRegister(const Constant *PersonalityFn) const {
1835  return Register();
1836  }
1837 
1838  /// If a physical register, this returns the register that receives the
1839  /// exception typeid on entry to a landing pad.
1840  virtual Register
1841  getExceptionSelectorRegister(const Constant *PersonalityFn) const {
1842  return Register();
1843  }
1844 
1845  virtual bool needsFixedCatchObjects() const {
1846  report_fatal_error("Funclet EH is not implemented for this target");
1847  }
1848 
1849  /// Return the minimum stack alignment of an argument.
1851  return MinStackArgumentAlignment;
1852  }
1853 
1854  /// Return the minimum function alignment.
1855  Align getMinFunctionAlignment() const { return MinFunctionAlignment; }
1856 
1857  /// Return the preferred function alignment.
1858  Align getPrefFunctionAlignment() const { return PrefFunctionAlignment; }
1859 
1860  /// Return the preferred loop alignment.
1861  virtual Align getPrefLoopAlignment(MachineLoop *ML = nullptr) const;
1862 
1863  /// Return the maximum amount of bytes allowed to be emitted when padding for
1864  /// alignment
1865  virtual unsigned
1867 
1868  /// Should loops be aligned even when the function is marked OptSize (but not
1869  /// MinSize).
1870  virtual bool alignLoopsWithOptSize() const { return false; }
1871 
1872  /// If the target has a standard location for the stack protector guard,
1873  /// returns the address of that location. Otherwise, returns nullptr.
1874  /// DEPRECATED: please override useLoadStackGuardNode and customize
1875  /// LOAD_STACK_GUARD, or customize \@llvm.stackguard().
1876  virtual Value *getIRStackGuard(IRBuilderBase &IRB) const;
1877 
1878  /// Inserts necessary declarations for SSP (stack protection) purpose.
1879  /// Should be used only when getIRStackGuard returns nullptr.
1880  virtual void insertSSPDeclarations(Module &M) const;
1881 
1882  /// Return the variable that's previously inserted by insertSSPDeclarations,
1883  /// if any, otherwise return nullptr. Should be used only when
1884  /// getIRStackGuard returns nullptr.
1885  virtual Value *getSDagStackGuard(const Module &M) const;
1886 
1887  /// If this function returns true, stack protection checks should XOR the
1888  /// frame pointer (or whichever pointer is used to address locals) into the
1889  /// stack guard value before checking it. getIRStackGuard must return nullptr
1890  /// if this returns true.
1891  virtual bool useStackGuardXorFP() const { return false; }
1892 
1893  /// If the target has a standard stack protection check function that
1894  /// performs validation and error handling, returns the function. Otherwise,
1895  /// returns nullptr. Must be previously inserted by insertSSPDeclarations.
1896  /// Should be used only when getIRStackGuard returns nullptr.
1897  virtual Function *getSSPStackGuardCheck(const Module &M) const;
1898 
1899  /// \returns true if a constant G_UBFX is legal on the target.
1900  virtual bool isConstantUnsignedBitfieldExtractLegal(unsigned Opc, LLT Ty1,
1901  LLT Ty2) const {
1902  return false;
1903  }
1904 
1905 protected:
1907  bool UseTLS) const;
1908 
1909 public:
1910  /// Returns the target-specific address of the unsafe stack pointer.
1911  virtual Value *getSafeStackPointerLocation(IRBuilderBase &IRB) const;
1912 
1913  /// Returns the name of the symbol used to emit stack probes or the empty
1914  /// string if not applicable.
1915  virtual bool hasStackProbeSymbol(const MachineFunction &MF) const { return false; }
1916 
1917  virtual bool hasInlineStackProbe(const MachineFunction &MF) const { return false; }
1918 
1920  return "";
1921  }
1922 
1923  /// Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g. we
1924  /// are happy to sink it into basic blocks. A cast may be free, but not
1925  /// necessarily a no-op. e.g. a free truncate from a 64-bit to 32-bit pointer.
1926  virtual bool isFreeAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const;
1927 
1928  /// Return true if the pointer arguments to CI should be aligned by aligning
1929  /// the object whose address is being passed. If so then MinSize is set to the
1930  /// minimum size the object must be to be aligned and PrefAlign is set to the
1931  /// preferred alignment.
1932  virtual bool shouldAlignPointerArgs(CallInst * /*CI*/, unsigned & /*MinSize*/,
1933  Align & /*PrefAlign*/) const {
1934  return false;
1935  }
1936 
1937  //===--------------------------------------------------------------------===//
1938  /// \name Helpers for TargetTransformInfo implementations
1939  /// @{
1940 
1941  /// Get the ISD node that corresponds to the Instruction class opcode.
1942  int InstructionOpcodeToISD(unsigned Opcode) const;
1943 
1944  /// @}
1945 
1946  //===--------------------------------------------------------------------===//
1947  /// \name Helpers for atomic expansion.
1948  /// @{
1949 
1950  /// Returns the maximum atomic operation size (in bits) supported by
1951  /// the backend. Atomic operations greater than this size (as well
1952  /// as ones that are not naturally aligned), will be expanded by
1953  /// AtomicExpandPass into an __atomic_* library call.
1955  return MaxAtomicSizeInBitsSupported;
1956  }
1957 
1958  /// Returns the size in bits of the maximum div/rem the backend supports.
1959  /// Larger operations will be expanded by ExpandLargeDivRem.
1961  return MaxDivRemBitWidthSupported;
1962  }
1963 
1964  /// Returns the size in bits of the maximum larget fp convert the backend
1965  /// supports. Larger operations will be expanded by ExpandLargeFPConvert.
1967  return MaxLargeFPConvertBitWidthSupported;
1968  }
1969 
1970  /// Returns the size of the smallest cmpxchg or ll/sc instruction
1971  /// the backend supports. Any smaller operations are widened in
1972  /// AtomicExpandPass.
1973  ///
1974  /// Note that *unlike* operations above the maximum size, atomic ops
1975  /// are still natively supported below the minimum; they just
1976  /// require a more complex expansion.
1977  unsigned getMinCmpXchgSizeInBits() const { return MinCmpXchgSizeInBits; }
1978 
1979  /// Whether the target supports unaligned atomic operations.
1980  bool supportsUnalignedAtomics() const { return SupportsUnalignedAtomics; }
1981 
1982  /// Whether AtomicExpandPass should automatically insert fences and reduce
1983  /// ordering for this atomic. This should be true for most architectures with
1984  /// weak memory ordering. Defaults to false.
1985  virtual bool shouldInsertFencesForAtomic(const Instruction *I) const {
1986  return false;
1987  }
1988 
1989  /// Perform a load-linked operation on Addr, returning a "Value *" with the
1990  /// corresponding pointee type. This may entail some non-trivial operations to
1991  /// truncate or reconstruct types that will be illegal in the backend. See
1992  /// ARMISelLowering for an example implementation.
1994  Value *Addr, AtomicOrdering Ord) const {
1995  llvm_unreachable("Load linked unimplemented on this target");
1996  }
1997 
1998  /// Perform a store-conditional operation to Addr. Return the status of the
1999  /// store. This should be 0 if the store succeeded, non-zero otherwise.
2001  Value *Addr, AtomicOrdering Ord) const {
2002  llvm_unreachable("Store conditional unimplemented on this target");
2003  }
2004 
2005  /// Perform a masked atomicrmw using a target-specific intrinsic. This
2006  /// represents the core LL/SC loop which will be lowered at a late stage by
2007  /// the backend. The target-specific intrinsic returns the loaded value and
2008  /// is not responsible for masking and shifting the result.
2010  AtomicRMWInst *AI,
2011  Value *AlignedAddr, Value *Incr,
2012  Value *Mask, Value *ShiftAmt,
2013  AtomicOrdering Ord) const {
2014  llvm_unreachable("Masked atomicrmw expansion unimplemented on this target");
2015  }
2016 
2017  /// Perform a atomicrmw expansion using a target-specific way. This is
2018  /// expected to be called when masked atomicrmw and bit test atomicrmw don't
2019  /// work, and the target supports another way to lower atomicrmw.
2020  virtual void emitExpandAtomicRMW(AtomicRMWInst *AI) const {
2022  "Generic atomicrmw expansion unimplemented on this target");
2023  }
2024 
2025  /// Perform a bit test atomicrmw using a target-specific intrinsic. This
2026  /// represents the combined bit test intrinsic which will be lowered at a late
2027  /// stage by the backend.
2030  "Bit test atomicrmw expansion unimplemented on this target");
2031  }
2032 
2033  /// Perform a atomicrmw which the result is only used by comparison, using a
2034  /// target-specific intrinsic. This represents the combined atomic and compare
2035  /// intrinsic which will be lowered at a late stage by the backend.
2038  "Compare arith atomicrmw expansion unimplemented on this target");
2039  }
2040 
2041  /// Perform a masked cmpxchg using a target-specific intrinsic. This
2042  /// represents the core LL/SC loop which will be lowered at a late stage by
2043  /// the backend. The target-specific intrinsic returns the loaded value and
2044  /// is not responsible for masking and shifting the result.
2046  IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
2047  Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
2048  llvm_unreachable("Masked cmpxchg expansion unimplemented on this target");
2049  }
2050 
2051  /// Inserts in the IR a target-specific intrinsic specifying a fence.
2052  /// It is called by AtomicExpandPass before expanding an
2053  /// AtomicRMW/AtomicCmpXchg/AtomicStore/AtomicLoad
2054  /// if shouldInsertFencesForAtomic returns true.
2055  ///
2056  /// Inst is the original atomic instruction, prior to other expansions that
2057  /// may be performed.
2058  ///
2059  /// This function should either return a nullptr, or a pointer to an IR-level
2060  /// Instruction*. Even complex fence sequences can be represented by a
2061  /// single Instruction* through an intrinsic to be lowered later.
2062  /// Backends should override this method to produce target-specific intrinsic
2063  /// for their fences.
2064  /// FIXME: Please note that the default implementation here in terms of
2065  /// IR-level fences exists for historical/compatibility reasons and is
2066  /// *unsound* ! Fences cannot, in general, be used to restore sequential
2067  /// consistency. For example, consider the following example:
2068  /// atomic<int> x = y = 0;
2069  /// int r1, r2, r3, r4;
2070  /// Thread 0:
2071  /// x.store(1);
2072  /// Thread 1:
2073  /// y.store(1);
2074  /// Thread 2:
2075  /// r1 = x.load();
2076  /// r2 = y.load();
2077  /// Thread 3:
2078  /// r3 = y.load();
2079  /// r4 = x.load();
2080  /// r1 = r3 = 1 and r2 = r4 = 0 is impossible as long as the accesses are all
2081  /// seq_cst. But if they are lowered to monotonic accesses, no amount of
2082  /// IR-level fences can prevent it.
2083  /// @{
2085  Instruction *Inst,
2086  AtomicOrdering Ord) const;
2087 
2089  Instruction *Inst,
2090  AtomicOrdering Ord) const;
2091  /// @}
2092 
2093  // Emits code that executes when the comparison result in the ll/sc
2094  // expansion of a cmpxchg instruction is such that the store-conditional will
2095  // not execute. This makes it possible to balance out the load-linked with
2096  // a dedicated instruction, if desired.
2097  // E.g., on ARM, if ldrex isn't followed by strex, the exclusive monitor would
2098  // be unnecessarily held, except if clrex, inserted by this hook, is executed.
2100 
2101  /// Returns true if arguments should be sign-extended in lib calls.
2102  virtual bool shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
2103  return IsSigned;
2104  }
2105 
2106  /// Returns true if arguments should be extended in lib calls.
2107  virtual bool shouldExtendTypeInLibCall(EVT Type) const {
2108  return true;
2109  }
2110 
2111  /// Returns how the given (atomic) load should be expanded by the
2112  /// IR-level AtomicExpand pass.
2115  }
2116 
2117  /// Returns how the given (atomic) load should be cast by the IR-level
2118  /// AtomicExpand pass.
2120  if (LI->getType()->isFloatingPointTy())
2123  }
2124 
2125  /// Returns how the given (atomic) store should be expanded by the IR-level
2126  /// AtomicExpand pass into. For instance AtomicExpansionKind::Expand will try
2127  /// to use an atomicrmw xchg.
2130  }
2131 
2132  /// Returns how the given (atomic) store should be cast by the IR-level
2133  /// AtomicExpand pass into. For instance AtomicExpansionKind::CastToInteger
2134  /// will try to cast the operands to integer values.
2136  if (SI->getValueOperand()->getType()->isFloatingPointTy())
2139  }
2140 
2141  /// Returns how the given atomic cmpxchg should be expanded by the IR-level
2142  /// AtomicExpand pass.
2143  virtual AtomicExpansionKind
2146  }
2147 
2148  /// Returns how the IR-level AtomicExpand pass should expand the given
2149  /// AtomicRMW, if at all. Default is to never expand.
2151  return RMW->isFloatingPointOperation() ?
2153  }
2154 
2155  /// Returns how the given atomic atomicrmw should be cast by the IR-level
2156  /// AtomicExpand pass.
2157  virtual AtomicExpansionKind
2159  if (RMWI->getOperation() == AtomicRMWInst::Xchg &&
2160  (RMWI->getValOperand()->getType()->isFloatingPointTy() ||
2161  RMWI->getValOperand()->getType()->isPointerTy()))
2163 
2165  }
2166 
2167  /// On some platforms, an AtomicRMW that never actually modifies the value
2168  /// (such as fetch_add of 0) can be turned into a fence followed by an
2169  /// atomic load. This may sound useless, but it makes it possible for the
2170  /// processor to keep the cacheline shared, dramatically improving
2171  /// performance. And such idempotent RMWs are useful for implementing some
2172  /// kinds of locks, see for example (justification + benchmarks):
2173  /// http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf
2174  /// This method tries doing that transformation, returning the atomic load if
2175  /// it succeeds, and nullptr otherwise.
2176  /// If shouldExpandAtomicLoadInIR returns true on that load, it will undergo
2177  /// another round of expansion.
2178  virtual LoadInst *
2180  return nullptr;
2181  }
2182 
2183  /// Returns how the platform's atomic operations are extended (ZERO_EXTEND,
2184  /// SIGN_EXTEND, or ANY_EXTEND).
2186  return ISD::ZERO_EXTEND;
2187  }
2188 
2189  /// Returns how the platform's atomic compare and swap expects its comparison
2190  /// value to be extended (ZERO_EXTEND, SIGN_EXTEND, or ANY_EXTEND). This is
2191  /// separate from getExtendForAtomicOps, which is concerned with the
2192  /// sign-extension of the instruction's output, whereas here we are concerned
2193  /// with the sign-extension of the input. For targets with compare-and-swap
2194  /// instructions (or sub-word comparisons in their LL/SC loop expansions),
2195  /// the input can be ANY_EXTEND, but the output will still have a specific
2196  /// extension.
2198  return ISD::ANY_EXTEND;
2199  }
2200 
2201  /// @}
2202 
2203  /// Returns true if we should normalize
2204  /// select(N0&N1, X, Y) => select(N0, select(N1, X, Y), Y) and
2205  /// select(N0|N1, X, Y) => select(N0, select(N1, X, Y, Y)) if it is likely
2206  /// that it saves us from materializing N0 and N1 in an integer register.
2207  /// Targets that are able to perform and/or on flags should return false here.
2209  EVT VT) const {
2210  // If a target has multiple condition registers, then it likely has logical
2211  // operations on those registers.
2213  return false;
2214  // Only do the transform if the value won't be split into multiple
2215  // registers.
2217  return Action != TypeExpandInteger && Action != TypeExpandFloat &&
2218  Action != TypeSplitVector;
2219  }
2220 
2221  virtual bool isProfitableToCombineMinNumMaxNum(EVT VT) const { return true; }
2222 
2223  /// Return true if a select of constants (select Cond, C1, C2) should be
2224  /// transformed into simple math ops with the condition value. For example:
2225  /// select Cond, C1, C1-1 --> add (zext Cond), C1-1
2226  virtual bool convertSelectOfConstantsToMath(EVT VT) const {
2227  return false;
2228  }
2229 
2230  /// Return true if it is profitable to transform an integer
2231  /// multiplication-by-constant into simpler operations like shifts and adds.
2232  /// This may be true if the target does not directly support the
2233  /// multiplication operation for the specified type or the sequence of simpler
2234  /// ops is faster than the multiply.
2236  EVT VT, SDValue C) const {
2237  return false;
2238  }
2239 
2240  /// Return true if it may be profitable to transform
2241  /// (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
2242  /// This may not be true if c1 and c2 can be represented as immediates but
2243  /// c1*c2 cannot, for example.
2244  /// The target should check if c1, c2 and c1*c2 can be represented as
2245  /// immediates, or have to be materialized into registers. If it is not sure
2246  /// about some cases, a default true can be returned to let the DAGCombiner
2247  /// decide.
2248  /// AddNode is (add x, c1), and ConstNode is c2.
2249  virtual bool isMulAddWithConstProfitable(SDValue AddNode,
2250  SDValue ConstNode) const {
2251  return true;
2252  }
2253 
2254  /// Return true if it is more correct/profitable to use strict FP_TO_INT
2255  /// conversion operations - canonicalizing the FP source value instead of
2256  /// converting all cases and then selecting based on value.
2257  /// This may be true if the target throws exceptions for out of bounds
2258  /// conversions or has fast FP CMOV.
2259  virtual bool shouldUseStrictFP_TO_INT(EVT FpVT, EVT IntVT,
2260  bool IsSigned) const {
2261  return false;
2262  }
2263 
2264  /// Return true if it is beneficial to expand an @llvm.powi.* intrinsic.
2265  /// If not optimizing for size, expanding @llvm.powi.* intrinsics is always
2266  /// considered beneficial.
2267  /// If optimizing for size, expansion is only considered beneficial for upto
2268  /// 5 multiplies and a divide (if the exponent is negative).
2269  bool isBeneficialToExpandPowI(int Exponent, bool OptForSize) const {
2270  if (Exponent < 0)
2271  Exponent = -Exponent;
2272  return !OptForSize ||
2273  (countPopulation((unsigned int)Exponent) + Log2_32(Exponent) < 7);
2274  }
2275 
2276  //===--------------------------------------------------------------------===//
2277  // TargetLowering Configuration Methods - These methods should be invoked by
2278  // the derived class constructor to configure this object for the target.
2279  //
2280 protected:
2281  /// Specify how the target extends the result of integer and floating point
2282  /// boolean values from i1 to a wider type. See getBooleanContents.
2284  BooleanContents = Ty;
2285  BooleanFloatContents = Ty;
2286  }
2287 
2288  /// Specify how the target extends the result of integer and floating point
2289  /// boolean values from i1 to a wider type. See getBooleanContents.
2291  BooleanContents = IntTy;
2292  BooleanFloatContents = FloatTy;
2293  }
2294 
2295  /// Specify how the target extends the result of a vector boolean value from a
2296  /// vector of i1 to a wider type. See getBooleanContents.
2298  BooleanVectorContents = Ty;
2299  }
2300 
2301  /// Specify the target scheduling preference.
2303  SchedPreferenceInfo = Pref;
2304  }
2305 
2306  /// Indicate the minimum number of blocks to generate jump tables.
2307  void setMinimumJumpTableEntries(unsigned Val);
2308 
2309  /// Indicate the maximum number of entries in jump tables.
2310  /// Set to zero to generate unlimited jump tables.
2311  void setMaximumJumpTableSize(unsigned);
2312 
2313  /// If set to a physical register, this specifies the register that
2314  /// llvm.savestack/llvm.restorestack should save and restore.
2316  StackPointerRegisterToSaveRestore = R;
2317  }
2318 
2319  /// Tells the code generator that the target has multiple (allocatable)
2320  /// condition registers that can be used to store the results of comparisons
2321  /// for use by selects and conditional branches. With multiple condition
2322  /// registers, the code generator will not aggressively sink comparisons into
2323  /// the blocks of their users.
2324  void setHasMultipleConditionRegisters(bool hasManyRegs = true) {
2325  HasMultipleConditionRegisters = hasManyRegs;
2326  }
2327 
2328  /// Tells the code generator that the target has BitExtract instructions.
2329  /// The code generator will aggressively sink "shift"s into the blocks of
2330  /// their users if the users will generate "and" instructions which can be
2331  /// combined with "shift" to BitExtract instructions.
2332  void setHasExtractBitsInsn(bool hasExtractInsn = true) {
2333  HasExtractBitsInsn = hasExtractInsn;
2334  }
2335 
2336  /// Tells the code generator not to expand logic operations on comparison
2337  /// predicates into separate sequences that increase the amount of flow
2338  /// control.
2339  void setJumpIsExpensive(bool isExpensive = true);
2340 
2341  /// Tells the code generator which bitwidths to bypass.
2342  void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
2343  BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
2344  }
2345 
2346  /// Add the specified register class as an available regclass for the
2347  /// specified value type. This indicates the selector can handle values of
2348  /// that class natively.
2350  assert((unsigned)VT.SimpleTy < std::size(RegClassForVT));
2351  RegClassForVT[VT.SimpleTy] = RC;
2352  }
2353 
2354  /// Return the largest legal super-reg register class of the register class
2355  /// for the specified type and its associated "cost".
2356  virtual std::pair<const TargetRegisterClass *, uint8_t>
2358 
2359  /// Once all of the register classes are added, this allows us to compute
2360  /// derived properties we expose.
2362 
2363  /// Indicate that the specified operation does not work with the specified
2364  /// type and indicate what to do about it. Note that VT may refer to either
2365  /// the type of a result or that of an operand of Op.
2366  void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action) {
2367  assert(Op < std::size(OpActions[0]) && "Table isn't big enough!");
2368  OpActions[(unsigned)VT.SimpleTy][Op] = Action;
2369  }
2371  LegalizeAction Action) {
2372  for (auto Op : Ops)
2373  setOperationAction(Op, VT, Action);
2374  }
2376  LegalizeAction Action) {
2377  for (auto VT : VTs)
2378  setOperationAction(Ops, VT, Action);
2379  }
2380 
2381  /// Indicate that the specified load with extension does not work with the
2382  /// specified type and indicate what to do about it.
2383  void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT,
2384  LegalizeAction Action) {
2385  assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() &&
2386  MemVT.isValid() && "Table isn't big enough!");
2387  assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
2388  unsigned Shift = 4 * ExtType;
2389  LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] &= ~((uint16_t)0xF << Shift);
2390  LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] |= (uint16_t)Action << Shift;
2391  }
2392  void setLoadExtAction(ArrayRef<unsigned> ExtTypes, MVT ValVT, MVT MemVT,
2393  LegalizeAction Action) {
2394  for (auto ExtType : ExtTypes)
2395  setLoadExtAction(ExtType, ValVT, MemVT, Action);
2396  }
2398  ArrayRef<MVT> MemVTs, LegalizeAction Action) {
2399  for (auto MemVT : MemVTs)
2400  setLoadExtAction(ExtTypes, ValVT, MemVT, Action);
2401  }
2402 
2403  /// Indicate that the specified truncating store does not work with the
2404  /// specified type and indicate what to do about it.
2405  void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action) {
2406  assert(ValVT.isValid() && MemVT.isValid() && "Table isn't big enough!");
2407  TruncStoreActions[(unsigned)ValVT.SimpleTy][MemVT.SimpleTy] = Action;
2408  }
2409 
2410  /// Indicate that the specified indexed load does or does not work with the
2411  /// specified type and indicate what to do abort it.
2412  ///
2413  /// NOTE: All indexed mode loads are initialized to Expand in
2414  /// TargetLowering.cpp
2416  LegalizeAction Action) {
2417  for (auto IdxMode : IdxModes)
2418  setIndexedModeAction(IdxMode, VT, IMAB_Load, Action);
2419  }
2420 
2422  LegalizeAction Action) {
2423  for (auto VT : VTs)
2424  setIndexedLoadAction(IdxModes, VT, Action);
2425  }
2426 
2427  /// Indicate that the specified indexed store does or does not work with the
2428  /// specified type and indicate what to do about it.
2429  ///
2430  /// NOTE: All indexed mode stores are initialized to Expand in
2431  /// TargetLowering.cpp
2433  LegalizeAction Action) {
2434  for (auto IdxMode : IdxModes)
2435  setIndexedModeAction(IdxMode, VT, IMAB_Store, Action);
2436  }
2437 
2439  LegalizeAction Action) {
2440  for (auto VT : VTs)
2441  setIndexedStoreAction(IdxModes, VT, Action);
2442  }
2443 
2444  /// Indicate that the specified indexed masked load does or does not work with
2445  /// the specified type and indicate what to do about it.
2446  ///
2447  /// NOTE: All indexed mode masked loads are initialized to Expand in
2448  /// TargetLowering.cpp
2449  void setIndexedMaskedLoadAction(unsigned IdxMode, MVT VT,
2450  LegalizeAction Action) {
2451  setIndexedModeAction(IdxMode, VT, IMAB_MaskedLoad, Action);
2452  }
2453 
2454  /// Indicate that the specified indexed masked store does or does not work
2455  /// with the specified type and indicate what to do about it.
2456  ///
2457  /// NOTE: All indexed mode masked stores are initialized to Expand in
2458  /// TargetLowering.cpp
2459  void setIndexedMaskedStoreAction(unsigned IdxMode, MVT VT,
2460  LegalizeAction Action) {
2461  setIndexedModeAction(IdxMode, VT, IMAB_MaskedStore, Action);
2462  }
2463 
2464  /// Indicate that the specified condition code is or isn't supported on the
2465  /// target and indicate what to do about it.
2467  LegalizeAction Action) {
2468  for (auto CC : CCs) {
2469  assert(VT.isValid() && (unsigned)CC < std::size(CondCodeActions) &&
2470  "Table isn't big enough!");
2471  assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
2472  /// The lower 3 bits of the SimpleTy index into Nth 4bit set from the
2473  /// 32-bit value and the upper 29 bits index into the second dimension of
2474  /// the array to select what 32-bit value to use.
2475  uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
2476  CondCodeActions[CC][VT.SimpleTy >> 3] &= ~((uint32_t)0xF << Shift);
2477  CondCodeActions[CC][VT.SimpleTy >> 3] |= (uint32_t)Action << Shift;
2478  }
2479  }
2481  LegalizeAction Action) {
2482  for (auto VT : VTs)
2483  setCondCodeAction(CCs, VT, Action);
2484  }
2485 
2486  /// If Opc/OrigVT is specified as being promoted, the promotion code defaults
2487  /// to trying a larger integer/fp until it can find one that works. If that
2488  /// default is insufficient, this method can be used by the target to override
2489  /// the default.
2490  void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
2491  PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
2492  }
2493 
2494  /// Convenience method to set an operation to Promote and specify the type
2495  /// in a single call.
2496  void setOperationPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
2497  setOperationAction(Opc, OrigVT, Promote);
2498  AddPromotedToType(Opc, OrigVT, DestVT);
2499  }
2500 
2501  /// Targets should invoke this method for each target independent node that
2502  /// they want to provide a custom DAG combiner for by implementing the
2503  /// PerformDAGCombine virtual method.
2505  for (auto NT : NTs) {
2506  assert(unsigned(NT >> 3) < std::size(TargetDAGCombineArray));
2507  TargetDAGCombineArray[NT >> 3] |= 1 << (NT & 7);
2508  }
2509  }
2510 
2511  /// Set the target's minimum function alignment.
2512  void setMinFunctionAlignment(Align Alignment) {
2513  MinFunctionAlignment = Alignment;
2514  }
2515 
2516  /// Set the target's preferred function alignment. This should be set if
2517  /// there is a performance benefit to higher-than-minimum alignment
2519  PrefFunctionAlignment = Alignment;
2520  }
2521 
2522  /// Set the target's preferred loop alignment. Default alignment is one, it
2523  /// means the target does not care about loop alignment. The target may also
2524  /// override getPrefLoopAlignment to provide per-loop values.
2525  void setPrefLoopAlignment(Align Alignment) { PrefLoopAlignment = Alignment; }
2526  void setMaxBytesForAlignment(unsigned MaxBytes) {
2527  MaxBytesForAlignment = MaxBytes;
2528  }
2529 
2530  /// Set the minimum stack alignment of an argument.
2532  MinStackArgumentAlignment = Alignment;
2533  }
2534 
2535  /// Set the maximum atomic operation size supported by the
2536  /// backend. Atomic operations greater than this size (as well as
2537  /// ones that are not naturally aligned), will be expanded by
2538  /// AtomicExpandPass into an __atomic_* library call.
2539  void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits) {
2540  MaxAtomicSizeInBitsSupported = SizeInBits;
2541  }
2542 
2543  /// Set the size in bits of the maximum div/rem the backend supports.
2544  /// Larger operations will be expanded by ExpandLargeDivRem.
2545  void setMaxDivRemBitWidthSupported(unsigned SizeInBits) {
2546  MaxDivRemBitWidthSupported = SizeInBits;
2547  }
2548 
2549  /// Set the size in bits of the maximum fp convert the backend supports.
2550  /// Larger operations will be expanded by ExpandLargeFPConvert.
2551  void setMaxLargeFPConvertBitWidthSupported(unsigned SizeInBits) {
2552  MaxLargeFPConvertBitWidthSupported = SizeInBits;
2553  }
2554 
2555  /// Sets the minimum cmpxchg or ll/sc size supported by the backend.
2556  void setMinCmpXchgSizeInBits(unsigned SizeInBits) {
2557  MinCmpXchgSizeInBits = SizeInBits;
2558  }
2559 
2560  /// Sets whether unaligned atomic operations are supported.
2561  void setSupportsUnalignedAtomics(bool UnalignedSupported) {
2562  SupportsUnalignedAtomics = UnalignedSupported;
2563  }
2564 
2565 public:
2566  //===--------------------------------------------------------------------===//
2567  // Addressing mode description hooks (used by LSR etc).
2568  //
2569 
2570  /// CodeGenPrepare sinks address calculations into the same BB as Load/Store
2571  /// instructions reading the address. This allows as much computation as
2572  /// possible to be done in the address mode for that operand. This hook lets
2573  /// targets also pass back when this should be done on intrinsics which
2574  /// load/store.
2575  virtual bool getAddrModeArguments(IntrinsicInst * /*I*/,
2576  SmallVectorImpl<Value*> &/*Ops*/,
2577  Type *&/*AccessTy*/) const {
2578  return false;
2579  }
2580 
2581  /// This represents an addressing mode of:
2582  /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
2583  /// If BaseGV is null, there is no BaseGV.
2584  /// If BaseOffs is zero, there is no base offset.
2585  /// If HasBaseReg is false, there is no base register.
2586  /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
2587  /// no scale.
2588  struct AddrMode {
2589  GlobalValue *BaseGV = nullptr;
2590  int64_t BaseOffs = 0;
2591  bool HasBaseReg = false;
2592  int64_t Scale = 0;
2593  AddrMode() = default;
2594  };
2595 
2596  /// Return true if the addressing mode represented by AM is legal for this
2597  /// target, for a load/store of the specified type.
2598  ///
2599  /// The type may be VoidTy, in which case only return true if the addressing
2600  /// mode is legal for a load/store of any legal type. TODO: Handle
2601  /// pre/postinc as well.
2602  ///
2603  /// If the address space cannot be determined, it will be -1.
2604  ///
2605  /// TODO: Remove default argument
2606  virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM,
2607  Type *Ty, unsigned AddrSpace,
2608  Instruction *I = nullptr) const;
2609 
2610  /// Return true if the specified immediate is legal icmp immediate, that is
2611  /// the target has icmp instructions which can compare a register against the
2612  /// immediate without having to materialize the immediate into a register.
2613  virtual bool isLegalICmpImmediate(int64_t) const {
2614  return true;
2615  }
2616 
2617  /// Return true if the specified immediate is legal add immediate, that is the
2618  /// target has add instructions which can add a register with the immediate
2619  /// without having to materialize the immediate into a register.
2620  virtual bool isLegalAddImmediate(int64_t) const {
2621  return true;
2622  }
2623 
2624  /// Return true if the specified immediate is legal for the value input of a
2625  /// store instruction.
2626  virtual bool isLegalStoreImmediate(int64_t Value) const {
2627  // Default implementation assumes that at least 0 works since it is likely
2628  // that a zero register exists or a zero immediate is allowed.
2629  return Value == 0;
2630  }
2631 
2632  /// Return true if it's significantly cheaper to shift a vector by a uniform
2633  /// scalar than by an amount which will vary across each lane. On x86 before
2634  /// AVX2 for example, there is a "psllw" instruction for the former case, but
2635  /// no simple instruction for a general "a << b" operation on vectors.
2636  /// This should also apply to lowering for vector funnel shifts (rotates).
2637  virtual bool isVectorShiftByScalarCheap(Type *Ty) const {
2638  return false;
2639  }
2640 
2641  /// Given a shuffle vector SVI representing a vector splat, return a new
2642  /// scalar type of size equal to SVI's scalar type if the new type is more
2643  /// profitable. Returns nullptr otherwise. For example under MVE float splats
2644  /// are converted to integer to prevent the need to move from SPR to GPR
2645  /// registers.
2647  return nullptr;
2648  }
2649 
2650  /// Given a set in interconnected phis of type 'From' that are loaded/stored
2651  /// or bitcast to type 'To', return true if the set should be converted to
2652  /// 'To'.
2653  virtual bool shouldConvertPhiType(Type *From, Type *To) const {
2654  return (From->isIntegerTy() || From->isFloatingPointTy()) &&
2655  (To->isIntegerTy() || To->isFloatingPointTy());
2656  }
2657 
2658  /// Returns true if the opcode is a commutative binary operation.
2659  virtual bool isCommutativeBinOp(unsigned Opcode) const {
2660  // FIXME: This should get its info from the td file.
2661  switch (Opcode) {
2662  case ISD::ADD:
2663  case ISD::SMIN:
2664  case ISD::SMAX:
2665  case ISD::UMIN:
2666  case ISD::UMAX:
2667  case ISD::MUL:
2668  case ISD::MULHU:
2669  case ISD::MULHS:
2670  case ISD::SMUL_LOHI:
2671  case ISD::UMUL_LOHI:
2672  case ISD::FADD:
2673  case ISD::FMUL:
2674  case ISD::AND:
2675  case ISD::OR:
2676  case ISD::XOR:
2677  case ISD::SADDO:
2678  case ISD::UADDO:
2679  case ISD::ADDC:
2680  case ISD::ADDE:
2681  case ISD::SADDSAT:
2682  case ISD::UADDSAT:
2683  case ISD::FMINNUM:
2684  case ISD::FMAXNUM:
2685  case ISD::FMINNUM_IEEE:
2686  case ISD::FMAXNUM_IEEE:
2687  case ISD::FMINIMUM:
2688  case ISD::FMAXIMUM:
2689  case ISD::AVGFLOORS:
2690  case ISD::AVGFLOORU:
2691  case ISD::AVGCEILS:
2692  case ISD::AVGCEILU:
2693  return true;
2694  default: return false;
2695  }
2696  }
2697 
2698  /// Return true if the node is a math/logic binary operator.
2699  virtual bool isBinOp(unsigned Opcode) const {
2700  // A commutative binop must be a binop.
2701  if (isCommutativeBinOp(Opcode))
2702  return true;
2703  // These are non-commutative binops.
2704  switch (Opcode) {
2705  case ISD::SUB:
2706  case ISD::SHL:
2707  case ISD::SRL:
2708  case ISD::SRA:
2709  case ISD::ROTL:
2710  case ISD::ROTR:
2711  case ISD::SDIV:
2712  case ISD::UDIV:
2713  case ISD::SREM:
2714  case ISD::UREM:
2715  case ISD::SSUBSAT:
2716  case ISD::USUBSAT:
2717  case ISD::FSUB:
2718  case ISD::FDIV:
2719  case ISD::FREM:
2720  return true;
2721  default:
2722  return false;
2723  }
2724  }
2725 
2726  /// Return true if it's free to truncate a value of type FromTy to type
2727  /// ToTy. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
2728  /// by referencing its sub-register AX.
2729  /// Targets must return false when FromTy <= ToTy.
2730  virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const {
2731  return false;
2732  }
2733 
2734  /// Return true if a truncation from FromTy to ToTy is permitted when deciding
2735  /// whether a call is in tail position. Typically this means that both results
2736  /// would be assigned to the same register or stack slot, but it could mean
2737  /// the target performs adequate checks of its own before proceeding with the
2738  /// tail call. Targets must return false when FromTy <= ToTy.
2739  virtual bool allowTruncateForTailCall(Type *FromTy, Type *ToTy) const {
2740  return false;
2741  }
2742 
2743  virtual bool isTruncateFree(EVT FromVT, EVT ToVT) const { return false; }
2744  virtual bool isTruncateFree(LLT FromTy, LLT ToTy, const DataLayout &DL,
2745  LLVMContext &Ctx) const {
2746  return isTruncateFree(getApproximateEVTForLLT(FromTy, DL, Ctx),
2747  getApproximateEVTForLLT(ToTy, DL, Ctx));
2748  }
2749 
2750  virtual bool isProfitableToHoist(Instruction *I) const { return true; }
2751 
2752  /// Return true if the extension represented by \p I is free.
2753  /// Unlikely the is[Z|FP]ExtFree family which is based on types,
2754  /// this method can use the context provided by \p I to decide
2755  /// whether or not \p I is free.
2756  /// This method extends the behavior of the is[Z|FP]ExtFree family.
2757  /// In other words, if is[Z|FP]Free returns true, then this method
2758  /// returns true as well. The converse is not true.
2759  /// The target can perform the adequate checks by overriding isExtFreeImpl.
2760  /// \pre \p I must be a sign, zero, or fp extension.
2761  bool isExtFree(const Instruction *I) const {
2762  switch (I->getOpcode()) {
2763  case Instruction::FPExt:
2764  if (isFPExtFree(EVT::getEVT(I->getType()),
2765  EVT::getEVT(I->getOperand(0)->getType())))
2766  return true;
2767  break;
2768  case Instruction::ZExt:
2769  if (isZExtFree(I->getOperand(0)->getType(), I->getType()))
2770  return true;
2771  break;
2772  case Instruction::SExt:
2773  break;
2774  default:
2775  llvm_unreachable("Instruction is not an extension");
2776  }
2777  return isExtFreeImpl(I);
2778  }
2779 
2780  /// Return true if \p Load and \p Ext can form an ExtLoad.
2781  /// For example, in AArch64
2782  /// %L = load i8, i8* %ptr
2783  /// %E = zext i8 %L to i32
2784  /// can be lowered into one load instruction
2785  /// ldrb w0, [x0]
2786  bool isExtLoad(const LoadInst *Load, const Instruction *Ext,
2787  const DataLayout &DL) const {
2788  EVT VT = getValueType(DL, Ext->getType());
2789  EVT LoadVT = getValueType(DL, Load->getType());
2790 
2791  // If the load has other users and the truncate is not free, the ext
2792  // probably isn't free.
2793  if (!Load->hasOneUse() && (isTypeLegal(LoadVT) || !isTypeLegal(VT)) &&
2794  !isTruncateFree(Ext->getType(), Load->getType()))
2795  return false;
2796 
2797  // Check whether the target supports casts folded into loads.
2798  unsigned LType;
2799  if (isa<ZExtInst>(Ext))
2800  LType = ISD::ZEXTLOAD;
2801  else {
2802  assert(isa<SExtInst>(Ext) && "Unexpected ext type!");
2803  LType = ISD::SEXTLOAD;
2804  }
2805 
2806  return isLoadExtLegal(LType, VT, LoadVT);
2807  }
2808 
2809  /// Return true if any actual instruction that defines a value of type FromTy
2810  /// implicitly zero-extends the value to ToTy in the result register.
2811  ///
2812  /// The function should return true when it is likely that the truncate can
2813  /// be freely folded with an instruction defining a value of FromTy. If
2814  /// the defining instruction is unknown (because you're looking at a
2815  /// function argument, PHI, etc.) then the target may require an
2816  /// explicit truncate, which is not necessarily free, but this function
2817  /// does not deal with those cases.
2818  /// Targets must return false when FromTy >= ToTy.
2819  virtual bool isZExtFree(Type *FromTy, Type *ToTy) const {
2820  return false;
2821  }
2822 
2823  virtual bool isZExtFree(EVT FromTy, EVT ToTy) const { return false; }
2824  virtual bool isZExtFree(LLT FromTy, LLT ToTy, const DataLayout &DL,
2825  LLVMContext &Ctx) const {
2826  return isZExtFree(getApproximateEVTForLLT(FromTy, DL, Ctx),
2827  getApproximateEVTForLLT(ToTy, DL, Ctx));
2828  }
2829 
2830  /// Return true if sign-extension from FromTy to ToTy is cheaper than
2831  /// zero-extension.
2832  virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const {
2833  return false;
2834  }
2835 
2836  /// Return true if this constant should be sign extended when promoting to
2837  /// a larger type.
2838  virtual bool signExtendConstant(const ConstantInt *C) const { return false; }
2839 
2840  /// Return true if sinking I's operands to the same basic block as I is
2841  /// profitable, e.g. because the operands can be folded into a target
2842  /// instruction during instruction selection. After calling the function
2843  /// \p Ops contains the Uses to sink ordered by dominance (dominating users
2844  /// come first).
2846  SmallVectorImpl<Use *> &Ops) const {
2847  return false;
2848  }
2849 
2850  /// Try to optimize extending or truncating conversion instructions (like
2851  /// zext, trunc, fptoui, uitofp) for the target.
2853  Loop *L) const {
2854  return false;
2855  }
2856 
2857  /// Return true if the target supplies and combines to a paired load
2858  /// two loaded values of type LoadedType next to each other in memory.
2859  /// RequiredAlignment gives the minimal alignment constraints that must be met
2860  /// to be able to select this paired load.
2861  ///
2862  /// This information is *not* used to generate actual paired loads, but it is
2863  /// used to generate a sequence of loads that is easier to combine into a
2864  /// paired load.
2865  /// For instance, something like this:
2866  /// a = load i64* addr
2867  /// b = trunc i64 a to i32
2868  /// c = lshr i64 a, 32
2869  /// d = trunc i64 c to i32
2870  /// will be optimized into:
2871  /// b = load i32* addr1
2872  /// d = load i32* addr2
2873  /// Where addr1 = addr2 +/- sizeof(i32).
2874  ///
2875  /// In other words, unless the target performs a post-isel load combining,
2876  /// this information should not be provided because it will generate more
2877  /// loads.
2878  virtual bool hasPairedLoad(EVT /*LoadedType*/,
2879  Align & /*RequiredAlignment*/) const {
2880  return false;
2881  }
2882 
2883  /// Return true if the target has a vector blend instruction.
2884  virtual bool hasVectorBlend() const { return false; }
2885 
2886  /// Get the maximum supported factor for interleaved memory accesses.
2887  /// Default to be the minimum interleave factor: 2.
2888  virtual unsigned getMaxSupportedInterleaveFactor() const { return 2; }
2889 
2890  /// Lower an interleaved load to target specific intrinsics. Return
2891  /// true on success.
2892  ///
2893  /// \p LI is the vector load instruction.
2894  /// \p Shuffles is the shufflevector list to DE-interleave the loaded vector.
2895  /// \p Indices is the corresponding indices for each shufflevector.
2896  /// \p Factor is the interleave factor.
2897  virtual bool lowerInterleavedLoad(LoadInst *LI,
2899  ArrayRef<unsigned> Indices,
2900  unsigned Factor) const {
2901  return false;
2902  }
2903 
2904  /// Lower an interleaved store to target specific intrinsics. Return
2905  /// true on success.
2906  ///
2907  /// \p SI is the vector store instruction.
2908  /// \p SVI is the shufflevector to RE-interleave the stored vector.
2909  /// \p Factor is the interleave factor.
2911  unsigned Factor) const {
2912  return false;
2913  }
2914 
2915  /// Return true if zero-extending the specific node Val to type VT2 is free
2916  /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
2917  /// because it's folded such as X86 zero-extending loads).
2918  virtual bool isZExtFree(SDValue Val, EVT VT2) const {
2919  return isZExtFree(Val.getValueType(), VT2);
2920  }
2921 
2922  /// Return true if an fpext operation is free (for instance, because
2923  /// single-precision floating-point numbers are implicitly extended to
2924  /// double-precision).
2925  virtual bool isFPExtFree(EVT DestVT, EVT SrcVT) const {
2926  assert(SrcVT.isFloatingPoint() && DestVT.isFloatingPoint() &&
2927  "invalid fpext types");
2928  return false;
2929  }
2930 
2931  /// Return true if an fpext operation input to an \p Opcode operation is free
2932  /// (for instance, because half-precision floating-point numbers are
2933  /// implicitly extended to float-precision) for an FMA instruction.
2934  virtual bool isFPExtFoldable(const MachineInstr &MI, unsigned Opcode,
2935  LLT DestTy, LLT SrcTy) const {
2936  return false;
2937  }
2938 
2939  /// Return true if an fpext operation input to an \p Opcode operation is free
2940  /// (for instance, because half-precision floating-point numbers are
2941  /// implicitly extended to float-precision) for an FMA instruction.
2942  virtual bool isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
2943  EVT DestVT, EVT SrcVT) const {
2944  assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
2945  "invalid fpext types");
2946  return isFPExtFree(DestVT, SrcVT);
2947  }
2948 
2949  /// Return true if folding a vector load into ExtVal (a sign, zero, or any
2950  /// extend node) is profitable.
2951  virtual bool isVectorLoadExtDesirable(SDValue ExtVal) const { return false; }
2952 
2953  /// Return true if an fneg operation is free to the point where it is never
2954  /// worthwhile to replace it with a bitwise operation.
2955  virtual bool isFNegFree(EVT VT) const {
2956  assert(VT.isFloatingPoint());
2957  return false;
2958  }
2959 
2960  /// Return true if an fabs operation is free to the point where it is never
2961  /// worthwhile to replace it with a bitwise operation.
2962  virtual bool isFAbsFree(EVT VT) const {
2963  assert(VT.isFloatingPoint());
2964  return false;
2965  }
2966 
2967  /// Return true if an FMA operation is faster than a pair of fmul and fadd
2968  /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
2969  /// returns true, otherwise fmuladd is expanded to fmul + fadd.
2970  ///
2971  /// NOTE: This may be called before legalization on types for which FMAs are
2972  /// not legal, but should return true if those types will eventually legalize
2973  /// to types that support FMAs. After legalization, it will only be called on
2974  /// types that support FMAs (via Legal or Custom actions)
2976  EVT) const {
2977  return false;
2978  }
2979 
2980  /// Return true if an FMA operation is faster than a pair of fmul and fadd
2981  /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
2982  /// returns true, otherwise fmuladd is expanded to fmul + fadd.
2983  ///
2984  /// NOTE: This may be called before legalization on types for which FMAs are
2985  /// not legal, but should return true if those types will eventually legalize
2986  /// to types that support FMAs. After legalization, it will only be called on
2987  /// types that support FMAs (via Legal or Custom actions)
2989  LLT) const {
2990  return false;
2991  }
2992 
2993  /// IR version
2994  virtual bool isFMAFasterThanFMulAndFAdd(const Function &F, Type *) const {
2995  return false;
2996  }
2997 
2998  /// Returns true if \p MI can be combined with another instruction to
2999  /// form TargetOpcode::G_FMAD. \p N may be an TargetOpcode::G_FADD,
3000  /// TargetOpcode::G_FSUB, or an TargetOpcode::G_FMUL which will be
3001  /// distributed into an fadd/fsub.
3002  virtual bool isFMADLegal(const MachineInstr &MI, LLT Ty) const {
3003  assert((MI.getOpcode() == TargetOpcode::G_FADD ||
3004  MI.getOpcode() == TargetOpcode::G_FSUB ||
3005  MI.getOpcode() == TargetOpcode::G_FMUL) &&
3006  "unexpected node in FMAD forming combine");
3007  switch (Ty.getScalarSizeInBits()) {
3008  case 16:
3009  return isOperationLegal(TargetOpcode::G_FMAD, MVT::f16);
3010  case 32:
3011  return isOperationLegal(TargetOpcode::G_FMAD, MVT::f32);
3012  case 64:
3013  return isOperationLegal(TargetOpcode::G_FMAD, MVT::f64);
3014  default:
3015  break;
3016  }
3017 
3018  return false;
3019  }
3020 
3021  /// Returns true if be combined with to form an ISD::FMAD. \p N may be an
3022  /// ISD::FADD, ISD::FSUB, or an ISD::FMUL which will be distributed into an
3023  /// fadd/fsub.
3024  virtual bool isFMADLegal(const SelectionDAG &DAG, const SDNode *N) const {
3025  assert((N->getOpcode() == ISD::FADD || N->getOpcode() == ISD::FSUB ||
3026  N->getOpcode() == ISD::FMUL) &&
3027  "unexpected node in FMAD forming combine");
3028  return isOperationLegal(ISD::FMAD, N->getValueType(0));
3029  }
3030 
3031  // Return true when the decision to generate FMA's (or FMS, FMLA etc) rather
3032  // than FMUL and ADD is delegated to the machine combiner.
3034  CodeGenOpt::Level OptLevel) const {
3035  return false;
3036  }
3037 
3038  /// Return true if it's profitable to narrow operations of type VT1 to
3039  /// VT2. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
3040  /// i32 to i16.
3041  virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
3042  return false;
3043  }
3044 
3045  /// Return true if pulling a binary operation into a select with an identity
3046  /// constant is profitable. This is the inverse of an IR transform.
3047  /// Example: X + (Cond ? Y : 0) --> Cond ? (X + Y) : X
3048  virtual bool shouldFoldSelectWithIdentityConstant(unsigned BinOpcode,
3049  EVT VT) const {
3050  return false;
3051  }
3052 
3053  /// Return true if it is beneficial to convert a load of a constant to
3054  /// just the constant itself.
3055  /// On some targets it might be more efficient to use a combination of
3056  /// arithmetic instructions to materialize the constant instead of loading it
3057  /// from a constant pool.
3059  Type *Ty) const {
3060  return false;
3061  }
3062 
3063  /// Return true if EXTRACT_SUBVECTOR is cheap for extracting this result type
3064  /// from this source type with this index. This is needed because
3065  /// EXTRACT_SUBVECTOR usually has custom lowering that depends on the index of
3066  /// the first element, and only the target knows which lowering is cheap.
3067  virtual bool isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
3068  unsigned Index) const {
3069  return false;
3070  }
3071 
3072  /// Try to convert an extract element of a vector binary operation into an
3073  /// extract element followed by a scalar operation.
3074  virtual bool shouldScalarizeBinop(SDValue VecOp) const {
3075  return false;
3076  }
3077 
3078  /// Return true if extraction of a scalar element from the given vector type
3079  /// at the given index is cheap. For example, if scalar operations occur on
3080  /// the same register file as vector operations, then an extract element may
3081  /// be a sub-register rename rather than an actual instruction.
3082  virtual bool isExtractVecEltCheap(EVT VT, unsigned Index) const {
3083  return false;
3084  }
3085 
3086  /// Try to convert math with an overflow comparison into the corresponding DAG
3087  /// node operation. Targets may want to override this independently of whether
3088  /// the operation is legal/custom for the given type because it may obscure
3089  /// matching of other patterns.
3090  virtual bool shouldFormOverflowOp(unsigned Opcode, EVT VT,
3091  bool MathUsed) const {
3092  // TODO: The default logic is inherited from code in CodeGenPrepare.
3093  // The opcode should not make a difference by default?
3094  if (Opcode != ISD::UADDO)
3095  return false;
3096 
3097  // Allow the transform as long as we have an integer type that is not
3098  // obviously illegal and unsupported and if the math result is used
3099  // besides the overflow check. On some targets (e.g. SPARC), it is
3100  // not profitable to form on overflow op if the math result has no
3101  // concrete users.
3102  if (VT.isVector())
3103  return false;
3104  return MathUsed && (VT.isSimple() || !isOperationExpand(Opcode, VT));
3105  }
3106 
3107  // Return true if it is profitable to use a scalar input to a BUILD_VECTOR
3108  // even if the vector itself has multiple uses.
3109  virtual bool aggressivelyPreferBuildVectorSources(EVT VecVT) const {
3110  return false;
3111  }
3112 
3113  // Return true if CodeGenPrepare should consider splitting large offset of a
3114  // GEP to make the GEP fit into the addressing mode and can be sunk into the
3115  // same blocks of its users.
3116  virtual bool shouldConsiderGEPOffsetSplit() const { return false; }
3117 
3118  /// Return true if creating a shift of the type by the given
3119  /// amount is not profitable.
3120  virtual bool shouldAvoidTransformToShift(EVT VT, unsigned Amount) const {
3121  return false;
3122  }
3123 
3124  /// Does this target require the clearing of high-order bits in a register
3125  /// passed to the fp16 to fp conversion library function.
3126  virtual bool shouldKeepZExtForFP16Conv() const { return false; }
3127 
3128  /// Should we generate fp_to_si_sat and fp_to_ui_sat from type FPVT to type VT
3129  /// from min(max(fptoi)) saturation patterns.
3130  virtual bool shouldConvertFpToSat(unsigned Op, EVT FPVT, EVT VT) const {
3131  return isOperationLegalOrCustom(Op, VT);
3132  }
3133 
3134  /// Does this target support complex deinterleaving
3135  virtual bool isComplexDeinterleavingSupported() const { return false; }
3136 
3137  /// Does this target support complex deinterleaving with the given operation
3138  /// and type
3141  return false;
3142  }
3143 
3144  /// Create the IR node for the given complex deinterleaving operation.
3145  /// If one cannot be created using all the given inputs, nullptr should be
3146  /// returned.
3149  ComplexDeinterleavingRotation Rotation, Value *InputA, Value *InputB,
3150  Value *Accumulator = nullptr) const {
3151  return nullptr;
3152  }
3153 
3154  //===--------------------------------------------------------------------===//
3155  // Runtime Library hooks
3156  //
3157 
3158  /// Rename the default libcall routine name for the specified libcall.
3159  void setLibcallName(RTLIB::Libcall Call, const char *Name) {
3160  LibcallRoutineNames[Call] = Name;
3161  }
3162  void setLibcallName(ArrayRef<RTLIB::Libcall> Calls, const char *Name) {
3163  for (auto Call : Calls)
3164  setLibcallName(Call, Name);
3165  }
3166 
3167  /// Get the libcall routine name for the specified libcall.
3168  const char *getLibcallName(RTLIB::Libcall Call) const {
3169  return LibcallRoutineNames[Call];
3170  }
3171 
3172  /// Override the default CondCode to be used to test the result of the
3173  /// comparison libcall against zero.
3175  CmpLibcallCCs[Call] = CC;
3176  }
3177 
3178  /// Get the CondCode that's to be used to test the result of the comparison
3179  /// libcall against zero.
3181  return CmpLibcallCCs[Call];
3182  }
3183 
3184  /// Set the CallingConv that should be used for the specified libcall.
3186  LibcallCallingConvs[Call] = CC;
3187  }
3188 
3189  /// Get the CallingConv that should be used for the specified libcall.
3191  return LibcallCallingConvs[Call];
3192  }
3193 
3194  /// Execute target specific actions to finalize target lowering.
3195  /// This is used to set extra flags in MachineFrameInformation and freezing
3196  /// the set of reserved registers.
3197  /// The default implementation just freezes the set of reserved registers.
3198  virtual void finalizeLowering(MachineFunction &MF) const;
3199 
3200  //===----------------------------------------------------------------------===//
3201  // GlobalISel Hooks
3202  //===----------------------------------------------------------------------===//
3203  /// Check whether or not \p MI needs to be moved close to its uses.
3204  virtual bool shouldLocalize(const MachineInstr &MI, const TargetTransformInfo *TTI) const;
3205 
3206 
3207 private:
3208  const TargetMachine &TM;
3209 
3210  /// Tells the code generator that the target has multiple (allocatable)
3211  /// condition registers that can be used to store the results of comparisons
3212  /// for use by selects and conditional branches. With multiple condition
3213  /// registers, the code generator will not aggressively sink comparisons into
3214  /// the blocks of their users.
3215  bool HasMultipleConditionRegisters;
3216 
3217  /// Tells the code generator that the target has BitExtract instructions.
3218  /// The code generator will aggressively sink "shift"s into the blocks of
3219  /// their users if the users will generate "and" instructions which can be
3220  /// combined with "shift" to BitExtract instructions.
3221  bool HasExtractBitsInsn;
3222 
3223  /// Tells the code generator to bypass slow divide or remainder
3224  /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
3225  /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
3226  /// div/rem when the operands are positive and less than 256.
3227  DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
3228 
3229  /// Tells the code generator that it shouldn't generate extra flow control
3230  /// instructions and should attempt to combine flow control instructions via
3231  /// predication.
3232  bool JumpIsExpensive;
3233 
3234  /// Information about the contents of the high-bits in boolean values held in
3235  /// a type wider than i1. See getBooleanContents.
3236  BooleanContent BooleanContents;
3237 
3238  /// Information about the contents of the high-bits in boolean values held in
3239  /// a type wider than i1. See getBooleanContents.
3240  BooleanContent BooleanFloatContents;
3241 
3242  /// Information about the contents of the high-bits in boolean vector values
3243  /// when the element type is wider than i1. See getBooleanContents.
3244  BooleanContent BooleanVectorContents;
3245 
3246  /// The target scheduling preference: shortest possible total cycles or lowest
3247  /// register usage.
3248  Sched::Preference SchedPreferenceInfo;
3249 
3250  /// The minimum alignment that any argument on the stack needs to have.
3251  Align MinStackArgumentAlignment;
3252 
3253  /// The minimum function alignment (used when optimizing for size, and to
3254  /// prevent explicitly provided alignment from leading to incorrect code).
3255  Align MinFunctionAlignment;
3256 
3257  /// The preferred function alignment (used when alignment unspecified and
3258  /// optimizing for speed).
3259  Align PrefFunctionAlignment;
3260 
3261  /// The preferred loop alignment (in log2 bot in bytes).
3262  Align PrefLoopAlignment;
3263  /// The maximum amount of bytes permitted to be emitted for alignment.
3264  unsigned MaxBytesForAlignment;
3265 
3266  /// Size in bits of the maximum atomics size the backend supports.
3267  /// Accesses larger than this will be expanded by AtomicExpandPass.
3268  unsigned MaxAtomicSizeInBitsSupported;
3269 
3270  /// Size in bits of the maximum div/rem size the backend supports.
3271  /// Larger operations will be expanded by ExpandLargeDivRem.
3272  unsigned MaxDivRemBitWidthSupported;
3273 
3274  /// Size in bits of the maximum larget fp convert size the backend
3275  /// supports. Larger operations will be expanded by ExpandLargeFPConvert.
3276  unsigned MaxLargeFPConvertBitWidthSupported;
3277 
3278  /// Size in bits of the minimum cmpxchg or ll/sc operation the
3279  /// backend supports.
3280  unsigned MinCmpXchgSizeInBits;
3281 
3282  /// This indicates if the target supports unaligned atomic operations.
3283  bool SupportsUnalignedAtomics;
3284 
3285  /// If set to a physical register, this specifies the register that
3286  /// llvm.savestack/llvm.restorestack should save and restore.
3287  Register StackPointerRegisterToSaveRestore;
3288 
3289  /// This indicates the default register class to use for each ValueType the
3290  /// target supports natively.
3291  const TargetRegisterClass *RegClassForVT[MVT::VALUETYPE_SIZE];
3292  uint16_t NumRegistersForVT[MVT::VALUETYPE_SIZE];
3293  MVT RegisterTypeForVT[MVT::VALUETYPE_SIZE];
3294 
3295  /// This indicates the "representative" register class to use for each
3296  /// ValueType the target supports natively. This information is used by the
3297  /// scheduler to track register pressure. By default, the representative
3298  /// register class is the largest legal super-reg register class of the
3299  /// register class of the specified type. e.g. On x86, i8, i16, and i32's
3300  /// representative class would be GR32.
3301  const TargetRegisterClass *RepRegClassForVT[MVT::VALUETYPE_SIZE];
3302 
3303  /// This indicates the "cost" of the "representative" register class for each
3304  /// ValueType. The cost is used by the scheduler to approximate register
3305  /// pressure.
3306  uint8_t RepRegClassCostForVT[MVT::VALUETYPE_SIZE];
3307 
3308  /// For any value types we are promoting or expanding, this contains the value
3309  /// type that we are changing to. For Expanded types, this contains one step
3310  /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
3311  /// (e.g. i64 -> i16). For types natively supported by the system, this holds
3312  /// the same type (e.g. i32 -> i32).
3313  MVT TransformToType[MVT::VALUETYPE_SIZE];
3314 
3315  /// For each operation and each value type, keep a LegalizeAction that
3316  /// indicates how instruction selection should deal with the operation. Most
3317  /// operations are Legal (aka, supported natively by the target), but
3318  /// operations that are not should be described. Note that operations on
3319  /// non-legal value types are not described here.
3321 
3322  /// For each load extension type and each value type, keep a LegalizeAction
3323  /// that indicates how instruction selection should deal with a load of a
3324  /// specific value type and extension type. Uses 4-bits to store the action
3325  /// for each of the 4 load ext types.
3327 
3328  /// For each value type pair keep a LegalizeAction that indicates whether a
3329  /// truncating store of a specific value type and truncating type is legal.
3331 
3332  /// For each indexed mode and each value type, keep a quad of LegalizeAction
3333  /// that indicates how instruction selection should deal with the load /
3334  /// store / maskedload / maskedstore.
3335  ///
3336  /// The first dimension is the value_type for the reference. The second
3337  /// dimension represents the various modes for load store.
3339 
3340  /// For each condition code (ISD::CondCode) keep a LegalizeAction that
3341  /// indicates how instruction selection should deal with the condition code.
3342  ///
3343  /// Because each CC action takes up 4 bits, we need to have the array size be
3344  /// large enough to fit all of the value types. This can be done by rounding
3345  /// up the MVT::VALUETYPE_SIZE value to the next multiple of 8.
3346  uint32_t CondCodeActions[ISD::SETCC_INVALID][(MVT::VALUETYPE_SIZE + 7) / 8];
3347 
3348  ValueTypeActionImpl ValueTypeActions;
3349 
3350 private:
3351  /// Targets can specify ISD nodes that they would like PerformDAGCombine
3352  /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
3353  /// array.
3354  unsigned char
3355  TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
3356 
3357  /// For operations that must be promoted to a specific type, this holds the
3358  /// destination type. This map should be sparse, so don't hold it as an
3359  /// array.
3360  ///
3361  /// Targets add entries to this map with AddPromotedToType(..), clients access
3362  /// this with getTypeToPromoteTo(..).
3363  std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
3364  PromoteToType;
3365 
3366  /// Stores the name each libcall.
3367  const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL + 1];
3368 
3369  /// The ISD::CondCode that should be used to test the result of each of the
3370  /// comparison libcall against zero.
3371  ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
3372 
3373  /// Stores the CallingConv that should be used for each libcall.
3374  CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
3375 
3376  /// Set default libcall names and calling conventions.
3377  void InitLibcalls(const Triple &TT);
3378 
3379  /// The bits of IndexedModeActions used to store the legalisation actions
3380  /// We store the data as | ML | MS | L | S | each taking 4 bits.
3381  enum IndexedModeActionsBits {
3382  IMAB_Store = 0,
3383  IMAB_Load = 4,
3384  IMAB_MaskedStore = 8,
3385  IMAB_MaskedLoad = 12
3386  };
3387 
3388  void setIndexedModeAction(unsigned IdxMode, MVT VT, unsigned Shift,
3389  LegalizeAction Action) {
3390  assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&
3391  (unsigned)Action < 0xf && "Table isn't big enough!");
3392  unsigned Ty = (unsigned)VT.SimpleTy;
3393  IndexedModeActions[Ty][IdxMode] &= ~(0xf << Shift);
3394  IndexedModeActions[Ty][IdxMode] |= ((uint16_t)Action) << Shift;
3395  }
3396 
3397  LegalizeAction getIndexedModeAction(unsigned IdxMode, MVT VT,
3398  unsigned Shift) const {
3399  assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&
3400  "Table isn't big enough!");
3401  unsigned Ty = (unsigned)VT.SimpleTy;
3402  return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] >> Shift) & 0xf);
3403  }
3404 
3405 protected:
3406  /// Return true if the extension represented by \p I is free.
3407  /// \pre \p I is a sign, zero, or fp extension and
3408  /// is[Z|FP]ExtFree of the related types is not true.
3409  virtual bool isExtFreeImpl(const Instruction *I) const { return false; }
3410 
3411  /// Depth that GatherAllAliases should should continue looking for chain
3412  /// dependencies when trying to find a more preferable chain. As an
3413  /// approximation, this should be more than the number of consecutive stores
3414  /// expected to be merged.
3416 
3417  /// \brief Specify maximum number of store instructions per memset call.
3418  ///
3419  /// When lowering \@llvm.memset this field specifies the maximum number of
3420  /// store operations that may be substituted for the call to memset. Targets
3421  /// must set this value based on the cost threshold for that target. Targets
3422  /// should assume that the memset will be done using as many of the largest
3423  /// store operations first, followed by smaller ones, if necessary, per
3424  /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
3425  /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
3426  /// store. This only applies to setting a constant array of a constant size.
3428  /// Likewise for functions with the OptSize attribute.
3430 
3431  /// \brief Specify maximum number of store instructions per memcpy call.
3432  ///
3433  /// When lowering \@llvm.memcpy this field specifies the maximum number of
3434  /// store operations that may be substituted for a call to memcpy. Targets
3435  /// must set this value based on the cost threshold for that target. Targets
3436  /// should assume that the memcpy will be done using as many of the largest
3437  /// store operations first, followed by smaller ones, if necessary, per
3438  /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
3439  /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
3440  /// and one 1-byte store. This only applies to copying a constant array of
3441  /// constant size.
3443  /// Likewise for functions with the OptSize attribute.
3445  /// \brief Specify max number of store instructions to glue in inlined memcpy.
3446  ///
3447  /// When memcpy is inlined based on MaxStoresPerMemcpy, specify maximum number
3448  /// of store instructions to keep together. This helps in pairing and
3449  // vectorization later on.
3451 
3452  /// \brief Specify maximum number of load instructions per memcmp call.
3453  ///
3454  /// When lowering \@llvm.memcmp this field specifies the maximum number of
3455  /// pairs of load operations that may be substituted for a call to memcmp.
3456  /// Targets must set this value based on the cost threshold for that target.
3457  /// Targets should assume that the memcmp will be done using as many of the
3458  /// largest load operations first, followed by smaller ones, if necessary, per
3459  /// alignment restrictions. For example, loading 7 bytes on a 32-bit machine
3460  /// with 32-bit alignment would result in one 4-byte load, a one 2-byte load
3461  /// and one 1-byte load. This only applies to copying a constant array of
3462  /// constant size.
3464  /// Likewise for functions with the OptSize attribute.
3466 
3467  /// \brief Specify maximum number of store instructions per memmove call.
3468  ///
3469  /// When lowering \@llvm.memmove this field specifies the maximum number of
3470  /// store instructions that may be substituted for a call to memmove. Targets
3471  /// must set this value based on the cost threshold for that target. Targets
3472  /// should assume that the memmove will be done using as many of the largest
3473  /// store operations first, followed by smaller ones, if necessary, per
3474  /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
3475  /// with 8-bit alignment would result in nine 1-byte stores. This only
3476  /// applies to copying a constant array of constant size.
3478  /// Likewise for functions with the OptSize attribute.
3480 
3481  /// Tells the code generator that select is more expensive than a branch if
3482  /// the branch is usually predicted right.
3484 
3485  /// \see enableExtLdPromotion.
3487 
3488  /// Return true if the value types that can be represented by the specified
3489  /// register class are all legal.
3490  bool isLegalRC(const TargetRegisterInfo &TRI,
3491  const TargetRegisterClass &RC) const;
3492 
3493  /// Replace/modify any TargetFrameIndex operands with a targte-dependent
3494  /// sequence of memory operands that is recognized by PrologEpilogInserter.
3496  MachineBasicBlock *MBB) const;
3497 
3499 };
3500 
3501 /// This class defines information used to lower LLVM code to legal SelectionDAG
3502 /// operators that the target instruction selector can accept natively.
3503 ///
3504 /// This class also defines callbacks that targets must implement to lower
3505 /// target-specific constructs to SelectionDAG operators.
3507 public:
3508  struct DAGCombinerInfo;
3509  struct MakeLibCallOptions;
3510 
3511  TargetLowering(const TargetLowering &) = delete;
3512  TargetLowering &operator=(const TargetLowering &) = delete;
3513 
3514  explicit TargetLowering(const TargetMachine &TM);
3515 
3516  bool isPositionIndependent() const;
3517 
3518  virtual bool isSDNodeSourceOfDivergence(const SDNode *N,
3519  FunctionLoweringInfo *FLI,
3520  LegacyDivergenceAnalysis *DA) const {
3521  return false;
3522  }
3523 
3524  // Lets target to control the following reassociation of operands: (op (op x,
3525  // c1), y) -> (op (op x, y), c1) where N0 is (op x, c1) and N1 is y. By
3526  // default consider profitable any case where N0 has single use. This
3527  // behavior reflects the condition replaced by this target hook call in the
3528  // DAGCombiner. Any particular target can implement its own heuristic to
3529  // restrict common combiner.
3531  SDValue N1) const {
3532  return N0.hasOneUse();
3533  }
3534 
3535  virtual bool isSDNodeAlwaysUniform(const SDNode * N) const {
3536  return false;
3537  }
3538 
3539  /// Returns true by value, base pointer and offset pointer and addressing mode
3540  /// by reference if the node's address can be legally represented as
3541  /// pre-indexed load / store address.
3542  virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
3543  SDValue &/*Offset*/,
3544  ISD::MemIndexedMode &/*AM*/,
3545  SelectionDAG &/*DAG*/) const {
3546  return false;
3547  }
3548 
3549  /// Returns true by value, base pointer and offset pointer and addressing mode
3550  /// by reference if this node can be combined with a load / store to form a
3551  /// post-indexed load / store.
3552  virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
3553  SDValue &/*Base*/,
3554  SDValue &/*Offset*/,
3555  ISD::MemIndexedMode &/*AM*/,
3556  SelectionDAG &/*DAG*/) const {
3557  return false;
3558  }
3559 
3560  /// Returns true if the specified base+offset is a legal indexed addressing
3561  /// mode for this target. \p MI is the load or store instruction that is being
3562  /// considered for transformation.
3564  bool IsPre, MachineRegisterInfo &MRI) const {
3565  return false;
3566  }
3567 
3568  /// Return the entry encoding for a jump table in the current function. The
3569  /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
3570  virtual unsigned getJumpTableEncoding() const;
3571 
3572  virtual const MCExpr *
3574  const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
3575  MCContext &/*Ctx*/) const {
3576  llvm_unreachable("Need to implement this hook if target has custom JTIs");
3577  }
3578 
3579  /// Returns relocation base for the given PIC jumptable.
3581  SelectionDAG &DAG) const;
3582 
3583  /// This returns the relocation base for the given PIC jumptable, the same as
3584  /// getPICJumpTableRelocBase, but as an MCExpr.
3585  virtual const MCExpr *
3587  unsigned JTI, MCContext &Ctx) const;
3588 
3589  /// Return true if folding a constant offset with the given GlobalAddress is
3590  /// legal. It is frequently not legal in PIC relocation models.
3591  virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
3592 
3593  /// Return true if the operand with index OpNo corresponding to a target
3594  /// branch, for example, in following case
3595  ///
3596  /// call void asm "lea r8, $0\0A\09call qword ptr ${1:P}\0A\09ret",
3597  /// "*m,*m,~{r8},~{dirflag},~{fpsr},~{flags}"
3598  /// ([9 x i32]* @Arr), void (...)* @sincos_asm)
3599  ///
3600  /// the operand $1 (sincos_asm) is target branch in inline asm, but the
3601  /// operand $0 (Arr) is not.
3602  virtual bool
3604  unsigned OpNo) const {
3605  return false;
3606  }
3607 
3609  SDValue &Chain) const;
3610 
3611  void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
3612  SDValue &NewRHS, ISD::CondCode &CCCode,
3613  const SDLoc &DL, const SDValue OldLHS,
3614  const SDValue OldRHS) const;
3615 
3616  void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
3617  SDValue &NewRHS, ISD::CondCode &CCCode,
3618  const SDLoc &DL, const SDValue OldLHS,
3619  const SDValue OldRHS, SDValue &Chain,
3620  bool IsSignaling = false) const;
3621 
3622  /// Returns a pair of (return value, chain).
3623  /// It is an error to pass RTLIB::UNKNOWN_LIBCALL as \p LC.
3624  std::pair<SDValue, SDValue> makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC,
3625  EVT RetVT, ArrayRef<SDValue> Ops,
3626  MakeLibCallOptions CallOptions,
3627  const SDLoc &dl,
3628  SDValue Chain = SDValue()) const;
3629 
3630  /// Check whether parameters to a call that are passed in callee saved
3631  /// registers are the same as from the calling function. This needs to be
3632  /// checked for tail call eligibility.
3634  const uint32_t *CallerPreservedMask,
3635  const SmallVectorImpl<CCValAssign> &ArgLocs,
3636  const SmallVectorImpl<SDValue> &OutVals) const;
3637 
3638  //===--------------------------------------------------------------------===//
3639  // TargetLowering Optimization Methods
3640  //
3641 
3642  /// A convenience struct that encapsulates a DAG, and two SDValues for
3643  /// returning information from TargetLowering to its clients that want to
3644  /// combine.
3647  bool LegalTys;
3648  bool LegalOps;
3651 
3653  bool LT, bool LO) :
3654  DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
3655 
3656  bool LegalTypes() const { return LegalTys; }
3657  bool LegalOperations() const { return LegalOps; }
3658 
3660  Old = O;
3661  New = N;
3662  return true;
3663  }
3664  };
3665 
3666  /// Determines the optimal series of memory ops to replace the memset / memcpy.
3667  /// Return true if the number of memory ops is below the threshold (Limit).
3668  /// Note that this is always the case when Limit is ~0.
3669  /// It returns the types of the sequence of memory ops to perform
3670  /// memset / memcpy by reference.
3671  virtual bool
3672  findOptimalMemOpLowering(std::vector<EVT> &MemOps, unsigned Limit,
3673  const MemOp &Op, unsigned DstAS, unsigned SrcAS,
3674  const AttributeList &FuncAttributes) const;
3675 
3676  /// Check to see if the specified operand of the specified instruction is a
3677  /// constant integer. If so, check to see if there are any bits set in the
3678  /// constant that are not demanded. If so, shrink the constant and return
3679  /// true.
3681  const APInt &DemandedElts,
3682  TargetLoweringOpt &TLO) const;
3683 
3684  /// Helper wrapper around ShrinkDemandedConstant, demanding all elements.
3686  TargetLoweringOpt &TLO) const;
3687 
3688  // Target hook to do target-specific const optimization, which is called by
3689  // ShrinkDemandedConstant. This function should return true if the target
3690  // doesn't want ShrinkDemandedConstant to further optimize the constant.
3692  const APInt &DemandedBits,
3693  const APInt &DemandedElts,
3694  TargetLoweringOpt &TLO) const {
3695  return false;
3696  }
3697 
3698  /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. This
3699  /// uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
3700  /// generalized for targets with other types of implicit widening casts.
3701  bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
3702  TargetLoweringOpt &TLO) const;
3703 
3704  /// Look at Op. At this point, we know that only the DemandedBits bits of the
3705  /// result of Op are ever used downstream. If we can use this information to
3706  /// simplify Op, create a new simplified DAG node and return true, returning
3707  /// the original and new nodes in Old and New. Otherwise, analyze the
3708  /// expression and return a mask of KnownOne and KnownZero bits for the
3709  /// expression (used to simplify the caller). The KnownZero/One bits may only
3710  /// be accurate for those bits in the Demanded masks.
3711  /// \p AssumeSingleUse When this parameter is true, this function will
3712  /// attempt to simplify \p Op even if there are multiple uses.
3713  /// Callers are responsible for correctly updating the DAG based on the
3714  /// results of this function, because simply replacing replacing TLO.Old
3715  /// with TLO.New will be incorrect when this parameter is true and TLO.Old
3716  /// has multiple uses.
3718  const APInt &DemandedElts, KnownBits &Known,
3719  TargetLoweringOpt &TLO, unsigned Depth = 0,
3720  bool AssumeSingleUse = false) const;
3721 
3722  /// Helper wrapper around SimplifyDemandedBits, demanding all elements.
3723  /// Adds Op back to the worklist upon success.
3725  KnownBits &Known, TargetLoweringOpt &TLO,
3726  unsigned Depth = 0,
3727  bool AssumeSingleUse = false) const;
3728 
3729  /// Helper wrapper around SimplifyDemandedBits.
3730  /// Adds Op back to the worklist upon success.
3732  DAGCombinerInfo &DCI) const;
3733 
3734  /// Helper wrapper around SimplifyDemandedBits.
3735  /// Adds Op back to the worklist upon success.
3737  const APInt &DemandedElts,
3738  DAGCombinerInfo &DCI) const;
3739 
3740  /// More limited version of SimplifyDemandedBits that can be used to "look
3741  /// through" ops that don't contribute to the DemandedBits/DemandedElts -
3742  /// bitwise ops etc.
3744  const APInt &DemandedElts,
3745  SelectionDAG &DAG,
3746  unsigned Depth = 0) const;
3747 
3748  /// Helper wrapper around SimplifyMultipleUseDemandedBits, demanding all
3749  /// elements.
3751  SelectionDAG &DAG,
3752  unsigned Depth = 0) const;
3753 
3754  /// Helper wrapper around SimplifyMultipleUseDemandedBits, demanding all
3755  /// bits from only some vector elements.
3757  const APInt &DemandedElts,
3758  SelectionDAG &DAG,
3759  unsigned Depth = 0) const;
3760 
3761  /// Look at Vector Op. At this point, we know that only the DemandedElts
3762  /// elements of the result of Op are ever used downstream. If we can use
3763  /// this information to simplify Op, create a new simplified DAG node and
3764  /// return true, storing the original and new nodes in TLO.
3765  /// Otherwise, analyze the expression and return a mask of KnownUndef and
3766  /// KnownZero elements for the expression (used to simplify the caller).
3767  /// The KnownUndef/Zero elements may only be accurate for those bits
3768  /// in the DemandedMask.
3769  /// \p AssumeSingleUse When this parameter is true, this function will
3770  /// attempt to simplify \p Op even if there are multiple uses.
3771  /// Callers are responsible for correctly updating the DAG based on the
3772  /// results of this function, because simply replacing replacing TLO.Old
3773  /// with TLO.New will be incorrect when this parameter is true and TLO.Old
3774  /// has multiple uses.
3775  bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedEltMask,
3776  APInt &KnownUndef, APInt &KnownZero,
3777  TargetLoweringOpt &TLO, unsigned Depth = 0,
3778  bool AssumeSingleUse = false) const;
3779 
3780  /// Helper wrapper around SimplifyDemandedVectorElts.
3781  /// Adds Op back to the worklist upon success.
3782  bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedElts,
3783  DAGCombinerInfo &DCI) const;
3784 
3785  /// Return true if the target supports simplifying demanded vector elements by
3786  /// converting them to undefs.
3787  virtual bool
3789  const TargetLoweringOpt &TLO) const {
3790  return true;
3791  }
3792 
3793  /// Determine which of the bits specified in Mask are known to be either zero
3794  /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
3795  /// argument allows us to only collect the known bits that are shared by the
3796  /// requested vector elements.
3797  virtual void computeKnownBitsForTargetNode(const SDValue Op,
3798  KnownBits &Known,
3799  const APInt &DemandedElts,
3800  const SelectionDAG &DAG,
3801  unsigned Depth = 0) const;
3802 
3803  /// Determine which of the bits specified in Mask are known to be either zero
3804  /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
3805  /// argument allows us to only collect the known bits that are shared by the
3806  /// requested vector elements. This is for GISel.
3807  virtual void computeKnownBitsForTargetInstr(GISelKnownBits &Analysis,
3808  Register R, KnownBits &Known,
3809  const APInt &DemandedElts,
3810  const MachineRegisterInfo &MRI,
3811  unsigned Depth = 0) const;
3812 
3813  /// Determine the known alignment for the pointer value \p R. This is can
3814  /// typically be inferred from the number of low known 0 bits. However, for a
3815  /// pointer with a non-integral address space, the alignment value may be
3816  /// independent from the known low bits.
3818  Register R,
3819  const MachineRegisterInfo &MRI,
3820  unsigned Depth = 0) const;
3821 
3822  /// Determine which of the bits of FrameIndex \p FIOp are known to be 0.
3823  /// Default implementation computes low bits based on alignment
3824  /// information. This should preserve known bits passed into it.
3825  virtual void computeKnownBitsForFrameIndex(int FIOp,
3826  KnownBits &Known,
3827  const MachineFunction &MF) const;
3828 
3829  /// This method can be implemented by targets that want to expose additional
3830  /// information about sign bits to the DAG Combiner. The DemandedElts
3831  /// argument allows us to only collect the minimum sign bits that are shared
3832  /// by the requested vector elements.
3833  virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
3834  const APInt &DemandedElts,
3835  const SelectionDAG &DAG,
3836  unsigned Depth = 0) const;
3837 
3838  /// This method can be implemented by targets that want to expose additional
3839  /// information about sign bits to GlobalISel combiners. The DemandedElts
3840  /// argument allows us to only collect the minimum sign bits that are shared
3841  /// by the requested vector elements.
3842  virtual unsigned computeNumSignBitsForTargetInstr(GISelKnownBits &Analysis,
3843  Register R,
3844  const APInt &DemandedElts,
3845  const MachineRegisterInfo &MRI,
3846  unsigned Depth = 0) const;
3847 
3848  /// Attempt to simplify any target nodes based on the demanded vector
3849  /// elements, returning true on success. Otherwise, analyze the expression and
3850  /// return a mask of KnownUndef and KnownZero elements for the expression
3851  /// (used to simplify the caller). The KnownUndef/Zero elements may only be
3852  /// accurate for those bits in the DemandedMask.
3854  SDValue Op, const APInt &DemandedElts, APInt &KnownUndef,
3855  APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth = 0) const;
3856 
3857  /// Attempt to simplify any target nodes based on the demanded bits/elts,
3858  /// returning true on success. Otherwise, analyze the
3859  /// expression and return a mask of KnownOne and KnownZero bits for the
3860  /// expression (used to simplify the caller). The KnownZero/One bits may only
3861  /// be accurate for those bits in the Demanded masks.
3863  const APInt &DemandedBits,
3864  const APInt &DemandedElts,
3865  KnownBits &Known,
3866  TargetLoweringOpt &TLO,
3867  unsigned Depth = 0) const;
3868 
3869  /// More limited version of SimplifyDemandedBits that can be used to "look
3870  /// through" ops that don't contribute to the DemandedBits/DemandedElts -
3871  /// bitwise ops etc.
3873  SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
3874  SelectionDAG &DAG, unsigned Depth) const;
3875 
3876  /// Return true if this function can prove that \p Op is never poison
3877  /// and, if \p PoisonOnly is false, does not have undef bits. The DemandedElts
3878  /// argument limits the check to the requested vector elements.
3880  SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
3881  bool PoisonOnly, unsigned Depth) const;
3882 
3883  /// Return true if Op can create undef or poison from non-undef & non-poison
3884  /// operands. The DemandedElts argument limits the check to the requested
3885  /// vector elements.
3886  virtual bool
3887  canCreateUndefOrPoisonForTargetNode(SDValue Op, const APInt &DemandedElts,
3888  const SelectionDAG &DAG, bool PoisonOnly,
3889  bool ConsiderFlags, unsigned Depth) const;
3890 
3891  /// Tries to build a legal vector shuffle using the provided parameters
3892  /// or equivalent variations. The Mask argument maybe be modified as the
3893  /// function tries different variations.
3894  /// Returns an empty SDValue if the operation fails.
3897  SelectionDAG &DAG) const;
3898 
3899  /// This method returns the constant pool value that will be loaded by LD.
3900  /// NOTE: You must check for implicit extensions of the constant by LD.
3901  virtual const Constant *getTargetConstantFromLoad(LoadSDNode *LD) const;
3902 
3903  /// If \p SNaN is false, \returns true if \p Op is known to never be any
3904  /// NaN. If \p sNaN is true, returns if \p Op is known to never be a signaling
3905  /// NaN.
3907  const SelectionDAG &DAG,
3908  bool SNaN = false,
3909  unsigned Depth = 0) const;
3910 
3911  /// Return true if vector \p Op has the same value across all \p DemandedElts,
3912  /// indicating any elements which may be undef in the output \p UndefElts.
3913  virtual bool isSplatValueForTargetNode(SDValue Op, const APInt &DemandedElts,
3914  APInt &UndefElts,
3915  unsigned Depth = 0) const;
3916 
3917  /// Returns true if the given Opc is considered a canonical constant for the
3918  /// target, which should not be transformed back into a BUILD_VECTOR.
3920  return Op.getOpcode() == ISD::SPLAT_VECTOR;
3921  }
3922 
3924  void *DC; // The DAG Combiner object.
3927 
3928  public:
3930 
3931  DAGCombinerInfo(SelectionDAG &dag, CombineLevel level, bool cl, void *dc)
3932  : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
3933 
3934  bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
3936  bool isAfterLegalizeDAG() const { return Level >= AfterLegalizeDAG; }
3938  bool isCalledByLegalizer() const { return CalledByLegalizer; }
3939 
3940  void AddToWorklist(SDNode *N);
3941  SDValue CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo = true);
3942  SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
3943  SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
3944 
3946 
3947  void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
3948  };
3949 
3950  /// Return if the N is a constant or constant vector equal to the true value
3951  /// from getBooleanContents().
3952  bool isConstTrueVal(SDValue N) const;
3953 
3954  /// Return if the N is a constant or constant vector equal to the false value
3955  /// from getBooleanContents().
3956  bool isConstFalseVal(SDValue N) const;
3957 
3958  /// Return if \p N is a True value when extended to \p VT.
3959  bool isExtendedTrueVal(const ConstantSDNode *N, EVT VT, bool SExt) const;
3960 
3961  /// Try to simplify a setcc built with the specified operands and cc. If it is
3962  /// unable to simplify it, return a null SDValue.
3964  bool foldBooleans, DAGCombinerInfo &DCI,
3965  const SDLoc &dl) const;
3966 
3967  // For targets which wrap address, unwrap for analysis.
3968  virtual SDValue unwrapAddress(SDValue N) const { return N; }
3969 
3970  /// Returns true (and the GlobalValue and the offset) if the node is a
3971  /// GlobalAddress + offset.
3972  virtual bool
3973  isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
3974 
3975  /// This method will be invoked for all target nodes and for any
3976  /// target-independent nodes that the target has registered with invoke it
3977  /// for.
3978  ///
3979  /// The semantics are as follows:
3980  /// Return Value:
3981  /// SDValue.Val == 0 - No change was made
3982  /// SDValue.Val == N - N was replaced, is dead, and is already handled.
3983  /// otherwise - N should be replaced by the returned Operand.
3984  ///
3985  /// In addition, methods provided by DAGCombinerInfo may be used to perform
3986  /// more complex transformations.
3987  ///
3988  virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
3989 
3990  /// Return true if it is profitable to move this shift by a constant amount
3991  /// through its operand, adjusting any immediate operands as necessary to
3992  /// preserve semantics. This transformation may not be desirable if it
3993  /// disrupts a particularly auspicious target-specific tree (e.g. bitfield
3994  /// extraction in AArch64). By default, it returns true.
3995  ///
3996  /// @param N the shift node
3997  /// @param Level the current DAGCombine legalization level.
3999  CombineLevel Level) const {
4000  return true;
4001  }
4002 
4003  /// Return true if it is profitable to combine an XOR of a logical shift
4004  /// to create a logical shift of NOT. This transformation may not be desirable
4005  /// if it disrupts a particularly auspicious target-specific tree (e.g.
4006  /// BIC on ARM/AArch64). By default, it returns true.
4007  virtual bool isDesirableToCommuteXorWithShift(const SDNode *N) const {
4008  return true;
4009  }
4010 
4011  /// Return true if the target has native support for the specified value type
4012  /// and it is 'desirable' to use the type for the given node type. e.g. On x86
4013  /// i16 is legal, but undesirable since i16 instruction encodings are longer
4014  /// and some i16 instructions are slow.
4015  virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
4016  // By default, assume all legal types are desirable.
4017  return isTypeLegal(VT);
4018  }
4019 
4020  /// Return true if it is profitable for dag combiner to transform a floating
4021  /// point op of specified opcode to a equivalent op of an integer
4022  /// type. e.g. f32 load -> i32 load can be profitable on ARM.
4023  virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
4024  EVT /*VT*/) const {
4025  return false;
4026  }
4027 
4028  /// This method query the target whether it is beneficial for dag combiner to
4029  /// promote the specified node. If true, it should return the desired
4030  /// promotion type by reference.
4031  virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
4032  return false;
4033  }
4034 
4035  /// Return true if the target supports swifterror attribute. It optimizes
4036  /// loads and stores to reading and writing a specific register.
4037  virtual bool supportSwiftError() const {
4038  return false;
4039  }
4040 
4041  /// Return true if the target supports that a subset of CSRs for the given
4042  /// machine function is handled explicitly via copies.
4043  virtual bool supportSplitCSR(MachineFunction *MF) const {
4044  return false;
4045  }
4046 
4047  /// Return true if the target supports kcfi operand bundles.
4048  virtual bool supportKCFIBundles() const { return false; }
4049 
4050  /// Perform necessary initialization to handle a subset of CSRs explicitly
4051  /// via copies. This function is called at the beginning of instruction
4052  /// selection.
4053  virtual void initializeSplitCSR(MachineBasicBlock *Entry) const {
4054  llvm_unreachable("Not Implemented");
4055  }
4056 
4057  /// Insert explicit copies in entry and exit blocks. We copy a subset of
4058  /// CSRs to virtual registers in the entry block, and copy them back to
4059  /// physical registers in the exit blocks. This function is called at the end
4060  /// of instruction selection.
4061  virtual void insertCopiesSplitCSR(
4062  MachineBasicBlock *Entry,
4063  const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
4064  llvm_unreachable("Not Implemented");
4065  }
4066 
4067  /// Return the newly negated expression if the cost is not expensive and
4068  /// set the cost in \p Cost to indicate that if it is cheaper or neutral to
4069  /// do the negation.
4071  bool LegalOps, bool OptForSize,
4072  NegatibleCost &Cost,
4073  unsigned Depth = 0) const;
4074 
4075  /// This is the helper function to return the newly negated expression only
4076  /// when the cost is cheaper.
4078  bool LegalOps, bool OptForSize,
4079  unsigned Depth = 0) const {
4081  SDValue Neg =
4082  getNegatedExpression(Op, DAG, LegalOps, OptForSize, Cost, Depth);
4083  if (Neg && Cost == NegatibleCost::Cheaper)
4084  return Neg;
4085  // Remove the new created node to avoid the side effect to the DAG.
4086  if (Neg && Neg->use_empty())
4087  DAG.RemoveDeadNode(Neg.getNode());
4088  return SDValue();
4089  }
4090 
4091  /// This is the helper function to return the newly negated expression if
4092  /// the cost is not expensive.
4094  bool OptForSize, unsigned Depth = 0) const {
4096  return getNegatedExpression(Op, DAG, LegalOps, OptForSize, Cost, Depth);
4097  }
4098 
4099  //===--------------------------------------------------------------------===//
4100  // Lowering methods - These methods must be implemented by targets so that
4101  // the SelectionDAGBuilder code knows how to lower these.
4102  //
4103 
4104  /// Target-specific splitting of values into parts that fit a register
4105  /// storing a legal type
4107  SelectionDAG & DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
4108  unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
4109  return false;
4110  }
4111 
4112  /// Allows the target to handle physreg-carried dependency
4113  /// in target-specific way. Used from the ScheduleDAGSDNodes to decide whether
4114  /// to add the edge to the dependency graph.
4115  /// Def - input: Selection DAG node defininfg physical register
4116  /// User - input: Selection DAG node using physical register
4117  /// Op - input: Number of User operand
4118  /// PhysReg - inout: set to the physical register if the edge is
4119  /// necessary, unchanged otherwise
4120  /// Cost - inout: physical register copy cost.
4121  /// Returns 'true' is the edge is necessary, 'false' otherwise
4122  virtual bool checkForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
4123  const TargetRegisterInfo *TRI,
4124  const TargetInstrInfo *TII,
4125  unsigned &PhysReg, int &Cost) const {
4126  return false;
4127  }
4128 
4129  /// Target-specific combining of register parts into its original value
4130  virtual SDValue
4132  const SDValue *Parts, unsigned NumParts,
4133  MVT PartVT, EVT ValueVT,
4134  std::optional<CallingConv::ID> CC) const {
4135  return SDValue();
4136  }
4137 
4138  /// This hook must be implemented to lower the incoming (formal) arguments,
4139  /// described by the Ins array, into the specified DAG. The implementation
4140  /// should fill in the InVals array with legal-type argument values, and
4141  /// return the resulting token chain value.
4143  SDValue /*Chain*/, CallingConv::ID /*CallConv*/, bool /*isVarArg*/,
4144  const SmallVectorImpl<ISD::InputArg> & /*Ins*/, const SDLoc & /*dl*/,
4145  SelectionDAG & /*DAG*/, SmallVectorImpl<SDValue> & /*InVals*/) const {
4146  llvm_unreachable("Not Implemented");
4147  }
4148 
4149  /// This structure contains all information that is necessary for lowering
4150  /// calls. It is passed to TLI::LowerCallTo when the SelectionDAG builder
4151  /// needs to lower a call, and targets will see this struct in their LowerCall
4152  /// implementation.
4155  Type *RetTy = nullptr;
4156  bool RetSExt : 1;
4157  bool RetZExt : 1;
4158  bool IsVarArg : 1;
4159  bool IsInReg : 1;
4160  bool DoesNotReturn : 1;
4162  bool IsConvergent : 1;
4163  bool IsPatchPoint : 1;
4164  bool IsPreallocated : 1;
4165  bool NoMerge : 1;
4166 
4167  // IsTailCall should be modified by implementations of
4168  // TargetLowering::LowerCall that perform tail call conversions.
4169  bool IsTailCall = false;
4170 
4171  // Is Call lowering done post SelectionDAG type legalization.
4173 
4174  unsigned NumFixedArgs = -1;
4180  const CallBase *CB = nullptr;
4185  const ConstantInt *CFIType = nullptr;
4186 
4191  DAG(DAG) {}
4192 
4194  DL = dl;
4195  return *this;
4196  }
4197 
4199  Chain = InChain;
4200  return *this;
4201  }
4202 
4203  // setCallee with target/module-specific attributes
4205  SDValue Target, ArgListTy &&ArgsList) {
4206  RetTy = ResultType;
4207  Callee = Target;
4208  CallConv = CC;
4209  NumFixedArgs = ArgsList.size();
4210  Args = std::move(ArgsList);
4211 
4213  &(DAG.getMachineFunction()), CC, Args);
4214  return *this;
4215  }
4216 
4218  SDValue Target, ArgListTy &&ArgsList) {
4219  RetTy = ResultType;
4220  Callee = Target;
4221  CallConv = CC;
4222  NumFixedArgs = ArgsList.size();
4223  Args = std::move(ArgsList);
4224  return *this;
4225  }
4226 
4228  SDValue Target, ArgListTy &&ArgsList,
4229  const CallBase &Call) {
4230  RetTy = ResultType;
4231 
4232  IsInReg = Call.hasRetAttr(Attribute::InReg);
4233  DoesNotReturn =
4234  Call.doesNotReturn() ||
4235  (!isa<InvokeInst>(Call) && isa<UnreachableInst>(Call.getNextNode()));
4236  IsVarArg = FTy->isVarArg();
4237  IsReturnValueUsed = !Call.use_empty();
4238  RetSExt = Call.hasRetAttr(Attribute::SExt);
4239  RetZExt = Call.hasRetAttr(Attribute::ZExt);
4240  NoMerge = Call.hasFnAttr(Attribute::NoMerge);
4241 
4242  Callee = Target;
4243 
4244  CallConv = Call.getCallingConv();
4245  NumFixedArgs = FTy->getNumParams();
4246  Args = std::move(ArgsList);
4247 
4248  CB = &Call;
4249 
4250  return *this;
4251  }
4252 
4254  IsInReg = Value;
4255  return *this;
4256  }
4257 
4259  DoesNotReturn = Value;
4260  return *this;
4261  }
4262 
4264  IsVarArg = Value;
4265  return *this;
4266  }
4267 
4269  IsTailCall = Value;
4270  return *this;
4271  }
4272 
4275  return *this;
4276  }
4277 
4279  IsConvergent = Value;
4280  return *this;
4281  }
4282 
4284  RetSExt = Value;
4285  return *this;
4286  }
4287 
4289  RetZExt = Value;
4290  return *this;
4291  }
4292 
4294  IsPatchPoint = Value;
4295  return *this;
4296  }
4297 
4300  return *this;
4301  }
4302 
4305  return *this;
4306  }
4307 
4309  CFIType = Type;
4310  return *this;
4311  }
4312 
4314  return Args;
4315  }
4316  };
4317 
4318  /// This structure is used to pass arguments to makeLibCall function.
4320  // By passing type list before soften to makeLibCall, the target hook
4321  // shouldExtendTypeInLibCall can get the original type before soften.
4324  bool IsSExt : 1;
4325  bool DoesNotReturn : 1;
4328  bool IsSoften : 1;
4329 
4333 
4335  IsSExt = Value;
4336  return *this;
4337  }
4338 
4340  DoesNotReturn = Value;
4341  return *this;
4342  }
4343 
4346  return *this;
4347  }
4348 
4351  return *this;
4352  }
4353 
4355  bool Value = true) {
4356  OpsVTBeforeSoften = OpsVT;
4357  RetVTBeforeSoften = RetVT;
4358  IsSoften = Value;
4359  return *this;
4360  }
4361  };
4362 
4363  /// This function lowers an abstract call to a function into an actual call.
4364  /// This returns a pair of operands. The first element is the return value
4365  /// for the function (if RetTy is not VoidTy). The second element is the
4366  /// outgoing token chain. It calls LowerCall to do the actual lowering.
4367  std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
4368 
4369  /// This hook must be implemented to lower calls into the specified
4370  /// DAG. The outgoing arguments to the call are described by the Outs array,
4371  /// and the values to be returned by the call are described by the Ins
4372  /// array. The implementation should fill in the InVals array with legal-type
4373  /// return values from the call, and return the resulting token chain value.
4374  virtual SDValue
4376  SmallVectorImpl<SDValue> &/*InVals*/) const {
4377  llvm_unreachable("Not Implemented");
4378  }
4379 
4380  /// Target-specific cleanup for formal ByVal parameters.
4381  virtual void HandleByVal(CCState *, unsigned &, Align) const {}
4382 
4383  /// This hook should be implemented to check whether the return values
4384  /// described by the Outs array can fit into the return registers. If false
4385  /// is returned, an sret-demotion is performed.
4386  virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
4387  MachineFunction &/*MF*/, bool /*isVarArg*/,
4388  const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
4389  LLVMContext &/*Context*/) const
4390  {
4391  // Return true by default to get preexisting behavior.
4392  return true;
4393  }
4394 
4395  /// This hook must be implemented to lower outgoing return values, described
4396  /// by the Outs array, into the specified DAG. The implementation should
4397  /// return the resulting token chain value.
4398  virtual SDValue LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
4399  bool /*isVarArg*/,
4400  const SmallVectorImpl<ISD::OutputArg> & /*Outs*/,
4401  const SmallVectorImpl<SDValue> & /*OutVals*/,
4402  const SDLoc & /*dl*/,
4403  SelectionDAG & /*DAG*/) const {
4404  llvm_unreachable("Not Implemented");
4405  }
4406 
4407  /// Return true if result of the specified node is used by a return node
4408  /// only. It also compute and return the input chain for the tail call.
4409  ///
4410  /// This is used to determine whether it is possible to codegen a libcall as
4411  /// tail call at legalization time.
4412  virtual bool isUsedByReturnOnly(SDNode *, SDValue &/*Chain*/) const {
4413  return false;
4414  }
4415 
4416  /// Return true if the target may be able emit the call instruction as a tail
4417  /// call. This is used by optimization passes to determine if it's profitable
4418  /// to duplicate return instructions to enable tailcall optimization.
4419  virtual bool mayBeEmittedAsTailCall(const CallInst *) const {
4420  return false;
4421  }
4422 
4423  /// Return the builtin name for the __builtin___clear_cache intrinsic
4424  /// Default is to invoke the clear cache library call
4425  virtual const char * getClearCacheBuiltinName() const {
4426  return "__clear_cache";
4427  }
4428 
4429  /// Return the register ID of the name passed in. Used by named register
4430  /// global variables extension. There is no target-independent behaviour
4431  /// so the default action is to bail.
4432  virtual Register getRegisterByName(const char* RegName, LLT Ty,
4433  const MachineFunction &MF) const {
4434  report_fatal_error("Named registers not implemented for this target");
4435  }
4436 
4437  /// Return the type that should be used to zero or sign extend a
4438  /// zeroext/signext integer return value. FIXME: Some C calling conventions
4439  /// require the return type to be promoted, but this is not true all the time,
4440  /// e.g. i1/i8/i16 on x86/x86_64. It is also not necessary for non-C calling
4441  /// conventions. The frontend should handle this and include all of the
4442  /// necessary information.
4444  ISD::NodeType /*ExtendKind*/) const {
4445  EVT MinVT = getRegisterType(Context, MVT::i32);
4446  return VT.bitsLT(MinVT) ? MinVT : VT;
4447  }
4448 
4449  /// For some targets, an LLVM struct type must be broken down into multiple
4450  /// simple types, but the calling convention specifies that the entire struct
4451  /// must be passed in a block of consecutive registers.
4452  virtual bool
4454  bool isVarArg,
4455  const DataLayout &DL) const {
4456  return false;
4457  }
4458 
4459  /// For most targets, an LLVM type must be broken down into multiple
4460  /// smaller types. Usually the halves are ordered according to the endianness
4461  /// but for some platform that would break. So this method will default to
4462  /// matching the endianness but can be overridden.
4463  virtual bool
4465  return DL.isLittleEndian();
4466  }
4467 
4468  /// Returns a 0 terminated array of registers that can be safely used as
4469  /// scratch registers.
4471  return nullptr;
4472  }
4473 
4474  /// This callback is used to prepare for a volatile or atomic load.
4475  /// It takes a chain node as input and returns the chain for the load itself.
4476  ///
4477  /// Having a callback like this is necessary for targets like SystemZ,
4478  /// which allows a CPU to reuse the result of a previous load indefinitely,
4479  /// even if a cache-coherent store is performed by another CPU. The default
4480  /// implementation does nothing.
4482  SelectionDAG &DAG) const {
4483  return Chain;
4484  }
4485 
4486  /// Should SelectionDAG lower an atomic store of the given kind as a normal
4487  /// StoreSDNode (as opposed to an AtomicSDNode)? NOTE: The intention is to
4488  /// eventually migrate all targets to the using StoreSDNodes, but porting is
4489  /// being done target at a time.
4490  virtual bool lowerAtomicStoreAsStoreSDNode(const StoreInst &SI) const {
4491  assert(SI.isAtomic() && "violated precondition");
4492  return false;
4493  }
4494 
4495  /// Should SelectionDAG lower an atomic load of the given kind as a normal
4496  /// LoadSDNode (as opposed to an AtomicSDNode)? NOTE: The intention is to
4497  /// eventually migrate all targets to the using LoadSDNodes, but porting is
4498  /// being done target at a time.
4499  virtual bool lowerAtomicLoadAsLoadSDNode(const LoadInst &LI) const {
4500  assert(LI.isAtomic() && "violated precondition");
4501  return false;
4502  }
4503 
4504 
4505  /// This callback is invoked by the type legalizer to legalize nodes with an
4506  /// illegal operand type but legal result types. It replaces the
4507  /// LowerOperation callback in the type Legalizer. The reason we can not do
4508  /// away with LowerOperation entirely is that LegalizeDAG isn't yet ready to
4509  /// use this callback.
4510  ///
4511  /// TODO: Consider merging with ReplaceNodeResults.
4512  ///
4513  /// The target places new result values for the node in Results (their number
4514  /// and types must exactly match those of the original return values of
4515  /// the node), or leaves Results empty, which indicates that the node is not
4516  /// to be custom lowered after all.
4517  /// The default implementation calls LowerOperation.
4518  virtual void LowerOperationWrapper(SDNode *N,
4520  SelectionDAG &DAG) const;
4521 
4522  /// This callback is invoked for operations that are unsupported by the
4523  /// target, which are registered to use 'custom' lowering, and whose defined
4524  /// values are all legal. If the target has no operations that require custom
4525  /// lowering, it need not implement this. The default implementation of this
4526  /// aborts.
4527  virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
4528 
4529  /// This callback is invoked when a node result type is illegal for the
4530  /// target, and the operation was registered to use 'custom' lowering for that
4531  /// result type. The target places new result values for the node in Results
4532  /// (their number and types must exactly match those of the original return
4533  /// values of the node), or leaves Results empty, which indicates that the
4534  /// node is not to be custom lowered after all.
4535  ///
4536  /// If the target has no operations that require custom lowering, it need not
4537  /// implement this. The default implementation aborts.
4538  virtual void ReplaceNodeResults(SDNode * /*N*/,
4539  SmallVectorImpl<SDValue> &/*Results*/,
4540  SelectionDAG &/*DAG*/) const {
4541  llvm_unreachable("ReplaceNodeResults not implemented for this target!");
4542  }
4543 
4544  /// This method returns the name of a target specific DAG node.
4545  virtual const char *getTargetNodeName(unsigned Opcode) const;
4546 
4547  /// This method returns a target specific FastISel object, or null if the
4548  /// target does not support "fast" ISel.
4550  const TargetLibraryInfo *) const {
4551  return nullptr;
4552  }
4553 
4555  SelectionDAG &DAG) const;
4556 
4557  //===--------------------------------------------------------------------===//
4558  // Inline Asm Support hooks
4559  //
4560