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