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