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