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