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