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