LLVM  9.0.0svn
TargetLowering.h
Go to the documentation of this file.
1 //===- llvm/CodeGen/TargetLowering.h - Target Lowering Info -----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file describes how to lower LLVM code to machine code. This has two
11 /// main components:
12 ///
13 /// 1. Which ValueTypes are natively supported by the target.
14 /// 2. Which operations are supported for supported ValueTypes.
15 /// 3. Cost thresholds for alternative implementations of certain operations.
16 ///
17 /// In addition it has a few other components, like information about FP
18 /// immediates.
19 ///
20 //===----------------------------------------------------------------------===//
21 
22 #ifndef LLVM_CODEGEN_TARGETLOWERING_H
23 #define LLVM_CODEGEN_TARGETLOWERING_H
24 
25 #include "llvm/ADT/APInt.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringRef.h"
39 #include "llvm/IR/Attributes.h"
40 #include "llvm/IR/CallSite.h"
41 #include "llvm/IR/CallingConv.h"
42 #include "llvm/IR/DataLayout.h"
43 #include "llvm/IR/DerivedTypes.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/IRBuilder.h"
46 #include "llvm/IR/InlineAsm.h"
47 #include "llvm/IR/Instruction.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/Type.h"
50 #include "llvm/MC/MCRegisterInfo.h"
52 #include "llvm/Support/Casting.h"
56 #include <algorithm>
57 #include <cassert>
58 #include <climits>
59 #include <cstdint>
60 #include <iterator>
61 #include <map>
62 #include <string>
63 #include <utility>
64 #include <vector>
65 
66 namespace llvm {
67 
68 class BranchProbability;
69 class CCState;
70 class CCValAssign;
71 class Constant;
72 class FastISel;
73 class FunctionLoweringInfo;
74 class GlobalValue;
75 class IntrinsicInst;
76 struct KnownBits;
77 class LLVMContext;
78 class MachineBasicBlock;
79 class MachineFunction;
80 class MachineInstr;
81 class MachineJumpTableInfo;
82 class MachineLoop;
83 class MachineRegisterInfo;
84 class MCContext;
85 class MCExpr;
86 class Module;
87 class TargetRegisterClass;
88 class TargetLibraryInfo;
89 class TargetRegisterInfo;
90 class Value;
91 
92 namespace Sched {
93 
94  enum Preference {
95  None, // No preference
96  Source, // Follow source order.
97  RegPressure, // Scheduling for lowest register pressure.
98  Hybrid, // Scheduling for both latency and register pressure.
99  ILP, // Scheduling for ILP in low register pressure mode.
100  VLIW // Scheduling for VLIW targets.
101  };
102 
103 } // end namespace Sched
104 
105 /// This base class for TargetLowering contains the SelectionDAG-independent
106 /// parts that can be used from the rest of CodeGen.
108 public:
109  /// This enum indicates whether operations are valid for a target, and if not,
110  /// what action should be used to make them valid.
111  enum LegalizeAction : uint8_t {
112  Legal, // The target natively supports this operation.
113  Promote, // This operation should be executed in a larger type.
114  Expand, // Try to expand this to other ops, otherwise use a libcall.
115  LibCall, // Don't try to expand this to other ops, always use a libcall.
116  Custom // Use the LowerOperation hook to implement custom lowering.
117  };
118 
119  /// This enum indicates whether a types are legal for a target, and if not,
120  /// what action should be used to make them valid.
121  enum LegalizeTypeAction : uint8_t {
122  TypeLegal, // The target natively supports this type.
123  TypePromoteInteger, // Replace this integer with a larger one.
124  TypeExpandInteger, // Split this integer into two of half the size.
125  TypeSoftenFloat, // Convert this float to a same size integer type,
126  // if an operation is not supported in target HW.
127  TypeExpandFloat, // Split this float into two of half the size.
128  TypeScalarizeVector, // Replace this one-element vector with its element.
129  TypeSplitVector, // Split this vector into two of half the size.
130  TypeWidenVector, // This vector should be widened into a larger vector.
131  TypePromoteFloat // Replace this float with a larger one.
132  };
133 
134  /// LegalizeKind holds the legalization kind that needs to happen to EVT
135  /// in order to type-legalize it.
136  using LegalizeKind = std::pair<LegalizeTypeAction, EVT>;
137 
138  /// Enum that describes how the target represents true/false values.
140  UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
141  ZeroOrOneBooleanContent, // All bits zero except for bit 0.
142  ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
143  };
144 
145  /// Enum that describes what type of support for selects the target has.
147  ScalarValSelect, // The target supports scalar selects (ex: cmov).
148  ScalarCondVectorVal, // The target supports selects with a scalar condition
149  // and vector values (ex: cmov).
150  VectorMaskSelect // The target supports vector selects with a vector
151  // mask (ex: x86 blends).
152  };
153 
154  /// Enum that specifies what an atomic load/AtomicRMWInst is expanded
155  /// to, if at all. Exists because different targets have different levels of
156  /// support for these atomic instructions, and also have different options
157  /// w.r.t. what they should expand to.
158  enum class AtomicExpansionKind {
159  None, // Don't expand the instruction.
160  LLSC, // Expand the instruction into loadlinked/storeconditional; used
161  // by ARM/AArch64.
162  LLOnly, // Expand the (load) instruction into just a load-linked, which has
163  // greater atomic guarantees than a normal load.
164  CmpXChg, // Expand the instruction into cmpxchg; used by at least X86.
165  MaskedIntrinsic, // Use a target-specific intrinsic for the LL/SC loop.
166  };
167 
168  /// Enum that specifies when a multiplication should be expanded.
169  enum class MulExpansionKind {
170  Always, // Always expand the instruction.
171  OnlyLegalOrCustom, // Only expand when the resulting instructions are legal
172  // or custom.
173  };
174 
175  class ArgListEntry {
176  public:
177  Value *Val = nullptr;
179  Type *Ty = nullptr;
180  bool IsSExt : 1;
181  bool IsZExt : 1;
182  bool IsInReg : 1;
183  bool IsSRet : 1;
184  bool IsNest : 1;
185  bool IsByVal : 1;
186  bool IsInAlloca : 1;
187  bool IsReturned : 1;
188  bool IsSwiftSelf : 1;
189  bool IsSwiftError : 1;
190  uint16_t Alignment = 0;
191 
193  : IsSExt(false), IsZExt(false), IsInReg(false), IsSRet(false),
194  IsNest(false), IsByVal(false), IsInAlloca(false), IsReturned(false),
195  IsSwiftSelf(false), IsSwiftError(false) {}
196 
197  void setAttributes(const CallBase *Call, unsigned ArgIdx);
198 
199  void setAttributes(ImmutableCallSite *CS, unsigned ArgIdx) {
200  return setAttributes(cast<CallBase>(CS->getInstruction()), ArgIdx);
201  }
202  };
203  using ArgListTy = std::vector<ArgListEntry>;
204 
205  virtual void markLibCallAttributes(MachineFunction *MF, unsigned CC,
206  ArgListTy &Args) const {};
207 
209  switch (Content) {
210  case UndefinedBooleanContent:
211  // Extend by adding rubbish bits.
212  return ISD::ANY_EXTEND;
213  case ZeroOrOneBooleanContent:
214  // Extend by adding zero bits.
215  return ISD::ZERO_EXTEND;
216  case ZeroOrNegativeOneBooleanContent:
217  // Extend by copying the sign bit.
218  return ISD::SIGN_EXTEND;
219  }
220  llvm_unreachable("Invalid content kind");
221  }
222 
223  /// NOTE: The TargetMachine owns TLOF.
224  explicit TargetLoweringBase(const TargetMachine &TM);
225  TargetLoweringBase(const TargetLoweringBase &) = delete;
226  TargetLoweringBase &operator=(const TargetLoweringBase &) = delete;
227  virtual ~TargetLoweringBase() = default;
228 
229 protected:
230  /// Initialize all of the actions to default values.
231  void initActions();
232 
233 public:
234  const TargetMachine &getTargetMachine() const { return TM; }
235 
236  virtual bool useSoftFloat() const { return false; }
237 
238  /// Return the pointer type for the given address space, defaults to
239  /// the pointer type from the data layout.
240  /// FIXME: The default needs to be removed once all the code is updated.
241  virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS = 0) const {
243  }
244 
245  /// Return the in-memory pointer type for the given address space, defaults to
246  /// the pointer type from the data layout. FIXME: The default needs to be
247  /// removed once all the code is updated.
248  MVT getPointerMemTy(const DataLayout &DL, uint32_t AS = 0) const {
250  }
251 
252  /// Return the type for frame index, which is determined by
253  /// the alloca address space specified through the data layout.
254  MVT getFrameIndexTy(const DataLayout &DL) const {
255  return getPointerTy(DL, DL.getAllocaAddrSpace());
256  }
257 
258  /// Return the type for operands of fence.
259  /// TODO: Let fence operands be of i32 type and remove this.
260  virtual MVT getFenceOperandTy(const DataLayout &DL) const {
261  return getPointerTy(DL);
262  }
263 
264  /// EVT is not used in-tree, but is used by out-of-tree target.
265  /// A documentation for this function would be nice...
266  virtual MVT getScalarShiftAmountTy(const DataLayout &, EVT) const;
267 
268  EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL,
269  bool LegalTypes = true) const;
270 
271  /// Returns the type to be used for the index operand of:
272  /// ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
273  /// ISD::INSERT_SUBVECTOR, and ISD::EXTRACT_SUBVECTOR
274  virtual MVT getVectorIdxTy(const DataLayout &DL) const {
275  return getPointerTy(DL);
276  }
277 
278  virtual bool isSelectSupported(SelectSupportKind /*kind*/) const {
279  return true;
280  }
281 
282  /// Return true if it is profitable to convert a select of FP constants into
283  /// a constant pool load whose address depends on the select condition. The
284  /// parameter may be used to differentiate a select with FP compare from
285  /// integer compare.
286  virtual bool reduceSelectOfFPConstantLoads(bool IsFPSetCC) const {
287  return true;
288  }
289 
290  /// Return true if multiple condition registers are available.
292  return HasMultipleConditionRegisters;
293  }
294 
295  /// Return true if the target has BitExtract instructions.
296  bool hasExtractBitsInsn() const { return HasExtractBitsInsn; }
297 
298  /// Return the preferred vector type legalization action.
301  // The default action for one element vectors is to scalarize
302  if (VT.getVectorNumElements() == 1)
303  return TypeScalarizeVector;
304  // The default action for an odd-width vector is to widen.
305  if (!VT.isPow2VectorType())
306  return TypeWidenVector;
307  // The default action for other vectors is to promote
308  return TypePromoteInteger;
309  }
310 
311  // There are two general methods for expanding a BUILD_VECTOR node:
312  // 1. Use SCALAR_TO_VECTOR on the defined scalar values and then shuffle
313  // them together.
314  // 2. Build the vector on the stack and then load it.
315  // If this function returns true, then method (1) will be used, subject to
316  // the constraint that all of the necessary shuffles are legal (as determined
317  // by isShuffleMaskLegal). If this function returns false, then method (2) is
318  // always used. The vector type, and the number of defined values, are
319  // provided.
320  virtual bool
322  unsigned DefinedValues) const {
323  return DefinedValues < 3;
324  }
325 
326  /// Return true if integer divide is usually cheaper than a sequence of
327  /// several shifts, adds, and multiplies for this target.
328  /// The definition of "cheaper" may depend on whether we're optimizing
329  /// for speed or for size.
330  virtual bool isIntDivCheap(EVT VT, AttributeList Attr) const { return false; }
331 
332  /// Return true if the target can handle a standalone remainder operation.
333  virtual bool hasStandaloneRem(EVT VT) const {
334  return true;
335  }
336 
337  /// Return true if SQRT(X) shouldn't be replaced with X*RSQRT(X).
338  virtual bool isFsqrtCheap(SDValue X, SelectionDAG &DAG) const {
339  // Default behavior is to replace SQRT(X) with X*RSQRT(X).
340  return false;
341  }
342 
343  /// Reciprocal estimate status values used by the functions below.
344  enum ReciprocalEstimate : int {
345  Unspecified = -1,
346  Disabled = 0,
348  };
349 
350  /// Return a ReciprocalEstimate enum value for a square root of the given type
351  /// based on the function's attributes. If the operation is not overridden by
352  /// the function's attributes, "Unspecified" is returned and target defaults
353  /// are expected to be used for instruction selection.
354  int getRecipEstimateSqrtEnabled(EVT VT, MachineFunction &MF) const;
355 
356  /// Return a ReciprocalEstimate enum value for a division of the given type
357  /// based on the function's attributes. If the operation is not overridden by
358  /// the function's attributes, "Unspecified" is returned and target defaults
359  /// are expected to be used for instruction selection.
360  int getRecipEstimateDivEnabled(EVT VT, MachineFunction &MF) const;
361 
362  /// Return the refinement step count for a square root of the given type based
363  /// on the function's attributes. If the operation is not overridden by
364  /// the function's attributes, "Unspecified" is returned and target defaults
365  /// are expected to be used for instruction selection.
366  int getSqrtRefinementSteps(EVT VT, MachineFunction &MF) const;
367 
368  /// Return the refinement step count for a division of the given type based
369  /// on the function's attributes. If the operation is not overridden by
370  /// the function's attributes, "Unspecified" is returned and target defaults
371  /// are expected to be used for instruction selection.
372  int getDivRefinementSteps(EVT VT, MachineFunction &MF) const;
373 
374  /// Returns true if target has indicated at least one type should be bypassed.
375  bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
376 
377  /// Returns map of slow types for division or remainder with corresponding
378  /// fast types
380  return BypassSlowDivWidths;
381  }
382 
383  /// Return true if Flow Control is an expensive operation that should be
384  /// avoided.
385  bool isJumpExpensive() const { return JumpIsExpensive; }
386 
387  /// Return true if selects are only cheaper than branches if the branch is
388  /// unlikely to be predicted right.
390  return PredictableSelectIsExpensive;
391  }
392 
393  /// If a branch or a select condition is skewed in one direction by more than
394  /// this factor, it is very likely to be predicted correctly.
395  virtual BranchProbability getPredictableBranchThreshold() const;
396 
397  /// Return true if the following transform is beneficial:
398  /// fold (conv (load x)) -> (load (conv*)x)
399  /// On architectures that don't natively support some vector loads
400  /// efficiently, casting the load to a smaller vector of larger types and
401  /// loading is more efficient, however, this can be undone by optimizations in
402  /// dag combiner.
403  virtual bool isLoadBitCastBeneficial(EVT LoadVT,
404  EVT BitcastVT) const {
405  // Don't do if we could do an indexed load on the original type, but not on
406  // the new one.
407  if (!LoadVT.isSimple() || !BitcastVT.isSimple())
408  return true;
409 
410  MVT LoadMVT = LoadVT.getSimpleVT();
411 
412  // Don't bother doing this if it's just going to be promoted again later, as
413  // doing so might interfere with other combines.
414  if (getOperationAction(ISD::LOAD, LoadMVT) == Promote &&
415  getTypeToPromoteTo(ISD::LOAD, LoadMVT) == BitcastVT.getSimpleVT())
416  return false;
417 
418  return true;
419  }
420 
421  /// Return true if the following transform is beneficial:
422  /// (store (y (conv x)), y*)) -> (store x, (x*))
423  virtual bool isStoreBitCastBeneficial(EVT StoreVT, EVT BitcastVT) const {
424  // Default to the same logic as loads.
425  return isLoadBitCastBeneficial(StoreVT, BitcastVT);
426  }
427 
428  /// Return true if it is expected to be cheaper to do a store of a non-zero
429  /// vector constant with the given size and type for the address space than to
430  /// store the individual scalar element constants.
431  virtual bool storeOfVectorConstantIsCheap(EVT MemVT,
432  unsigned NumElem,
433  unsigned AddrSpace) const {
434  return false;
435  }
436 
437  /// Allow store merging after legalization in addition to before legalization.
438  /// This may catch stores that do not exist earlier (eg, stores created from
439  /// intrinsics).
440  virtual bool mergeStoresAfterLegalization() const { return true; }
441 
442  /// Returns if it's reasonable to merge stores to MemVT size.
443  virtual bool canMergeStoresTo(unsigned AS, EVT MemVT,
444  const SelectionDAG &DAG) const {
445  return true;
446  }
447 
448  /// Return true if it is cheap to speculate a call to intrinsic cttz.
449  virtual bool isCheapToSpeculateCttz() const {
450  return false;
451  }
452 
453  /// Return true if it is cheap to speculate a call to intrinsic ctlz.
454  virtual bool isCheapToSpeculateCtlz() const {
455  return false;
456  }
457 
458  /// Return true if ctlz instruction is fast.
459  virtual bool isCtlzFast() const {
460  return false;
461  }
462 
463  /// Return true if it is safe to transform an integer-domain bitwise operation
464  /// into the equivalent floating-point operation. This should be set to true
465  /// if the target has IEEE-754-compliant fabs/fneg operations for the input
466  /// type.
467  virtual bool hasBitPreservingFPLogic(EVT VT) const {
468  return false;
469  }
470 
471  /// Return true if it is cheaper to split the store of a merged int val
472  /// from a pair of smaller values into multiple stores.
473  virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const {
474  return false;
475  }
476 
477  /// Return if the target supports combining a
478  /// chain like:
479  /// \code
480  /// %andResult = and %val1, #mask
481  /// %icmpResult = icmp %andResult, 0
482  /// \endcode
483  /// into a single machine instruction of a form like:
484  /// \code
485  /// cc = test %register, #mask
486  /// \endcode
487  virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
488  return false;
489  }
490 
491  /// Use bitwise logic to make pairs of compares more efficient. For example:
492  /// and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
493  /// This should be true when it takes more than one instruction to lower
494  /// setcc (cmp+set on x86 scalar), when bitwise ops are faster than logic on
495  /// condition bits (crand on PowerPC), and/or when reducing cmp+br is a win.
496  virtual bool convertSetCCLogicToBitwiseLogic(EVT VT) const {
497  return false;
498  }
499 
500  /// Return the preferred operand type if the target has a quick way to compare
501  /// integer values of the given size. Assume that any legal integer type can
502  /// be compared efficiently. Targets may override this to allow illegal wide
503  /// types to return a vector type if there is support to compare that type.
504  virtual MVT hasFastEqualityCompare(unsigned NumBits) const {
505  MVT VT = MVT::getIntegerVT(NumBits);
506  return isTypeLegal(VT) ? VT : MVT::INVALID_SIMPLE_VALUE_TYPE;
507  }
508 
509  /// Return true if the target should transform:
510  /// (X & Y) == Y ---> (~X & Y) == 0
511  /// (X & Y) != Y ---> (~X & Y) != 0
512  ///
513  /// This may be profitable if the target has a bitwise and-not operation that
514  /// sets comparison flags. A target may want to limit the transformation based
515  /// on the type of Y or if Y is a constant.
516  ///
517  /// Note that the transform will not occur if Y is known to be a power-of-2
518  /// because a mask and compare of a single bit can be handled by inverting the
519  /// predicate, for example:
520  /// (X & 8) == 8 ---> (X & 8) != 0
521  virtual bool hasAndNotCompare(SDValue Y) const {
522  return false;
523  }
524 
525  /// Return true if the target has a bitwise and-not operation:
526  /// X = ~A & B
527  /// This can be used to simplify select or other instructions.
528  virtual bool hasAndNot(SDValue X) const {
529  // If the target has the more complex version of this operation, assume that
530  // it has this operation too.
531  return hasAndNotCompare(X);
532  }
533 
534  /// There are two ways to clear extreme bits (either low or high):
535  /// Mask: x & (-1 << y) (the instcombine canonical form)
536  /// Shifts: x >> y << y
537  /// Return true if the variant with 2 variable shifts is preferred.
538  /// Return false if there is no preference.
540  // By default, let's assume that no one prefers shifts.
541  return false;
542  }
543 
544  /// Return true if it is profitable to fold a pair of shifts into a mask.
545  /// This is usually true on most targets. But some targets, like Thumb1,
546  /// have immediate shift instructions, but no immediate "and" instruction;
547  /// this makes the fold unprofitable.
549  CombineLevel Level) const {
550  return true;
551  }
552 
553  /// Should we tranform the IR-optimal check for whether given truncation
554  /// down into KeptBits would be truncating or not:
555  /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
556  /// Into it's more traditional form:
557  /// ((%x << C) a>> C) dstcond %x
558  /// Return true if we should transform.
559  /// Return false if there is no preference.
561  unsigned KeptBits) const {
562  // By default, let's assume that no one prefers shifts.
563  return false;
564  }
565 
566  /// Return true if the target wants to use the optimization that
567  /// turns ext(promotableInst1(...(promotableInstN(load)))) into
568  /// promotedInst1(...(promotedInstN(ext(load)))).
569  bool enableExtLdPromotion() const { return EnableExtLdPromotion; }
570 
571  /// Return true if the target can combine store(extractelement VectorTy,
572  /// Idx).
573  /// \p Cost[out] gives the cost of that transformation when this is true.
574  virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
575  unsigned &Cost) const {
576  return false;
577  }
578 
579  /// Return true if inserting a scalar into a variable element of an undef
580  /// vector is more efficiently handled by splatting the scalar instead.
581  virtual bool shouldSplatInsEltVarIndex(EVT) const {
582  return false;
583  }
584 
585  /// Return true if target always beneficiates from combining into FMA for a
586  /// given value type. This must typically return false on targets where FMA
587  /// takes more cycles to execute than FADD.
588  virtual bool enableAggressiveFMAFusion(EVT VT) const {
589  return false;
590  }
591 
592  /// Return the ValueType of the result of SETCC operations.
593  virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context,
594  EVT VT) const;
595 
596  /// Return the ValueType for comparison libcalls. Comparions libcalls include
597  /// floating point comparion calls, and Ordered/Unordered check calls on
598  /// floating point numbers.
599  virtual
600  MVT::SimpleValueType getCmpLibcallReturnType() const;
601 
602  /// For targets without i1 registers, this gives the nature of the high-bits
603  /// of boolean values held in types wider than i1.
604  ///
605  /// "Boolean values" are special true/false values produced by nodes like
606  /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
607  /// Not to be confused with general values promoted from i1. Some cpus
608  /// distinguish between vectors of boolean and scalars; the isVec parameter
609  /// selects between the two kinds. For example on X86 a scalar boolean should
610  /// be zero extended from i1, while the elements of a vector of booleans
611  /// should be sign extended from i1.
612  ///
613  /// Some cpus also treat floating point types the same way as they treat
614  /// vectors instead of the way they treat scalars.
615  BooleanContent getBooleanContents(bool isVec, bool isFloat) const {
616  if (isVec)
617  return BooleanVectorContents;
618  return isFloat ? BooleanFloatContents : BooleanContents;
619  }
620 
622  return getBooleanContents(Type.isVector(), Type.isFloatingPoint());
623  }
624 
625  /// Return target scheduling preference.
627  return SchedPreferenceInfo;
628  }
629 
630  /// Some scheduler, e.g. hybrid, can switch to different scheduling heuristics
631  /// for different nodes. This function returns the preference (or none) for
632  /// the given node.
634  return Sched::None;
635  }
636 
637  /// Return the register class that should be used for the specified value
638  /// type.
639  virtual const TargetRegisterClass *getRegClassFor(MVT VT) const {
640  const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
641  assert(RC && "This value type is not natively supported!");
642  return RC;
643  }
644 
645  /// Return the 'representative' register class for the specified value
646  /// type.
647  ///
648  /// The 'representative' register class is the largest legal super-reg
649  /// register class for the register class of the value type. For example, on
650  /// i386 the rep register class for i8, i16, and i32 are GR32; while the rep
651  /// register class is GR64 on x86_64.
652  virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
653  const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
654  return RC;
655  }
656 
657  /// Return the cost of the 'representative' register class for the specified
658  /// value type.
659  virtual uint8_t getRepRegClassCostFor(MVT VT) const {
660  return RepRegClassCostForVT[VT.SimpleTy];
661  }
662 
663  /// Return true if SHIFT instructions should be expanded to SHIFT_PARTS
664  /// instructions, and false if a library call is preferred (e.g for code-size
665  /// reasons).
666  virtual bool shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
667  return true;
668  }
669 
670  /// Return true if the target has native support for the specified value type.
671  /// This means that it has a register that directly holds it without
672  /// promotions or expansions.
673  bool isTypeLegal(EVT VT) const {
674  assert(!VT.isSimple() ||
675  (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
676  return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != nullptr;
677  }
678 
680  /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
681  /// that indicates how instruction selection should deal with the type.
682  LegalizeTypeAction ValueTypeActions[MVT::LAST_VALUETYPE];
683 
684  public:
686  std::fill(std::begin(ValueTypeActions), std::end(ValueTypeActions),
687  TypeLegal);
688  }
689 
691  return ValueTypeActions[VT.SimpleTy];
692  }
693 
695  ValueTypeActions[VT.SimpleTy] = Action;
696  }
697  };
698 
700  return ValueTypeActions;
701  }
702 
703  /// Return how we should legalize values of this type, either it is already
704  /// legal (return 'Legal') or we need to promote it to a larger type (return
705  /// 'Promote'), or we need to expand it into multiple registers of smaller
706  /// integer type (return 'Expand'). 'Custom' is not an option.
708  return getTypeConversion(Context, VT).first;
709  }
711  return ValueTypeActions.getTypeAction(VT);
712  }
713 
714  /// For types supported by the target, this is an identity function. For
715  /// types that must be promoted to larger types, this returns the larger type
716  /// to promote to. For integer types that are larger than the largest integer
717  /// register, this contains one step in the expansion to get to the smaller
718  /// register. For illegal floating point types, this returns the integer type
719  /// to transform to.
720  EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
721  return getTypeConversion(Context, VT).second;
722  }
723 
724  /// For types supported by the target, this is an identity function. For
725  /// types that must be expanded (i.e. integer types that are larger than the
726  /// largest integer register or illegal floating point types), this returns
727  /// the largest legal type it will be expanded to.
728  EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
729  assert(!VT.isVector());
730  while (true) {
731  switch (getTypeAction(Context, VT)) {
732  case TypeLegal:
733  return VT;
734  case TypeExpandInteger:
735  VT = getTypeToTransformTo(Context, VT);
736  break;
737  default:
738  llvm_unreachable("Type is not legal nor is it to be expanded!");
739  }
740  }
741  }
742 
743  /// Vector types are broken down into some number of legal first class types.
744  /// For example, EVT::v8f32 maps to 2 EVT::v4f32 with Altivec or SSE1, or 8
745  /// promoted EVT::f64 values with the X86 FP stack. Similarly, EVT::v2i64
746  /// turns into 4 EVT::i32 values with both PPC and X86.
747  ///
748  /// This method returns the number of registers needed, and the VT for each
749  /// register. It also returns the VT and quantity of the intermediate values
750  /// before they are promoted/expanded.
751  unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
752  EVT &IntermediateVT,
753  unsigned &NumIntermediates,
754  MVT &RegisterVT) const;
755 
756  /// Certain targets such as MIPS require that some types such as vectors are
757  /// always broken down into scalars in some contexts. This occurs even if the
758  /// vector type is legal.
760  LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
761  unsigned &NumIntermediates, MVT &RegisterVT) const {
762  return getVectorTypeBreakdown(Context, VT, IntermediateVT, NumIntermediates,
763  RegisterVT);
764  }
765 
766  struct IntrinsicInfo {
767  unsigned opc = 0; // target opcode
768  EVT memVT; // memory VT
769 
770  // value representing memory location
772 
773  int offset = 0; // offset off of ptrVal
774  unsigned size = 0; // the size of the memory location
775  // (taken from memVT if zero)
776  unsigned align = 1; // alignment
777 
779  IntrinsicInfo() = default;
780  };
781 
782  /// Given an intrinsic, checks if on the target the intrinsic will need to map
783  /// to a MemIntrinsicNode (touches memory). If this is the case, it returns
784  /// true and store the intrinsic information into the IntrinsicInfo that was
785  /// passed to the function.
786  virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
787  MachineFunction &,
788  unsigned /*Intrinsic*/) const {
789  return false;
790  }
791 
792  /// Returns true if the target can instruction select the specified FP
793  /// immediate natively. If false, the legalizer will materialize the FP
794  /// immediate as a load from a constant pool.
795  virtual bool isFPImmLegal(const APFloat &/*Imm*/, EVT /*VT*/,
796  bool ForCodeSize = false) const {
797  return false;
798  }
799 
800  /// Targets can use this to indicate that they only support *some*
801  /// VECTOR_SHUFFLE operations, those with specific masks. By default, if a
802  /// target supports the VECTOR_SHUFFLE node, all mask values are assumed to be
803  /// legal.
804  virtual bool isShuffleMaskLegal(ArrayRef<int> /*Mask*/, EVT /*VT*/) const {
805  return true;
806  }
807 
808  /// Returns true if the operation can trap for the value type.
809  ///
810  /// VT must be a legal type. By default, we optimistically assume most
811  /// operations don't trap except for integer divide and remainder.
812  virtual bool canOpTrap(unsigned Op, EVT VT) const;
813 
814  /// Similar to isShuffleMaskLegal. Targets can use this to indicate if there
815  /// is a suitable VECTOR_SHUFFLE that can be used to replace a VAND with a
816  /// constant pool entry.
817  virtual bool isVectorClearMaskLegal(ArrayRef<int> /*Mask*/,
818  EVT /*VT*/) const {
819  return false;
820  }
821 
822  /// Return how this operation should be treated: either it is legal, needs to
823  /// be promoted to a larger size, needs to be expanded to some other code
824  /// sequence, or the target has a custom expander for it.
825  LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
826  if (VT.isExtended()) return Expand;
827  // If a target-specific SDNode requires legalization, require the target
828  // to provide custom legalization for it.
829  if (Op >= array_lengthof(OpActions[0])) return Custom;
830  return OpActions[(unsigned)VT.getSimpleVT().SimpleTy][Op];
831  }
832 
833  /// Custom method defined by each target to indicate if an operation which
834  /// may require a scale is supported natively by the target.
835  /// If not, the operation is illegal.
836  virtual bool isSupportedFixedPointOperation(unsigned Op, EVT VT,
837  unsigned Scale) const {
838  return false;
839  }
840 
841  /// Some fixed point operations may be natively supported by the target but
842  /// only for specific scales. This method allows for checking
843  /// if the width is supported by the target for a given operation that may
844  /// depend on scale.
846  unsigned Scale) const {
847  auto Action = getOperationAction(Op, VT);
848  if (Action != Legal)
849  return Action;
850 
851  // This operation is supported in this type but may only work on specific
852  // scales.
853  bool Supported;
854  switch (Op) {
855  default:
856  llvm_unreachable("Unexpected fixed point operation.");
857  case ISD::SMULFIX:
858  case ISD::UMULFIX:
859  Supported = isSupportedFixedPointOperation(Op, VT, Scale);
860  break;
861  }
862 
863  return Supported ? Action : Expand;
864  }
865 
867  unsigned EqOpc;
868  switch (Op) {
869  default: llvm_unreachable("Unexpected FP pseudo-opcode");
870  case ISD::STRICT_FADD: EqOpc = ISD::FADD; break;
871  case ISD::STRICT_FSUB: EqOpc = ISD::FSUB; break;
872  case ISD::STRICT_FMUL: EqOpc = ISD::FMUL; break;
873  case ISD::STRICT_FDIV: EqOpc = ISD::FDIV; break;
874  case ISD::STRICT_FREM: EqOpc = ISD::FREM; break;
875  case ISD::STRICT_FSQRT: EqOpc = ISD::FSQRT; break;
876  case ISD::STRICT_FPOW: EqOpc = ISD::FPOW; break;
877  case ISD::STRICT_FPOWI: EqOpc = ISD::FPOWI; break;
878  case ISD::STRICT_FMA: EqOpc = ISD::FMA; break;
879  case ISD::STRICT_FSIN: EqOpc = ISD::FSIN; break;
880  case ISD::STRICT_FCOS: EqOpc = ISD::FCOS; break;
881  case ISD::STRICT_FEXP: EqOpc = ISD::FEXP; break;
882  case ISD::STRICT_FEXP2: EqOpc = ISD::FEXP2; break;
883  case ISD::STRICT_FLOG: EqOpc = ISD::FLOG; break;
884  case ISD::STRICT_FLOG10: EqOpc = ISD::FLOG10; break;
885  case ISD::STRICT_FLOG2: EqOpc = ISD::FLOG2; break;
886  case ISD::STRICT_FRINT: EqOpc = ISD::FRINT; break;
887  case ISD::STRICT_FNEARBYINT: EqOpc = ISD::FNEARBYINT; break;
888  case ISD::STRICT_FMAXNUM: EqOpc = ISD::FMAXNUM; break;
889  case ISD::STRICT_FMINNUM: EqOpc = ISD::FMINNUM; break;
890  case ISD::STRICT_FCEIL: EqOpc = ISD::FCEIL; break;
891  case ISD::STRICT_FFLOOR: EqOpc = ISD::FFLOOR; break;
892  case ISD::STRICT_FROUND: EqOpc = ISD::FROUND; break;
893  case ISD::STRICT_FTRUNC: EqOpc = ISD::FTRUNC; break;
894  case ISD::STRICT_FP_ROUND: EqOpc = ISD::FP_ROUND; break;
895  case ISD::STRICT_FP_EXTEND: EqOpc = ISD::FP_EXTEND; break;
896  }
897 
898  auto Action = getOperationAction(EqOpc, VT);
899 
900  // We don't currently handle Custom or Promote for strict FP pseudo-ops.
901  // For now, we just expand for those cases.
902  if (Action != Legal)
903  Action = Expand;
904 
905  return Action;
906  }
907 
908  /// Return true if the specified operation is legal on this target or can be
909  /// made legal with custom lowering. This is used to help guide high-level
910  /// lowering decisions.
911  bool isOperationLegalOrCustom(unsigned Op, EVT VT) const {
912  return (VT == MVT::Other || isTypeLegal(VT)) &&
913  (getOperationAction(Op, VT) == Legal ||
914  getOperationAction(Op, VT) == Custom);
915  }
916 
917  /// Return true if the specified operation is legal on this target or can be
918  /// made legal using promotion. This is used to help guide high-level lowering
919  /// decisions.
920  bool isOperationLegalOrPromote(unsigned Op, EVT VT) const {
921  return (VT == MVT::Other || isTypeLegal(VT)) &&
922  (getOperationAction(Op, VT) == Legal ||
923  getOperationAction(Op, VT) == Promote);
924  }
925 
926  /// Return true if the specified operation is legal on this target or can be
927  /// made legal with custom lowering or using promotion. This is used to help
928  /// guide high-level lowering decisions.
929  bool isOperationLegalOrCustomOrPromote(unsigned Op, EVT VT) const {
930  return (VT == MVT::Other || isTypeLegal(VT)) &&
931  (getOperationAction(Op, VT) == Legal ||
932  getOperationAction(Op, VT) == Custom ||
933  getOperationAction(Op, VT) == Promote);
934  }
935 
936  /// Return true if the operation uses custom lowering, regardless of whether
937  /// the type is legal or not.
938  bool isOperationCustom(unsigned Op, EVT VT) const {
939  return getOperationAction(Op, VT) == Custom;
940  }
941 
942  /// Return true if lowering to a jump table is allowed.
943  virtual bool areJTsAllowed(const Function *Fn) const {
944  if (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true")
945  return false;
946 
947  return isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
948  isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
949  }
950 
951  /// Check whether the range [Low,High] fits in a machine word.
952  bool rangeFitsInWord(const APInt &Low, const APInt &High,
953  const DataLayout &DL) const {
954  // FIXME: Using the pointer type doesn't seem ideal.
955  uint64_t BW = DL.getIndexSizeInBits(0u);
956  uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1;
957  return Range <= BW;
958  }
959 
960  /// Return true if lowering to a jump table is suitable for a set of case
961  /// clusters which may contain \p NumCases cases, \p Range range of values.
962  /// FIXME: This function check the maximum table size and density, but the
963  /// minimum size is not checked. It would be nice if the minimum size is
964  /// also combined within this function. Currently, the minimum size check is
965  /// performed in findJumpTable() in SelectionDAGBuiler and
966  /// getEstimatedNumberOfCaseClusters() in BasicTTIImpl.
967  virtual bool isSuitableForJumpTable(const SwitchInst *SI, uint64_t NumCases,
968  uint64_t Range) const {
969  const bool OptForSize = SI->getParent()->getParent()->hasOptSize();
970  const unsigned MinDensity = getMinimumJumpTableDensity(OptForSize);
971  const unsigned MaxJumpTableSize =
972  OptForSize ? UINT_MAX : getMaximumJumpTableSize();
973  // Check whether a range of clusters is dense enough for a jump table.
974  if (Range <= MaxJumpTableSize &&
975  (NumCases * 100 >= Range * MinDensity)) {
976  return true;
977  }
978  return false;
979  }
980 
981  /// Return true if lowering to a bit test is suitable for a set of case
982  /// clusters which contains \p NumDests unique destinations, \p Low and
983  /// \p High as its lowest and highest case values, and expects \p NumCmps
984  /// case value comparisons. Check if the number of destinations, comparison
985  /// metric, and range are all suitable.
986  bool isSuitableForBitTests(unsigned NumDests, unsigned NumCmps,
987  const APInt &Low, const APInt &High,
988  const DataLayout &DL) const {
989  // FIXME: I don't think NumCmps is the correct metric: a single case and a
990  // range of cases both require only one branch to lower. Just looking at the
991  // number of clusters and destinations should be enough to decide whether to
992  // build bit tests.
993 
994  // To lower a range with bit tests, the range must fit the bitwidth of a
995  // machine word.
996  if (!rangeFitsInWord(Low, High, DL))
997  return false;
998 
999  // Decide whether it's profitable to lower this range with bit tests. Each
1000  // destination requires a bit test and branch, and there is an overall range
1001  // check branch. For a small number of clusters, separate comparisons might
1002  // be cheaper, and for many destinations, splitting the range might be
1003  // better.
1004  return (NumDests == 1 && NumCmps >= 3) || (NumDests == 2 && NumCmps >= 5) ||
1005  (NumDests == 3 && NumCmps >= 6);
1006  }
1007 
1008  /// Return true if the specified operation is illegal on this target or
1009  /// unlikely to be made legal with custom lowering. This is used to help guide
1010  /// high-level lowering decisions.
1011  bool isOperationExpand(unsigned Op, EVT VT) const {
1012  return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
1013  }
1014 
1015  /// Return true if the specified operation is legal on this target.
1016  bool isOperationLegal(unsigned Op, EVT VT) const {
1017  return (VT == MVT::Other || isTypeLegal(VT)) &&
1018  getOperationAction(Op, VT) == Legal;
1019  }
1020 
1021  /// Return how this load with extension should be treated: either it is legal,
1022  /// needs to be promoted to a larger size, needs to be expanded to some other
1023  /// code sequence, or the target has a custom expander for it.
1025  EVT MemVT) const {
1026  if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
1027  unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
1028  unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
1029  assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValI < MVT::LAST_VALUETYPE &&
1030  MemI < MVT::LAST_VALUETYPE && "Table isn't big enough!");
1031  unsigned Shift = 4 * ExtType;
1032  return (LegalizeAction)((LoadExtActions[ValI][MemI] >> Shift) & 0xf);
1033  }
1034 
1035  /// Return true if the specified load with extension is legal on this target.
1036  bool isLoadExtLegal(unsigned ExtType, EVT ValVT, EVT MemVT) const {
1037  return getLoadExtAction(ExtType, ValVT, MemVT) == Legal;
1038  }
1039 
1040  /// Return true if the specified load with extension is legal or custom
1041  /// on this target.
1042  bool isLoadExtLegalOrCustom(unsigned ExtType, EVT ValVT, EVT MemVT) const {
1043  return getLoadExtAction(ExtType, ValVT, MemVT) == Legal ||
1044  getLoadExtAction(ExtType, ValVT, MemVT) == Custom;
1045  }
1046 
1047  /// Return how this store with truncation should be treated: either it is
1048  /// legal, needs to be promoted to a larger size, needs to be expanded to some
1049  /// other code sequence, or the target has a custom expander for it.
1051  if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
1052  unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
1053  unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
1054  assert(ValI < MVT::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE &&
1055  "Table isn't big enough!");
1056  return TruncStoreActions[ValI][MemI];
1057  }
1058 
1059  /// Return true if the specified store with truncation is legal on this
1060  /// target.
1061  bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
1062  return isTypeLegal(ValVT) && getTruncStoreAction(ValVT, MemVT) == Legal;
1063  }
1064 
1065  /// Return true if the specified store with truncation has solution on this
1066  /// target.
1067  bool isTruncStoreLegalOrCustom(EVT ValVT, EVT MemVT) const {
1068  return isTypeLegal(ValVT) &&
1069  (getTruncStoreAction(ValVT, MemVT) == Legal ||
1070  getTruncStoreAction(ValVT, MemVT) == Custom);
1071  }
1072 
1073  /// Return how the indexed load should be treated: either it is legal, needs
1074  /// to be promoted to a larger size, needs to be expanded to some other code
1075  /// sequence, or the target has a custom expander for it.
1077  getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
1078  assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&
1079  "Table isn't big enough!");
1080  unsigned Ty = (unsigned)VT.SimpleTy;
1081  return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] & 0xf0) >> 4);
1082  }
1083 
1084  /// Return true if the specified indexed load is legal on this target.
1085  bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
1086  return VT.isSimple() &&
1087  (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
1088  getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
1089  }
1090 
1091  /// Return how the indexed store should be treated: either it is legal, needs
1092  /// to be promoted to a larger size, needs to be expanded to some other code
1093  /// sequence, or the target has a custom expander for it.
1095  getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
1096  assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&
1097  "Table isn't big enough!");
1098  unsigned Ty = (unsigned)VT.SimpleTy;
1099  return (LegalizeAction)(IndexedModeActions[Ty][IdxMode] & 0x0f);
1100  }
1101 
1102  /// Return true if the specified indexed load is legal on this target.
1103  bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
1104  return VT.isSimple() &&
1105  (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
1106  getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
1107  }
1108 
1109  /// Return how the condition code should be treated: either it is legal, needs
1110  /// to be expanded to some other code sequence, or the target has a custom
1111  /// expander for it.
1114  assert((unsigned)CC < array_lengthof(CondCodeActions) &&
1115  ((unsigned)VT.SimpleTy >> 3) < array_lengthof(CondCodeActions[0]) &&
1116  "Table isn't big enough!");
1117  // See setCondCodeAction for how this is encoded.
1118  uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
1119  uint32_t Value = CondCodeActions[CC][VT.SimpleTy >> 3];
1120  LegalizeAction Action = (LegalizeAction) ((Value >> Shift) & 0xF);
1121  assert(Action != Promote && "Can't promote condition code!");
1122  return Action;
1123  }
1124 
1125  /// Return true if the specified condition code is legal on this target.
1126  bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
1127  return getCondCodeAction(CC, VT) == Legal;
1128  }
1129 
1130  /// Return true if the specified condition code is legal or custom on this
1131  /// target.
1133  return getCondCodeAction(CC, VT) == Legal ||
1134  getCondCodeAction(CC, VT) == Custom;
1135  }
1136 
1137  /// If the action for this operation is to promote, this method returns the
1138  /// ValueType to promote to.
1139  MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
1140  assert(getOperationAction(Op, VT) == Promote &&
1141  "This operation isn't promoted!");
1142 
1143  // See if this has an explicit type specified.
1144  std::map<std::pair<unsigned, MVT::SimpleValueType>,
1146  PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
1147  if (PTTI != PromoteToType.end()) return PTTI->second;
1148 
1149  assert((VT.isInteger() || VT.isFloatingPoint()) &&
1150  "Cannot autopromote this type, add it with AddPromotedToType.");
1151 
1152  MVT NVT = VT;
1153  do {
1154  NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
1155  assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
1156  "Didn't find type to promote to!");
1157  } while (!isTypeLegal(NVT) ||
1158  getOperationAction(Op, NVT) == Promote);
1159  return NVT;
1160  }
1161 
1162  /// Return the EVT corresponding to this LLVM type. This is fixed by the LLVM
1163  /// operations except for the pointer size. If AllowUnknown is true, this
1164  /// will return MVT::Other for types with no EVT counterpart (e.g. structs),
1165  /// otherwise it will assert.
1167  bool AllowUnknown = false) const {
1168  // Lower scalar pointers to native pointer types.
1169  if (auto *PTy = dyn_cast<PointerType>(Ty))
1170  return getPointerTy(DL, PTy->getAddressSpace());
1171 
1172  if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1173  Type *EltTy = VTy->getElementType();
1174  // Lower vectors of pointers to native pointer types.
1175  if (auto *PTy = dyn_cast<PointerType>(EltTy)) {
1176  EVT PointerTy(getPointerTy(DL, PTy->getAddressSpace()));
1177  EltTy = PointerTy.getTypeForEVT(Ty->getContext());
1178  }
1179  return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(EltTy, false),
1180  VTy->getNumElements());
1181  }
1182 
1183  return EVT::getEVT(Ty, AllowUnknown);
1184  }
1185 
1187  bool AllowUnknown = false) const {
1188  // Lower scalar pointers to native pointer types.
1189  if (PointerType *PTy = dyn_cast<PointerType>(Ty))
1190  return getPointerMemTy(DL, PTy->getAddressSpace());
1191  else if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1192  Type *Elm = VTy->getElementType();
1193  if (PointerType *PT = dyn_cast<PointerType>(Elm)) {
1194  EVT PointerTy(getPointerMemTy(DL, PT->getAddressSpace()));
1195  Elm = PointerTy.getTypeForEVT(Ty->getContext());
1196  }
1197  return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
1198  VTy->getNumElements());
1199  }
1200 
1201  return getValueType(DL, Ty, AllowUnknown);
1202  }
1203 
1204 
1205  /// Return the MVT corresponding to this LLVM type. See getValueType.
1207  bool AllowUnknown = false) const {
1208  return getValueType(DL, Ty, AllowUnknown).getSimpleVT();
1209  }
1210 
1211  /// Return the desired alignment for ByVal or InAlloca aggregate function
1212  /// arguments in the caller parameter area. This is the actual alignment, not
1213  /// its logarithm.
1214  virtual unsigned getByValTypeAlignment(Type *Ty, const DataLayout &DL) const;
1215 
1216  /// Return the type of registers that this ValueType will eventually require.
1218  assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
1219  return RegisterTypeForVT[VT.SimpleTy];
1220  }
1221 
1222  /// Return the type of registers that this ValueType will eventually require.
1223  MVT getRegisterType(LLVMContext &Context, EVT VT) const {
1224  if (VT.isSimple()) {
1225  assert((unsigned)VT.getSimpleVT().SimpleTy <
1226  array_lengthof(RegisterTypeForVT));
1227  return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
1228  }
1229  if (VT.isVector()) {
1230  EVT VT1;
1231  MVT RegisterVT;
1232  unsigned NumIntermediates;
1233  (void)getVectorTypeBreakdown(Context, VT, VT1,
1234  NumIntermediates, RegisterVT);
1235  return RegisterVT;
1236  }
1237  if (VT.isInteger()) {
1238  return getRegisterType(Context, getTypeToTransformTo(Context, VT));
1239  }
1240  llvm_unreachable("Unsupported extended type!");
1241  }
1242 
1243  /// Return the number of registers that this ValueType will eventually
1244  /// require.
1245  ///
1246  /// This is one for any types promoted to live in larger registers, but may be
1247  /// more than one for types (like i64) that are split into pieces. For types
1248  /// like i140, which are first promoted then expanded, it is the number of
1249  /// registers needed to hold all the bits of the original type. For an i140
1250  /// on a 32 bit machine this means 5 registers.
1251  unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
1252  if (VT.isSimple()) {
1253  assert((unsigned)VT.getSimpleVT().SimpleTy <
1254  array_lengthof(NumRegistersForVT));
1255  return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
1256  }
1257  if (VT.isVector()) {
1258  EVT VT1;
1259  MVT VT2;
1260  unsigned NumIntermediates;
1261  return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
1262  }
1263  if (VT.isInteger()) {
1264  unsigned BitWidth = VT.getSizeInBits();
1265  unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
1266  return (BitWidth + RegWidth - 1) / RegWidth;
1267  }
1268  llvm_unreachable("Unsupported extended type!");
1269  }
1270 
1271  /// Certain combinations of ABIs, Targets and features require that types
1272  /// are legal for some operations and not for other operations.
1273  /// For MIPS all vector types must be passed through the integer register set.
1275  CallingConv::ID CC, EVT VT) const {
1276  return getRegisterType(Context, VT);
1277  }
1278 
1279  /// Certain targets require unusual breakdowns of certain types. For MIPS,
1280  /// this occurs when a vector type is used, as vector are passed through the
1281  /// integer register set.
1282  virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context,
1283  CallingConv::ID CC,
1284  EVT VT) const {
1285  return getNumRegisters(Context, VT);
1286  }
1287 
1288  /// Certain targets have context senstive alignment requirements, where one
1289  /// type has the alignment requirement of another type.
1290  virtual unsigned getABIAlignmentForCallingConv(Type *ArgTy,
1291  DataLayout DL) const {
1292  return DL.getABITypeAlignment(ArgTy);
1293  }
1294 
1295  /// If true, then instruction selection should seek to shrink the FP constant
1296  /// of the specified type to a smaller type in order to save space and / or
1297  /// reduce runtime.
1298  virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
1299 
1300  /// Return true if it is profitable to reduce a load to a smaller type.
1301  /// Example: (i16 (trunc (i32 (load x))) -> i16 load x
1303  EVT NewVT) const {
1304  // By default, assume that it is cheaper to extract a subvector from a wide
1305  // vector load rather than creating multiple narrow vector loads.
1306  if (NewVT.isVector() && !Load->hasOneUse())
1307  return false;
1308 
1309  return true;
1310  }
1311 
1312  /// When splitting a value of the specified type into parts, does the Lo
1313  /// or Hi part come first? This usually follows the endianness, except
1314  /// for ppcf128, where the Hi part always comes first.
1315  bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const {
1316  return DL.isBigEndian() || VT == MVT::ppcf128;
1317  }
1318 
1319  /// If true, the target has custom DAG combine transformations that it can
1320  /// perform for the specified node.
1322  assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1323  return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
1324  }
1325 
1326  unsigned getGatherAllAliasesMaxDepth() const {
1327  return GatherAllAliasesMaxDepth;
1328  }
1329 
1330  /// Returns the size of the platform's va_list object.
1331  virtual unsigned getVaListSizeInBits(const DataLayout &DL) const {
1332  return getPointerTy(DL).getSizeInBits();
1333  }
1334 
1335  /// Get maximum # of store operations permitted for llvm.memset
1336  ///
1337  /// This function returns the maximum number of store operations permitted
1338  /// to replace a call to llvm.memset. The value is set by the target at the
1339  /// performance threshold for such a replacement. If OptSize is true,
1340  /// return the limit for functions that have OptSize attribute.
1341  unsigned getMaxStoresPerMemset(bool OptSize) const {
1342  return OptSize ? MaxStoresPerMemsetOptSize : MaxStoresPerMemset;
1343  }
1344 
1345  /// Get maximum # of store operations permitted for llvm.memcpy
1346  ///
1347  /// This function returns the maximum number of store operations permitted
1348  /// to replace a call to llvm.memcpy. The value is set by the target at the
1349  /// performance threshold for such a replacement. If OptSize is true,
1350  /// return the limit for functions that have OptSize attribute.
1351  unsigned getMaxStoresPerMemcpy(bool OptSize) const {
1352  return OptSize ? MaxStoresPerMemcpyOptSize : MaxStoresPerMemcpy;
1353  }
1354 
1355  /// \brief Get maximum # of store operations to be glued together
1356  ///
1357  /// This function returns the maximum number of store operations permitted
1358  /// to glue together during lowering of llvm.memcpy. The value is set by
1359  // the target at the performance threshold for such a replacement.
1360  virtual unsigned getMaxGluedStoresPerMemcpy() const {
1361  return MaxGluedStoresPerMemcpy;
1362  }
1363 
1364  /// Get maximum # of load operations permitted for memcmp
1365  ///
1366  /// This function returns the maximum number of load operations permitted
1367  /// to replace a call to memcmp. The value is set by the target at the
1368  /// performance threshold for such a replacement. If OptSize is true,
1369  /// return the limit for functions that have OptSize attribute.
1370  unsigned getMaxExpandSizeMemcmp(bool OptSize) const {
1371  return OptSize ? MaxLoadsPerMemcmpOptSize : MaxLoadsPerMemcmp;
1372  }
1373 
1374  /// For memcmp expansion when the memcmp result is only compared equal or
1375  /// not-equal to 0, allow up to this number of load pairs per block. As an
1376  /// example, this may allow 'memcmp(a, b, 3) == 0' in a single block:
1377  /// a0 = load2bytes &a[0]
1378  /// b0 = load2bytes &b[0]
1379  /// a2 = load1byte &a[2]
1380  /// b2 = load1byte &b[2]
1381  /// r = cmp eq (a0 ^ b0 | a2 ^ b2), 0
1382  virtual unsigned getMemcmpEqZeroLoadsPerBlock() const {
1383  return 1;
1384  }
1385 
1386  /// Get maximum # of store operations permitted for llvm.memmove
1387  ///
1388  /// This function returns the maximum number of store operations permitted
1389  /// to replace a call to llvm.memmove. The value is set by the target at the
1390  /// performance threshold for such a replacement. If OptSize is true,
1391  /// return the limit for functions that have OptSize attribute.
1392  unsigned getMaxStoresPerMemmove(bool OptSize) const {
1393  return OptSize ? MaxStoresPerMemmoveOptSize : MaxStoresPerMemmove;
1394  }
1395 
1396  /// Determine if the target supports unaligned memory accesses.
1397  ///
1398  /// This function returns true if the target allows unaligned memory accesses
1399  /// of the specified type in the given address space. If true, it also returns
1400  /// whether the unaligned memory access is "fast" in the last argument by
1401  /// reference. This is used, for example, in situations where an array
1402  /// copy/move/set is converted to a sequence of store operations. Its use
1403  /// helps to ensure that such replacements don't generate code that causes an
1404  /// alignment error (trap) on the target machine.
1406  unsigned AddrSpace = 0,
1407  unsigned Align = 1,
1408  bool * /*Fast*/ = nullptr) const {
1409  return false;
1410  }
1411 
1412  /// Return true if the target supports a memory access of this type for the
1413  /// given address space and alignment. If the access is allowed, the optional
1414  /// final parameter returns if the access is also fast (as defined by the
1415  /// target).
1416  bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT,
1417  unsigned AddrSpace = 0, unsigned Alignment = 1,
1418  bool *Fast = nullptr) const;
1419 
1420  /// Returns the target specific optimal type for load and store operations as
1421  /// a result of memset, memcpy, and memmove lowering.
1422  ///
1423  /// If DstAlign is zero that means it's safe to destination alignment can
1424  /// satisfy any constraint. Similarly if SrcAlign is zero it means there isn't
1425  /// a need to check it against alignment requirement, probably because the
1426  /// source does not need to be loaded. If 'IsMemset' is true, that means it's
1427  /// expanding a memset. If 'ZeroMemset' is true, that means it's a memset of
1428  /// zero. 'MemcpyStrSrc' indicates whether the memcpy source is constant so it
1429  /// does not need to be loaded. It returns EVT::Other if the type should be
1430  /// determined using generic target-independent logic.
1431  virtual EVT
1432  getOptimalMemOpType(uint64_t /*Size*/, unsigned /*DstAlign*/,
1433  unsigned /*SrcAlign*/, bool /*IsMemset*/,
1434  bool /*ZeroMemset*/, bool /*MemcpyStrSrc*/,
1435  const AttributeList & /*FuncAttributes*/) const {
1436  return MVT::Other;
1437  }
1438 
1439  /// Returns true if it's safe to use load / store of the specified type to
1440  /// expand memcpy / memset inline.
1441  ///
1442  /// This is mostly true for all types except for some special cases. For
1443  /// example, on X86 targets without SSE2 f64 load / store are done with fldl /
1444  /// fstpl which also does type conversion. Note the specified type doesn't
1445  /// have to be legal as the hook is used before type legalization.
1446  virtual bool isSafeMemOpType(MVT /*VT*/) const { return true; }
1447 
1448  /// Determine if we should use _setjmp or setjmp to implement llvm.setjmp.
1449  bool usesUnderscoreSetJmp() const {
1450  return UseUnderscoreSetJmp;
1451  }
1452 
1453  /// Determine if we should use _longjmp or longjmp to implement llvm.longjmp.
1454  bool usesUnderscoreLongJmp() const {
1455  return UseUnderscoreLongJmp;
1456  }
1457 
1458  /// Return lower limit for number of blocks in a jump table.
1459  virtual unsigned getMinimumJumpTableEntries() const;
1460 
1461  /// Return lower limit of the density in a jump table.
1462  unsigned getMinimumJumpTableDensity(bool OptForSize) const;
1463 
1464  /// Return upper limit for number of entries in a jump table.
1465  /// Zero if no limit.
1466  unsigned getMaximumJumpTableSize() const;
1467 
1468  virtual bool isJumpTableRelative() const {
1469  return TM.isPositionIndependent();
1470  }
1471 
1472  /// If a physical register, this specifies the register that
1473  /// llvm.savestack/llvm.restorestack should save and restore.
1475  return StackPointerRegisterToSaveRestore;
1476  }
1477 
1478  /// If a physical register, this returns the register that receives the
1479  /// exception address on entry to an EH pad.
1480  virtual unsigned
1481  getExceptionPointerRegister(const Constant *PersonalityFn) const {
1482  // 0 is guaranteed to be the NoRegister value on all targets
1483  return 0;
1484  }
1485 
1486  /// If a physical register, this returns the register that receives the
1487  /// exception typeid on entry to a landing pad.
1488  virtual unsigned
1489  getExceptionSelectorRegister(const Constant *PersonalityFn) const {
1490  // 0 is guaranteed to be the NoRegister value on all targets
1491  return 0;
1492  }
1493 
1494  virtual bool needsFixedCatchObjects() const {
1495  report_fatal_error("Funclet EH is not implemented for this target");
1496  }
1497 
1498  /// Returns the target's jmp_buf size in bytes (if never set, the default is
1499  /// 200)
1500  unsigned getJumpBufSize() const {
1501  return JumpBufSize;
1502  }
1503 
1504  /// Returns the target's jmp_buf alignment in bytes (if never set, the default
1505  /// is 0)
1506  unsigned getJumpBufAlignment() const {
1507  return JumpBufAlignment;
1508  }
1509 
1510  /// Return the minimum stack alignment of an argument.
1511  unsigned getMinStackArgumentAlignment() const {
1512  return MinStackArgumentAlignment;
1513  }
1514 
1515  /// Return the minimum function alignment.
1516  unsigned getMinFunctionAlignment() const {
1517  return MinFunctionAlignment;
1518  }
1519 
1520  /// Return the preferred function alignment.
1521  unsigned getPrefFunctionAlignment() const {
1522  return PrefFunctionAlignment;
1523  }
1524 
1525  /// Return the preferred loop alignment.
1526  virtual unsigned getPrefLoopAlignment(MachineLoop *ML = nullptr) const {
1527  return PrefLoopAlignment;
1528  }
1529 
1530  /// Should loops be aligned even when the function is marked OptSize (but not
1531  /// MinSize).
1532  virtual bool alignLoopsWithOptSize() const {
1533  return false;
1534  }
1535 
1536  /// If the target has a standard location for the stack protector guard,
1537  /// returns the address of that location. Otherwise, returns nullptr.
1538  /// DEPRECATED: please override useLoadStackGuardNode and customize
1539  /// LOAD_STACK_GUARD, or customize \@llvm.stackguard().
1540  virtual Value *getIRStackGuard(IRBuilder<> &IRB) const;
1541 
1542  /// Inserts necessary declarations for SSP (stack protection) purpose.
1543  /// Should be used only when getIRStackGuard returns nullptr.
1544  virtual void insertSSPDeclarations(Module &M) const;
1545 
1546  /// Return the variable that's previously inserted by insertSSPDeclarations,
1547  /// if any, otherwise return nullptr. Should be used only when
1548  /// getIRStackGuard returns nullptr.
1549  virtual Value *getSDagStackGuard(const Module &M) const;
1550 
1551  /// If this function returns true, stack protection checks should XOR the
1552  /// frame pointer (or whichever pointer is used to address locals) into the
1553  /// stack guard value before checking it. getIRStackGuard must return nullptr
1554  /// if this returns true.
1555  virtual bool useStackGuardXorFP() const { return false; }
1556 
1557  /// If the target has a standard stack protection check function that
1558  /// performs validation and error handling, returns the function. Otherwise,
1559  /// returns nullptr. Must be previously inserted by insertSSPDeclarations.
1560  /// Should be used only when getIRStackGuard returns nullptr.
1561  virtual Function *getSSPStackGuardCheck(const Module &M) const;
1562 
1563 protected:
1564  Value *getDefaultSafeStackPointerLocation(IRBuilder<> &IRB,
1565  bool UseTLS) const;
1566 
1567 public:
1568  /// Returns the target-specific address of the unsafe stack pointer.
1569  virtual Value *getSafeStackPointerLocation(IRBuilder<> &IRB) const;
1570 
1571  /// Returns the name of the symbol used to emit stack probes or the empty
1572  /// string if not applicable.
1574  return "";
1575  }
1576 
1577  /// Returns true if a cast between SrcAS and DestAS is a noop.
1578  virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const {
1579  return false;
1580  }
1581 
1582  /// Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g. we
1583  /// are happy to sink it into basic blocks.
1584  virtual bool isCheapAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const {
1585  return isNoopAddrSpaceCast(SrcAS, DestAS);
1586  }
1587 
1588  /// Return true if the pointer arguments to CI should be aligned by aligning
1589  /// the object whose address is being passed. If so then MinSize is set to the
1590  /// minimum size the object must be to be aligned and PrefAlign is set to the
1591  /// preferred alignment.
1592  virtual bool shouldAlignPointerArgs(CallInst * /*CI*/, unsigned & /*MinSize*/,
1593  unsigned & /*PrefAlign*/) const {
1594  return false;
1595  }
1596 
1597  //===--------------------------------------------------------------------===//
1598  /// \name Helpers for TargetTransformInfo implementations
1599  /// @{
1600 
1601  /// Get the ISD node that corresponds to the Instruction class opcode.
1602  int InstructionOpcodeToISD(unsigned Opcode) const;
1603 
1604  /// Estimate the cost of type-legalization and the legalized type.
1605  std::pair<int, MVT> getTypeLegalizationCost(const DataLayout &DL,
1606  Type *Ty) const;
1607 
1608  /// @}
1609 
1610  //===--------------------------------------------------------------------===//
1611  /// \name Helpers for atomic expansion.
1612  /// @{
1613 
1614  /// Returns the maximum atomic operation size (in bits) supported by
1615  /// the backend. Atomic operations greater than this size (as well
1616  /// as ones that are not naturally aligned), will be expanded by
1617  /// AtomicExpandPass into an __atomic_* library call.
1619  return MaxAtomicSizeInBitsSupported;
1620  }
1621 
1622  /// Returns the size of the smallest cmpxchg or ll/sc instruction
1623  /// the backend supports. Any smaller operations are widened in
1624  /// AtomicExpandPass.
1625  ///
1626  /// Note that *unlike* operations above the maximum size, atomic ops
1627  /// are still natively supported below the minimum; they just
1628  /// require a more complex expansion.
1629  unsigned getMinCmpXchgSizeInBits() const { return MinCmpXchgSizeInBits; }
1630 
1631  /// Whether the target supports unaligned atomic operations.
1632  bool supportsUnalignedAtomics() const { return SupportsUnalignedAtomics; }
1633 
1634  /// Whether AtomicExpandPass should automatically insert fences and reduce
1635  /// ordering for this atomic. This should be true for most architectures with
1636  /// weak memory ordering. Defaults to false.
1637  virtual bool shouldInsertFencesForAtomic(const Instruction *I) const {
1638  return false;
1639  }
1640 
1641  /// Perform a load-linked operation on Addr, returning a "Value *" with the
1642  /// corresponding pointee type. This may entail some non-trivial operations to
1643  /// truncate or reconstruct types that will be illegal in the backend. See
1644  /// ARMISelLowering for an example implementation.
1645  virtual Value *emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
1646  AtomicOrdering Ord) const {
1647  llvm_unreachable("Load linked unimplemented on this target");
1648  }
1649 
1650  /// Perform a store-conditional operation to Addr. Return the status of the
1651  /// store. This should be 0 if the store succeeded, non-zero otherwise.
1652  virtual Value *emitStoreConditional(IRBuilder<> &Builder, Value *Val,
1653  Value *Addr, AtomicOrdering Ord) const {
1654  llvm_unreachable("Store conditional unimplemented on this target");
1655  }
1656 
1657  /// Perform a masked atomicrmw using a target-specific intrinsic. This
1658  /// represents the core LL/SC loop which will be lowered at a late stage by
1659  /// the backend.
1661  AtomicRMWInst *AI,
1662  Value *AlignedAddr, Value *Incr,
1663  Value *Mask, Value *ShiftAmt,
1664  AtomicOrdering Ord) const {
1665  llvm_unreachable("Masked atomicrmw expansion unimplemented on this target");
1666  }
1667 
1668  /// Perform a masked cmpxchg using a target-specific intrinsic. This
1669  /// represents the core LL/SC loop which will be lowered at a late stage by
1670  /// the backend.
1672  IRBuilder<> &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
1673  Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
1674  llvm_unreachable("Masked cmpxchg expansion unimplemented on this target");
1675  }
1676 
1677  /// Inserts in the IR a target-specific intrinsic specifying a fence.
1678  /// It is called by AtomicExpandPass before expanding an
1679  /// AtomicRMW/AtomicCmpXchg/AtomicStore/AtomicLoad
1680  /// if shouldInsertFencesForAtomic returns true.
1681  ///
1682  /// Inst is the original atomic instruction, prior to other expansions that
1683  /// may be performed.
1684  ///
1685  /// This function should either return a nullptr, or a pointer to an IR-level
1686  /// Instruction*. Even complex fence sequences can be represented by a
1687  /// single Instruction* through an intrinsic to be lowered later.
1688  /// Backends should override this method to produce target-specific intrinsic
1689  /// for their fences.
1690  /// FIXME: Please note that the default implementation here in terms of
1691  /// IR-level fences exists for historical/compatibility reasons and is
1692  /// *unsound* ! Fences cannot, in general, be used to restore sequential
1693  /// consistency. For example, consider the following example:
1694  /// atomic<int> x = y = 0;
1695  /// int r1, r2, r3, r4;
1696  /// Thread 0:
1697  /// x.store(1);
1698  /// Thread 1:
1699  /// y.store(1);
1700  /// Thread 2:
1701  /// r1 = x.load();
1702  /// r2 = y.load();
1703  /// Thread 3:
1704  /// r3 = y.load();
1705  /// r4 = x.load();
1706  /// r1 = r3 = 1 and r2 = r4 = 0 is impossible as long as the accesses are all
1707  /// seq_cst. But if they are lowered to monotonic accesses, no amount of
1708  /// IR-level fences can prevent it.
1709  /// @{
1711  AtomicOrdering Ord) const {
1712  if (isReleaseOrStronger(Ord) && Inst->hasAtomicStore())
1713  return Builder.CreateFence(Ord);
1714  else
1715  return nullptr;
1716  }
1717 
1719  Instruction *Inst,
1720  AtomicOrdering Ord) const {
1721  if (isAcquireOrStronger(Ord))
1722  return Builder.CreateFence(Ord);
1723  else
1724  return nullptr;
1725  }
1726  /// @}
1727 
1728  // Emits code that executes when the comparison result in the ll/sc
1729  // expansion of a cmpxchg instruction is such that the store-conditional will
1730  // not execute. This makes it possible to balance out the load-linked with
1731  // a dedicated instruction, if desired.
1732  // E.g., on ARM, if ldrex isn't followed by strex, the exclusive monitor would
1733  // be unnecessarily held, except if clrex, inserted by this hook, is executed.
1734  virtual void emitAtomicCmpXchgNoStoreLLBalance(IRBuilder<> &Builder) const {}
1735 
1736  /// Returns true if the given (atomic) store should be expanded by the
1737  /// IR-level AtomicExpand pass into an "atomic xchg" which ignores its input.
1739  return false;
1740  }
1741 
1742  /// Returns true if arguments should be sign-extended in lib calls.
1743  virtual bool shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
1744  return IsSigned;
1745  }
1746 
1747  /// Returns how the given (atomic) load should be expanded by the
1748  /// IR-level AtomicExpand pass.
1751  }
1752 
1753  /// Returns how the given atomic cmpxchg should be expanded by the IR-level
1754  /// AtomicExpand pass.
1755  virtual AtomicExpansionKind
1758  }
1759 
1760  /// Returns how the IR-level AtomicExpand pass should expand the given
1761  /// AtomicRMW, if at all. Default is to never expand.
1763  return RMW->isFloatingPointOperation() ?
1764  AtomicExpansionKind::CmpXChg : AtomicExpansionKind::None;
1765  }
1766 
1767  /// On some platforms, an AtomicRMW that never actually modifies the value
1768  /// (such as fetch_add of 0) can be turned into a fence followed by an
1769  /// atomic load. This may sound useless, but it makes it possible for the
1770  /// processor to keep the cacheline shared, dramatically improving
1771  /// performance. And such idempotent RMWs are useful for implementing some
1772  /// kinds of locks, see for example (justification + benchmarks):
1773  /// http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf
1774  /// This method tries doing that transformation, returning the atomic load if
1775  /// it succeeds, and nullptr otherwise.
1776  /// If shouldExpandAtomicLoadInIR returns true on that load, it will undergo
1777  /// another round of expansion.
1778  virtual LoadInst *
1780  return nullptr;
1781  }
1782 
1783  /// Returns how the platform's atomic operations are extended (ZERO_EXTEND,
1784  /// SIGN_EXTEND, or ANY_EXTEND).
1786  return ISD::ZERO_EXTEND;
1787  }
1788 
1789  /// @}
1790 
1791  /// Returns true if we should normalize
1792  /// select(N0&N1, X, Y) => select(N0, select(N1, X, Y), Y) and
1793  /// select(N0|N1, X, Y) => select(N0, select(N1, X, Y, Y)) if it is likely
1794  /// that it saves us from materializing N0 and N1 in an integer register.
1795  /// Targets that are able to perform and/or on flags should return false here.
1797  EVT VT) const {
1798  // If a target has multiple condition registers, then it likely has logical
1799  // operations on those registers.
1800  if (hasMultipleConditionRegisters())
1801  return false;
1802  // Only do the transform if the value won't be split into multiple
1803  // registers.
1804  LegalizeTypeAction Action = getTypeAction(Context, VT);
1805  return Action != TypeExpandInteger && Action != TypeExpandFloat &&
1806  Action != TypeSplitVector;
1807  }
1808 
1809  virtual bool isProfitableToCombineMinNumMaxNum(EVT VT) const { return true; }
1810 
1811  /// Return true if a select of constants (select Cond, C1, C2) should be
1812  /// transformed into simple math ops with the condition value. For example:
1813  /// select Cond, C1, C1-1 --> add (zext Cond), C1-1
1814  virtual bool convertSelectOfConstantsToMath(EVT VT) const {
1815  return false;
1816  }
1817 
1818  /// Return true if it is profitable to transform an integer
1819  /// multiplication-by-constant into simpler operations like shifts and adds.
1820  /// This may be true if the target does not directly support the
1821  /// multiplication operation for the specified type or the sequence of simpler
1822  /// ops is faster than the multiply.
1823  virtual bool decomposeMulByConstant(EVT VT, SDValue C) const {
1824  return false;
1825  }
1826 
1827  /// Return true if it is more correct/profitable to use strict FP_TO_INT
1828  /// conversion operations - canonicalizing the FP source value instead of
1829  /// converting all cases and then selecting based on value.
1830  /// This may be true if the target throws exceptions for out of bounds
1831  /// conversions or has fast FP CMOV.
1832  virtual bool shouldUseStrictFP_TO_INT(EVT FpVT, EVT IntVT,
1833  bool IsSigned) const {
1834  return false;
1835  }
1836 
1837  //===--------------------------------------------------------------------===//
1838  // TargetLowering Configuration Methods - These methods should be invoked by
1839  // the derived class constructor to configure this object for the target.
1840  //
1841 protected:
1842  /// Specify how the target extends the result of integer and floating point
1843  /// boolean values from i1 to a wider type. See getBooleanContents.
1845  BooleanContents = Ty;
1846  BooleanFloatContents = Ty;
1847  }
1848 
1849  /// Specify how the target extends the result of integer and floating point
1850  /// boolean values from i1 to a wider type. See getBooleanContents.
1852  BooleanContents = IntTy;
1853  BooleanFloatContents = FloatTy;
1854  }
1855 
1856  /// Specify how the target extends the result of a vector boolean value from a
1857  /// vector of i1 to a wider type. See getBooleanContents.
1859  BooleanVectorContents = Ty;
1860  }
1861 
1862  /// Specify the target scheduling preference.
1864  SchedPreferenceInfo = Pref;
1865  }
1866 
1867  /// Indicate whether this target prefers to use _setjmp to implement
1868  /// llvm.setjmp or the version without _. Defaults to false.
1869  void setUseUnderscoreSetJmp(bool Val) {
1870  UseUnderscoreSetJmp = Val;
1871  }
1872 
1873  /// Indicate whether this target prefers to use _longjmp to implement
1874  /// llvm.longjmp or the version without _. Defaults to false.
1875  void setUseUnderscoreLongJmp(bool Val) {
1876  UseUnderscoreLongJmp = Val;
1877  }
1878 
1879  /// Indicate the minimum number of blocks to generate jump tables.
1880  void setMinimumJumpTableEntries(unsigned Val);
1881 
1882  /// Indicate the maximum number of entries in jump tables.
1883  /// Set to zero to generate unlimited jump tables.
1884  void setMaximumJumpTableSize(unsigned);
1885 
1886  /// If set to a physical register, this specifies the register that
1887  /// llvm.savestack/llvm.restorestack should save and restore.
1889  StackPointerRegisterToSaveRestore = R;
1890  }
1891 
1892  /// Tells the code generator that the target has multiple (allocatable)
1893  /// condition registers that can be used to store the results of comparisons
1894  /// for use by selects and conditional branches. With multiple condition
1895  /// registers, the code generator will not aggressively sink comparisons into
1896  /// the blocks of their users.
1897  void setHasMultipleConditionRegisters(bool hasManyRegs = true) {
1898  HasMultipleConditionRegisters = hasManyRegs;
1899  }
1900 
1901  /// Tells the code generator that the target has BitExtract instructions.
1902  /// The code generator will aggressively sink "shift"s into the blocks of
1903  /// their users if the users will generate "and" instructions which can be
1904  /// combined with "shift" to BitExtract instructions.
1905  void setHasExtractBitsInsn(bool hasExtractInsn = true) {
1906  HasExtractBitsInsn = hasExtractInsn;
1907  }
1908 
1909  /// Tells the code generator not to expand logic operations on comparison
1910  /// predicates into separate sequences that increase the amount of flow
1911  /// control.
1912  void setJumpIsExpensive(bool isExpensive = true);
1913 
1914  /// Tells the code generator which bitwidths to bypass.
1915  void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
1916  BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
1917  }
1918 
1919  /// Add the specified register class as an available regclass for the
1920  /// specified value type. This indicates the selector can handle values of
1921  /// that class natively.
1923  assert((unsigned)VT.SimpleTy < array_lengthof(RegClassForVT));
1924  RegClassForVT[VT.SimpleTy] = RC;
1925  }
1926 
1927  /// Return the largest legal super-reg register class of the register class
1928  /// for the specified type and its associated "cost".
1929  virtual std::pair<const TargetRegisterClass *, uint8_t>
1930  findRepresentativeClass(const TargetRegisterInfo *TRI, MVT VT) const;
1931 
1932  /// Once all of the register classes are added, this allows us to compute
1933  /// derived properties we expose.
1934  void computeRegisterProperties(const TargetRegisterInfo *TRI);
1935 
1936  /// Indicate that the specified operation does not work with the specified
1937  /// type and indicate what to do about it. Note that VT may refer to either
1938  /// the type of a result or that of an operand of Op.
1939  void setOperationAction(unsigned Op, MVT VT,
1940  LegalizeAction Action) {
1941  assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
1942  OpActions[(unsigned)VT.SimpleTy][Op] = Action;
1943  }
1944 
1945  /// Indicate that the specified load with extension does not work with the
1946  /// specified type and indicate what to do about it.
1947  void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT,
1948  LegalizeAction Action) {
1949  assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() &&
1950  MemVT.isValid() && "Table isn't big enough!");
1951  assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
1952  unsigned Shift = 4 * ExtType;
1953  LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] &= ~((uint16_t)0xF << Shift);
1954  LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] |= (uint16_t)Action << Shift;
1955  }
1956 
1957  /// Indicate that the specified truncating store does not work with the
1958  /// specified type and indicate what to do about it.
1959  void setTruncStoreAction(MVT ValVT, MVT MemVT,
1960  LegalizeAction Action) {
1961  assert(ValVT.isValid() && MemVT.isValid() && "Table isn't big enough!");
1962  TruncStoreActions[(unsigned)ValVT.SimpleTy][MemVT.SimpleTy] = Action;
1963  }
1964 
1965  /// Indicate that the specified indexed load does or does not work with the
1966  /// specified type and indicate what to do abort it.
1967  ///
1968  /// NOTE: All indexed mode loads are initialized to Expand in
1969  /// TargetLowering.cpp
1970  void setIndexedLoadAction(unsigned IdxMode, MVT VT,
1971  LegalizeAction Action) {
1972  assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&
1973  (unsigned)Action < 0xf && "Table isn't big enough!");
1974  // Load action are kept in the upper half.
1975  IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0xf0;
1976  IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action) <<4;
1977  }
1978 
1979  /// Indicate that the specified indexed store does or does not work with the
1980  /// specified type and indicate what to do about it.
1981  ///
1982  /// NOTE: All indexed mode stores are initialized to Expand in
1983  /// TargetLowering.cpp
1984  void setIndexedStoreAction(unsigned IdxMode, MVT VT,
1985  LegalizeAction Action) {
1986  assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&
1987  (unsigned)Action < 0xf && "Table isn't big enough!");
1988  // Store action are kept in the lower half.
1989  IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0x0f;
1990  IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action);
1991  }
1992 
1993  /// Indicate that the specified condition code is or isn't supported on the
1994  /// target and indicate what to do about it.
1996  LegalizeAction Action) {
1997  assert(VT.isValid() && (unsigned)CC < array_lengthof(CondCodeActions) &&
1998  "Table isn't big enough!");
1999  assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
2000  /// The lower 3 bits of the SimpleTy index into Nth 4bit set from the 32-bit
2001  /// value and the upper 29 bits index into the second dimension of the array
2002  /// to select what 32-bit value to use.
2003  uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
2004  CondCodeActions[CC][VT.SimpleTy >> 3] &= ~((uint32_t)0xF << Shift);
2005  CondCodeActions[CC][VT.SimpleTy >> 3] |= (uint32_t)Action << Shift;
2006  }
2007 
2008  /// If Opc/OrigVT is specified as being promoted, the promotion code defaults
2009  /// to trying a larger integer/fp until it can find one that works. If that
2010  /// default is insufficient, this method can be used by the target to override
2011  /// the default.
2012  void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
2013  PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
2014  }
2015 
2016  /// Convenience method to set an operation to Promote and specify the type
2017  /// in a single call.
2018  void setOperationPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
2019  setOperationAction(Opc, OrigVT, Promote);
2020  AddPromotedToType(Opc, OrigVT, DestVT);
2021  }
2022 
2023  /// Targets should invoke this method for each target independent node that
2024  /// they want to provide a custom DAG combiner for by implementing the
2025  /// PerformDAGCombine virtual method.
2027  assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
2028  TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
2029  }
2030 
2031  /// Set the target's required jmp_buf buffer size (in bytes); default is 200
2032  void setJumpBufSize(unsigned Size) {
2033  JumpBufSize = Size;
2034  }
2035 
2036  /// Set the target's required jmp_buf buffer alignment (in bytes); default is
2037  /// 0
2038  void setJumpBufAlignment(unsigned Align) {
2039  JumpBufAlignment = Align;
2040  }
2041 
2042  /// Set the target's minimum function alignment (in log2(bytes))
2044  MinFunctionAlignment = Align;
2045  }
2046 
2047  /// Set the target's preferred function alignment. This should be set if
2048  /// there is a performance benefit to higher-than-minimum alignment (in
2049  /// log2(bytes))
2051  PrefFunctionAlignment = Align;
2052  }
2053 
2054  /// Set the target's preferred loop alignment. Default alignment is zero, it
2055  /// means the target does not care about loop alignment. The alignment is
2056  /// specified in log2(bytes). The target may also override
2057  /// getPrefLoopAlignment to provide per-loop values.
2058  void setPrefLoopAlignment(unsigned Align) {
2059  PrefLoopAlignment = Align;
2060  }
2061 
2062  /// Set the minimum stack alignment of an argument (in log2(bytes)).
2064  MinStackArgumentAlignment = Align;
2065  }
2066 
2067  /// Set the maximum atomic operation size supported by the
2068  /// backend. Atomic operations greater than this size (as well as
2069  /// ones that are not naturally aligned), will be expanded by
2070  /// AtomicExpandPass into an __atomic_* library call.
2071  void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits) {
2072  MaxAtomicSizeInBitsSupported = SizeInBits;
2073  }
2074 
2075  /// Sets the minimum cmpxchg or ll/sc size supported by the backend.
2076  void setMinCmpXchgSizeInBits(unsigned SizeInBits) {
2077  MinCmpXchgSizeInBits = SizeInBits;
2078  }
2079 
2080  /// Sets whether unaligned atomic operations are supported.
2081  void setSupportsUnalignedAtomics(bool UnalignedSupported) {
2082  SupportsUnalignedAtomics = UnalignedSupported;
2083  }
2084 
2085 public:
2086  //===--------------------------------------------------------------------===//
2087  // Addressing mode description hooks (used by LSR etc).
2088  //
2089 
2090  /// CodeGenPrepare sinks address calculations into the same BB as Load/Store
2091  /// instructions reading the address. This allows as much computation as
2092  /// possible to be done in the address mode for that operand. This hook lets
2093  /// targets also pass back when this should be done on intrinsics which
2094  /// load/store.
2095  virtual bool getAddrModeArguments(IntrinsicInst * /*I*/,
2096  SmallVectorImpl<Value*> &/*Ops*/,
2097  Type *&/*AccessTy*/) const {
2098  return false;
2099  }
2100 
2101  /// This represents an addressing mode of:
2102  /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
2103  /// If BaseGV is null, there is no BaseGV.
2104  /// If BaseOffs is zero, there is no base offset.
2105  /// If HasBaseReg is false, there is no base register.
2106  /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
2107  /// no scale.
2108  struct AddrMode {
2109  GlobalValue *BaseGV = nullptr;
2110  int64_t BaseOffs = 0;
2111  bool HasBaseReg = false;
2112  int64_t Scale = 0;
2113  AddrMode() = default;
2114  };
2115 
2116  /// Return true if the addressing mode represented by AM is legal for this
2117  /// target, for a load/store of the specified type.
2118  ///
2119  /// The type may be VoidTy, in which case only return true if the addressing
2120  /// mode is legal for a load/store of any legal type. TODO: Handle
2121  /// pre/postinc as well.
2122  ///
2123  /// If the address space cannot be determined, it will be -1.
2124  ///
2125  /// TODO: Remove default argument
2126  virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM,
2127  Type *Ty, unsigned AddrSpace,
2128  Instruction *I = nullptr) const;
2129 
2130  /// Return the cost of the scaling factor used in the addressing mode
2131  /// represented by AM for this target, for a load/store of the specified type.
2132  ///
2133  /// If the AM is supported, the return value must be >= 0.
2134  /// If the AM is not supported, it returns a negative value.
2135  /// TODO: Handle pre/postinc as well.
2136  /// TODO: Remove default argument
2137  virtual int getScalingFactorCost(const DataLayout &DL, const AddrMode &AM,
2138  Type *Ty, unsigned AS = 0) const {
2139  // Default: assume that any scaling factor used in a legal AM is free.
2140  if (isLegalAddressingMode(DL, AM, Ty, AS))
2141  return 0;
2142  return -1;
2143  }
2144 
2145  /// Return true if the specified immediate is legal icmp immediate, that is
2146  /// the target has icmp instructions which can compare a register against the
2147  /// immediate without having to materialize the immediate into a register.
2148  virtual bool isLegalICmpImmediate(int64_t) const {
2149  return true;
2150  }
2151 
2152  /// Return true if the specified immediate is legal add immediate, that is the
2153  /// target has add instructions which can add a register with the immediate
2154  /// without having to materialize the immediate into a register.
2155  virtual bool isLegalAddImmediate(int64_t) const {
2156  return true;
2157  }
2158 
2159  /// Return true if the specified immediate is legal for the value input of a
2160  /// store instruction.
2161  virtual bool isLegalStoreImmediate(int64_t Value) const {
2162  // Default implementation assumes that at least 0 works since it is likely
2163  // that a zero register exists or a zero immediate is allowed.
2164  return Value == 0;
2165  }
2166 
2167  /// Return true if it's significantly cheaper to shift a vector by a uniform
2168  /// scalar than by an amount which will vary across each lane. On x86, for
2169  /// example, there is a "psllw" instruction for the former case, but no simple
2170  /// instruction for a general "a << b" operation on vectors.
2171  virtual bool isVectorShiftByScalarCheap(Type *Ty) const {
2172  return false;
2173  }
2174 
2175  /// Return true if the node is a math/logic binary operator.
2176  virtual bool isBinOp(unsigned Opcode) const {
2177  switch (Opcode) {
2178  case ISD::ADD:
2179  case ISD::SUB:
2180  case ISD::MUL:
2181  case ISD::AND:
2182  case ISD::OR:
2183  case ISD::XOR:
2184  case ISD::SHL:
2185  case ISD::SRL:
2186  case ISD::SRA:
2187  case ISD::SDIV:
2188  case ISD::UDIV:
2189  case ISD::SREM:
2190  case ISD::UREM:
2191  case ISD::FADD:
2192  case ISD::FSUB:
2193  case ISD::FMUL:
2194  case ISD::FDIV:
2195  case ISD::FREM:
2196  case ISD::FMINNUM:
2197  case ISD::FMAXNUM:
2198  case ISD::FMINNUM_IEEE:
2199  case ISD::FMAXNUM_IEEE:
2200  case ISD::FMAXIMUM:
2201  case ISD::FMINIMUM:
2202  return true;
2203  default:
2204  return false;
2205  }
2206  }
2207 
2208  /// Returns true if the opcode is a commutative binary operation.
2209  virtual bool isCommutativeBinOp(unsigned Opcode) const {
2210  // FIXME: This should get its info from the td file.
2211  switch (Opcode) {
2212  case ISD::ADD:
2213  case ISD::SMIN:
2214  case ISD::SMAX:
2215  case ISD::UMIN:
2216  case ISD::UMAX:
2217  case ISD::MUL:
2218  case ISD::MULHU:
2219  case ISD::MULHS:
2220  case ISD::SMUL_LOHI:
2221  case ISD::UMUL_LOHI:
2222  case ISD::FADD:
2223  case ISD::FMUL:
2224  case ISD::AND:
2225  case ISD::OR:
2226  case ISD::XOR:
2227  case ISD::SADDO:
2228  case ISD::UADDO:
2229  case ISD::ADDC:
2230  case ISD::ADDE:
2231  case ISD::SADDSAT:
2232  case ISD::UADDSAT:
2233  case ISD::FMINNUM:
2234  case ISD::FMAXNUM:
2235  case ISD::FMINIMUM:
2236  case ISD::FMAXIMUM:
2237  return true;
2238  default: return false;
2239  }
2240  }
2241 
2242  /// Return true if it's free to truncate a value of type FromTy to type
2243  /// ToTy. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
2244  /// by referencing its sub-register AX.
2245  /// Targets must return false when FromTy <= ToTy.
2246  virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const {
2247  return false;
2248  }
2249 
2250  /// Return true if a truncation from FromTy to ToTy is permitted when deciding
2251  /// whether a call is in tail position. Typically this means that both results
2252  /// would be assigned to the same register or stack slot, but it could mean
2253  /// the target performs adequate checks of its own before proceeding with the
2254  /// tail call. Targets must return false when FromTy <= ToTy.
2255  virtual bool allowTruncateForTailCall(Type *FromTy, Type *ToTy) const {
2256  return false;
2257  }
2258 
2259  virtual bool isTruncateFree(EVT FromVT, EVT ToVT) const {
2260  return false;
2261  }
2262 
2263  virtual bool isProfitableToHoist(Instruction *I) const { return true; }
2264 
2265  /// Return true if the extension represented by \p I is free.
2266  /// Unlikely the is[Z|FP]ExtFree family which is based on types,
2267  /// this method can use the context provided by \p I to decide
2268  /// whether or not \p I is free.
2269  /// This method extends the behavior of the is[Z|FP]ExtFree family.
2270  /// In other words, if is[Z|FP]Free returns true, then this method
2271  /// returns true as well. The converse is not true.
2272  /// The target can perform the adequate checks by overriding isExtFreeImpl.
2273  /// \pre \p I must be a sign, zero, or fp extension.
2274  bool isExtFree(const Instruction *I) const {
2275  switch (I->getOpcode()) {
2276  case Instruction::FPExt:
2277  if (isFPExtFree(EVT::getEVT(I->getType()),
2278  EVT::getEVT(I->getOperand(0)->getType())))
2279  return true;
2280  break;
2281  case Instruction::ZExt:
2282  if (isZExtFree(I->getOperand(0)->getType(), I->getType()))
2283  return true;
2284  break;
2285  case Instruction::SExt:
2286  break;
2287  default:
2288  llvm_unreachable("Instruction is not an extension");
2289  }
2290  return isExtFreeImpl(I);
2291  }
2292 
2293  /// Return true if \p Load and \p Ext can form an ExtLoad.
2294  /// For example, in AArch64
2295  /// %L = load i8, i8* %ptr
2296  /// %E = zext i8 %L to i32
2297  /// can be lowered into one load instruction
2298  /// ldrb w0, [x0]
2299  bool isExtLoad(const LoadInst *Load, const Instruction *Ext,
2300  const DataLayout &DL) const {
2301  EVT VT = getValueType(DL, Ext->getType());
2302  EVT LoadVT = getValueType(DL, Load->getType());
2303 
2304  // If the load has other users and the truncate is not free, the ext
2305  // probably isn't free.
2306  if (!Load->hasOneUse() && (isTypeLegal(LoadVT) || !isTypeLegal(VT)) &&
2307  !isTruncateFree(Ext->getType(), Load->getType()))
2308  return false;
2309 
2310  // Check whether the target supports casts folded into loads.
2311  unsigned LType;
2312  if (isa<ZExtInst>(Ext))
2313  LType = ISD::ZEXTLOAD;
2314  else {
2315  assert(isa<SExtInst>(Ext) && "Unexpected ext type!");
2316  LType = ISD::SEXTLOAD;
2317  }
2318 
2319  return isLoadExtLegal(LType, VT, LoadVT);
2320  }
2321 
2322  /// Return true if any actual instruction that defines a value of type FromTy
2323  /// implicitly zero-extends the value to ToTy in the result register.
2324  ///
2325  /// The function should return true when it is likely that the truncate can
2326  /// be freely folded with an instruction defining a value of FromTy. If
2327  /// the defining instruction is unknown (because you're looking at a
2328  /// function argument, PHI, etc.) then the target may require an
2329  /// explicit truncate, which is not necessarily free, but this function
2330  /// does not deal with those cases.
2331  /// Targets must return false when FromTy >= ToTy.
2332  virtual bool isZExtFree(Type *FromTy, Type *ToTy) const {
2333  return false;
2334  }
2335 
2336  virtual bool isZExtFree(EVT FromTy, EVT ToTy) const {
2337  return false;
2338  }
2339 
2340  /// Return true if sign-extension from FromTy to ToTy is cheaper than
2341  /// zero-extension.
2342  virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const {
2343  return false;
2344  }
2345 
2346  /// Return true if sinking I's operands to the same basic block as I is
2347  /// profitable, e.g. because the operands can be folded into a target
2348  /// instruction during instruction selection. After calling the function
2349  /// \p Ops contains the Uses to sink ordered by dominance (dominating users
2350  /// come first).
2352  SmallVectorImpl<Use *> &Ops) const {
2353  return false;
2354  }
2355 
2356  /// Return true if the target supplies and combines to a paired load
2357  /// two loaded values of type LoadedType next to each other in memory.
2358  /// RequiredAlignment gives the minimal alignment constraints that must be met
2359  /// to be able to select this paired load.
2360  ///
2361  /// This information is *not* used to generate actual paired loads, but it is
2362  /// used to generate a sequence of loads that is easier to combine into a
2363  /// paired load.
2364  /// For instance, something like this:
2365  /// a = load i64* addr
2366  /// b = trunc i64 a to i32
2367  /// c = lshr i64 a, 32
2368  /// d = trunc i64 c to i32
2369  /// will be optimized into:
2370  /// b = load i32* addr1
2371  /// d = load i32* addr2
2372  /// Where addr1 = addr2 +/- sizeof(i32).
2373  ///
2374  /// In other words, unless the target performs a post-isel load combining,
2375  /// this information should not be provided because it will generate more
2376  /// loads.
2377  virtual bool hasPairedLoad(EVT /*LoadedType*/,
2378  unsigned & /*RequiredAlignment*/) const {
2379  return false;
2380  }
2381 
2382  /// Return true if the target has a vector blend instruction.
2383  virtual bool hasVectorBlend() const { return false; }
2384 
2385  /// Get the maximum supported factor for interleaved memory accesses.
2386  /// Default to be the minimum interleave factor: 2.
2387  virtual unsigned getMaxSupportedInterleaveFactor() const { return 2; }
2388 
2389  /// Lower an interleaved load to target specific intrinsics. Return
2390  /// true on success.
2391  ///
2392  /// \p LI is the vector load instruction.
2393  /// \p Shuffles is the shufflevector list to DE-interleave the loaded vector.
2394  /// \p Indices is the corresponding indices for each shufflevector.
2395  /// \p Factor is the interleave factor.
2396  virtual bool lowerInterleavedLoad(LoadInst *LI,
2398  ArrayRef<unsigned> Indices,
2399  unsigned Factor) const {
2400  return false;
2401  }
2402 
2403  /// Lower an interleaved store to target specific intrinsics. Return
2404  /// true on success.
2405  ///
2406  /// \p SI is the vector store instruction.
2407  /// \p SVI is the shufflevector to RE-interleave the stored vector.
2408  /// \p Factor is the interleave factor.
2410  unsigned Factor) const {
2411  return false;
2412  }
2413 
2414  /// Return true if zero-extending the specific node Val to type VT2 is free
2415  /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
2416  /// because it's folded such as X86 zero-extending loads).
2417  virtual bool isZExtFree(SDValue Val, EVT VT2) const {
2418  return isZExtFree(Val.getValueType(), VT2);
2419  }
2420 
2421  /// Return true if an fpext operation is free (for instance, because
2422  /// single-precision floating-point numbers are implicitly extended to
2423  /// double-precision).
2424  virtual bool isFPExtFree(EVT DestVT, EVT SrcVT) const {
2425  assert(SrcVT.isFloatingPoint() && DestVT.isFloatingPoint() &&
2426  "invalid fpext types");
2427  return false;
2428  }
2429 
2430  /// Return true if an fpext operation input to an \p Opcode operation is free
2431  /// (for instance, because half-precision floating-point numbers are
2432  /// implicitly extended to float-precision) for an FMA instruction.
2433  virtual bool isFPExtFoldable(unsigned Opcode, EVT DestVT, EVT SrcVT) const {
2434  assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
2435  "invalid fpext types");
2436  return isFPExtFree(DestVT, SrcVT);
2437  }
2438 
2439  /// Return true if folding a vector load into ExtVal (a sign, zero, or any
2440  /// extend node) is profitable.
2441  virtual bool isVectorLoadExtDesirable(SDValue ExtVal) const { return false; }
2442 
2443  /// Return true if an fneg operation is free to the point where it is never
2444  /// worthwhile to replace it with a bitwise operation.
2445  virtual bool isFNegFree(EVT VT) const {
2446  assert(VT.isFloatingPoint());
2447  return false;
2448  }
2449 
2450  /// Return true if an fabs operation is free to the point where it is never
2451  /// worthwhile to replace it with a bitwise operation.
2452  virtual bool isFAbsFree(EVT VT) const {
2453  assert(VT.isFloatingPoint());
2454  return false;
2455  }
2456 
2457  /// Return true if an FMA operation is faster than a pair of fmul and fadd
2458  /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
2459  /// returns true, otherwise fmuladd is expanded to fmul + fadd.
2460  ///
2461  /// NOTE: This may be called before legalization on types for which FMAs are
2462  /// not legal, but should return true if those types will eventually legalize
2463  /// to types that support FMAs. After legalization, it will only be called on
2464  /// types that support FMAs (via Legal or Custom actions)
2465  virtual bool isFMAFasterThanFMulAndFAdd(EVT) const {
2466  return false;
2467  }
2468 
2469  /// Return true if it's profitable to narrow operations of type VT1 to
2470  /// VT2. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
2471  /// i32 to i16.
2472  virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
2473  return false;
2474  }
2475 
2476  /// Return true if it is beneficial to convert a load of a constant to
2477  /// just the constant itself.
2478  /// On some targets it might be more efficient to use a combination of
2479  /// arithmetic instructions to materialize the constant instead of loading it
2480  /// from a constant pool.
2481  virtual bool shouldConvertConstantLoadToIntImm(const APInt &Imm,
2482  Type *Ty) const {
2483  return false;
2484  }
2485 
2486  /// Return true if EXTRACT_SUBVECTOR is cheap for extracting this result type
2487  /// from this source type with this index. This is needed because
2488  /// EXTRACT_SUBVECTOR usually has custom lowering that depends on the index of
2489  /// the first element, and only the target knows which lowering is cheap.
2490  virtual bool isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
2491  unsigned Index) const {
2492  return false;
2493  }
2494 
2495  /// Try to convert an extract element of a vector binary operation into an
2496  /// extract element followed by a scalar operation.
2497  virtual bool shouldScalarizeBinop(SDValue VecOp) const {
2498  return false;
2499  }
2500 
2501  /// Return true if extraction of a scalar element from the given vector type
2502  /// at the given index is cheap. For example, if scalar operations occur on
2503  /// the same register file as vector operations, then an extract element may
2504  /// be a sub-register rename rather than an actual instruction.
2505  virtual bool isExtractVecEltCheap(EVT VT, unsigned Index) const {
2506  return false;
2507  }
2508 
2509  /// Try to convert math with an overflow comparison into the corresponding DAG
2510  /// node operation. Targets may want to override this independently of whether
2511  /// the operation is legal/custom for the given type because it may obscure
2512  /// matching of other patterns.
2513  virtual bool shouldFormOverflowOp(unsigned Opcode, EVT VT) const {
2514  // TODO: The default logic is inherited from code in CodeGenPrepare.
2515  // The opcode should not make a difference by default?
2516  if (Opcode != ISD::UADDO)
2517  return false;
2518 
2519  // Allow the transform as long as we have an integer type that is not
2520  // obviously illegal and unsupported.
2521  if (VT.isVector())
2522  return false;
2523  return VT.isSimple() || !isOperationExpand(Opcode, VT);
2524  }
2525 
2526  // Return true if it is profitable to use a scalar input to a BUILD_VECTOR
2527  // even if the vector itself has multiple uses.
2528  virtual bool aggressivelyPreferBuildVectorSources(EVT VecVT) const {
2529  return false;
2530  }
2531 
2532  // Return true if CodeGenPrepare should consider splitting large offset of a
2533  // GEP to make the GEP fit into the addressing mode and can be sunk into the
2534  // same blocks of its users.
2535  virtual bool shouldConsiderGEPOffsetSplit() const { return false; }
2536 
2537  //===--------------------------------------------------------------------===//
2538  // Runtime Library hooks
2539  //
2540 
2541  /// Rename the default libcall routine name for the specified libcall.
2542  void setLibcallName(RTLIB::Libcall Call, const char *Name) {
2543  LibcallRoutineNames[Call] = Name;
2544  }
2545 
2546  /// Get the libcall routine name for the specified libcall.
2547  const char *getLibcallName(RTLIB::Libcall Call) const {
2548  return LibcallRoutineNames[Call];
2549  }
2550 
2551  /// Override the default CondCode to be used to test the result of the
2552  /// comparison libcall against zero.
2554  CmpLibcallCCs[Call] = CC;
2555  }
2556 
2557  /// Get the CondCode that's to be used to test the result of the comparison
2558  /// libcall against zero.
2560  return CmpLibcallCCs[Call];
2561  }
2562 
2563  /// Set the CallingConv that should be used for the specified libcall.
2565  LibcallCallingConvs[Call] = CC;
2566  }
2567 
2568  /// Get the CallingConv that should be used for the specified libcall.
2570  return LibcallCallingConvs[Call];
2571  }
2572 
2573  /// Execute target specific actions to finalize target lowering.
2574  /// This is used to set extra flags in MachineFrameInformation and freezing
2575  /// the set of reserved registers.
2576  /// The default implementation just freezes the set of reserved registers.
2577  virtual void finalizeLowering(MachineFunction &MF) const;
2578 
2579 private:
2580  const TargetMachine &TM;
2581 
2582  /// Tells the code generator that the target has multiple (allocatable)
2583  /// condition registers that can be used to store the results of comparisons
2584  /// for use by selects and conditional branches. With multiple condition
2585  /// registers, the code generator will not aggressively sink comparisons into
2586  /// the blocks of their users.
2587  bool HasMultipleConditionRegisters;
2588 
2589  /// Tells the code generator that the target has BitExtract instructions.
2590  /// The code generator will aggressively sink "shift"s into the blocks of
2591  /// their users if the users will generate "and" instructions which can be
2592  /// combined with "shift" to BitExtract instructions.
2593  bool HasExtractBitsInsn;
2594 
2595  /// Tells the code generator to bypass slow divide or remainder
2596  /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
2597  /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
2598  /// div/rem when the operands are positive and less than 256.
2599  DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
2600 
2601  /// Tells the code generator that it shouldn't generate extra flow control
2602  /// instructions and should attempt to combine flow control instructions via
2603  /// predication.
2604  bool JumpIsExpensive;
2605 
2606  /// This target prefers to use _setjmp to implement llvm.setjmp.
2607  ///
2608  /// Defaults to false.
2609  bool UseUnderscoreSetJmp;
2610 
2611  /// This target prefers to use _longjmp to implement llvm.longjmp.
2612  ///
2613  /// Defaults to false.
2614  bool UseUnderscoreLongJmp;
2615 
2616  /// Information about the contents of the high-bits in boolean values held in
2617  /// a type wider than i1. See getBooleanContents.
2618  BooleanContent BooleanContents;
2619 
2620  /// Information about the contents of the high-bits in boolean values held in
2621  /// a type wider than i1. See getBooleanContents.
2622  BooleanContent BooleanFloatContents;
2623 
2624  /// Information about the contents of the high-bits in boolean vector values
2625  /// when the element type is wider than i1. See getBooleanContents.
2626  BooleanContent BooleanVectorContents;
2627 
2628  /// The target scheduling preference: shortest possible total cycles or lowest
2629  /// register usage.
2630  Sched::Preference SchedPreferenceInfo;
2631 
2632  /// The size, in bytes, of the target's jmp_buf buffers
2633  unsigned JumpBufSize;
2634 
2635  /// The alignment, in bytes, of the target's jmp_buf buffers
2636  unsigned JumpBufAlignment;
2637 
2638  /// The minimum alignment that any argument on the stack needs to have.
2639  unsigned MinStackArgumentAlignment;
2640 
2641  /// The minimum function alignment (used when optimizing for size, and to
2642  /// prevent explicitly provided alignment from leading to incorrect code).
2643  unsigned MinFunctionAlignment;
2644 
2645  /// The preferred function alignment (used when alignment unspecified and
2646  /// optimizing for speed).
2647  unsigned PrefFunctionAlignment;
2648 
2649  /// The preferred loop alignment.
2650  unsigned PrefLoopAlignment;
2651 
2652  /// Size in bits of the maximum atomics size the backend supports.
2653  /// Accesses larger than this will be expanded by AtomicExpandPass.
2654  unsigned MaxAtomicSizeInBitsSupported;
2655 
2656  /// Size in bits of the minimum cmpxchg or ll/sc operation the
2657  /// backend supports.
2658  unsigned MinCmpXchgSizeInBits;
2659 
2660  /// This indicates if the target supports unaligned atomic operations.
2661  bool SupportsUnalignedAtomics;
2662 
2663  /// If set to a physical register, this specifies the register that
2664  /// llvm.savestack/llvm.restorestack should save and restore.
2665  unsigned StackPointerRegisterToSaveRestore;
2666 
2667  /// This indicates the default register class to use for each ValueType the
2668  /// target supports natively.
2669  const TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
2670  unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
2671  MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
2672 
2673  /// This indicates the "representative" register class to use for each
2674  /// ValueType the target supports natively. This information is used by the
2675  /// scheduler to track register pressure. By default, the representative
2676  /// register class is the largest legal super-reg register class of the
2677  /// register class of the specified type. e.g. On x86, i8, i16, and i32's
2678  /// representative class would be GR32.
2679  const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
2680 
2681  /// This indicates the "cost" of the "representative" register class for each
2682  /// ValueType. The cost is used by the scheduler to approximate register
2683  /// pressure.
2684  uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
2685 
2686  /// For any value types we are promoting or expanding, this contains the value
2687  /// type that we are changing to. For Expanded types, this contains one step
2688  /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
2689  /// (e.g. i64 -> i16). For types natively supported by the system, this holds
2690  /// the same type (e.g. i32 -> i32).
2691  MVT TransformToType[MVT::LAST_VALUETYPE];
2692 
2693  /// For each operation and each value type, keep a LegalizeAction that
2694  /// indicates how instruction selection should deal with the operation. Most
2695  /// operations are Legal (aka, supported natively by the target), but
2696  /// operations that are not should be described. Note that operations on
2697  /// non-legal value types are not described here.
2699 
2700  /// For each load extension type and each value type, keep a LegalizeAction
2701  /// that indicates how instruction selection should deal with a load of a
2702  /// specific value type and extension type. Uses 4-bits to store the action
2703  /// for each of the 4 load ext types.
2704  uint16_t LoadExtActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
2705 
2706  /// For each value type pair keep a LegalizeAction that indicates whether a
2707  /// truncating store of a specific value type and truncating type is legal.
2709 
2710  /// For each indexed mode and each value type, keep a pair of LegalizeAction
2711  /// that indicates how instruction selection should deal with the load /
2712  /// store.
2713  ///
2714  /// The first dimension is the value_type for the reference. The second
2715  /// dimension represents the various modes for load store.
2716  uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
2717 
2718  /// For each condition code (ISD::CondCode) keep a LegalizeAction that
2719  /// indicates how instruction selection should deal with the condition code.
2720  ///
2721  /// Because each CC action takes up 4 bits, we need to have the array size be
2722  /// large enough to fit all of the value types. This can be done by rounding
2723  /// up the MVT::LAST_VALUETYPE value to the next multiple of 8.
2724  uint32_t CondCodeActions[ISD::SETCC_INVALID][(MVT::LAST_VALUETYPE + 7) / 8];
2725 
2726 protected:
2728 
2729 private:
2730  LegalizeKind getTypeConversion(LLVMContext &Context, EVT VT) const;
2731 
2732  /// Targets can specify ISD nodes that they would like PerformDAGCombine
2733  /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
2734  /// array.
2735  unsigned char
2736  TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
2737 
2738  /// For operations that must be promoted to a specific type, this holds the
2739  /// destination type. This map should be sparse, so don't hold it as an
2740  /// array.
2741  ///
2742  /// Targets add entries to this map with AddPromotedToType(..), clients access
2743  /// this with getTypeToPromoteTo(..).
2744  std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
2745  PromoteToType;
2746 
2747  /// Stores the name each libcall.
2748  const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL + 1];
2749 
2750  /// The ISD::CondCode that should be used to test the result of each of the
2751  /// comparison libcall against zero.
2752  ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
2753 
2754  /// Stores the CallingConv that should be used for each libcall.
2755  CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
2756 
2757  /// Set default libcall names and calling conventions.
2758  void InitLibcalls(const Triple &TT);
2759 
2760 protected:
2761  /// Return true if the extension represented by \p I is free.
2762  /// \pre \p I is a sign, zero, or fp extension and
2763  /// is[Z|FP]ExtFree of the related types is not true.
2764  virtual bool isExtFreeImpl(const Instruction *I) const { return false; }
2765 
2766  /// Depth that GatherAllAliases should should continue looking for chain
2767  /// dependencies when trying to find a more preferable chain. As an
2768  /// approximation, this should be more than the number of consecutive stores
2769  /// expected to be merged.
2771 
2772  /// Specify maximum number of store instructions per memset call.
2773  ///
2774  /// When lowering \@llvm.memset this field specifies the maximum number of
2775  /// store operations that may be substituted for the call to memset. Targets
2776  /// must set this value based on the cost threshold for that target. Targets
2777  /// should assume that the memset will be done using as many of the largest
2778  /// store operations first, followed by smaller ones, if necessary, per
2779  /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
2780  /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
2781  /// store. This only applies to setting a constant array of a constant size.
2783 
2784  /// Maximum number of stores operations that may be substituted for the call
2785  /// to memset, used for functions with OptSize attribute.
2787 
2788  /// Specify maximum bytes of store instructions per memcpy call.
2789  ///
2790  /// When lowering \@llvm.memcpy this field specifies the maximum number of
2791  /// store operations that may be substituted for a call to memcpy. Targets
2792  /// must set this value based on the cost threshold for that target. Targets
2793  /// should assume that the memcpy will be done using as many of the largest
2794  /// store operations first, followed by smaller ones, if necessary, per
2795  /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
2796  /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
2797  /// and one 1-byte store. This only applies to copying a constant array of
2798  /// constant size.
2800 
2801 
2802  /// \brief Specify max number of store instructions to glue in inlined memcpy.
2803  ///
2804  /// When memcpy is inlined based on MaxStoresPerMemcpy, specify maximum number
2805  /// of store instructions to keep together. This helps in pairing and
2806  // vectorization later on.
2807  unsigned MaxGluedStoresPerMemcpy = 0;
2808 
2809  /// Maximum number of store operations that may be substituted for a call to
2810  /// memcpy, used for functions with OptSize attribute.
2814 
2815  /// Specify maximum bytes of store instructions per memmove call.
2816  ///
2817  /// When lowering \@llvm.memmove this field specifies the maximum number of
2818  /// store instructions that may be substituted for a call to memmove. Targets
2819  /// must set this value based on the cost threshold for that target. Targets
2820  /// should assume that the memmove will be done using as many of the largest
2821  /// store operations first, followed by smaller ones, if necessary, per
2822  /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
2823  /// with 8-bit alignment would result in nine 1-byte stores. This only
2824  /// applies to copying a constant array of constant size.
2826 
2827  /// Maximum number of store instructions that may be substituted for a call to
2828  /// memmove, used for functions with OptSize attribute.
2830 
2831  /// Tells the code generator that select is more expensive than a branch if
2832  /// the branch is usually predicted right.
2834 
2835  /// \see enableExtLdPromotion.
2837 
2838  /// Return true if the value types that can be represented by the specified
2839  /// register class are all legal.
2840  bool isLegalRC(const TargetRegisterInfo &TRI,
2841  const TargetRegisterClass &RC) const;
2842 
2843  /// Replace/modify any TargetFrameIndex operands with a targte-dependent
2844  /// sequence of memory operands that is recognized by PrologEpilogInserter.
2845  MachineBasicBlock *emitPatchPoint(MachineInstr &MI,
2846  MachineBasicBlock *MBB) const;
2847 
2848  /// Replace/modify the XRay custom event operands with target-dependent
2849  /// details.
2850  MachineBasicBlock *emitXRayCustomEvent(MachineInstr &MI,
2851  MachineBasicBlock *MBB) const;
2852 
2853  /// Replace/modify the XRay typed event operands with target-dependent
2854  /// details.
2855  MachineBasicBlock *emitXRayTypedEvent(MachineInstr &MI,
2856  MachineBasicBlock *MBB) const;
2857 };
2858 
2859 /// This class defines information used to lower LLVM code to legal SelectionDAG
2860 /// operators that the target instruction selector can accept natively.
2861 ///
2862 /// This class also defines callbacks that targets must implement to lower
2863 /// target-specific constructs to SelectionDAG operators.
2865 public:
2866  struct DAGCombinerInfo;
2867 
2868  TargetLowering(const TargetLowering &) = delete;
2869  TargetLowering &operator=(const TargetLowering &) = delete;
2870 
2871  /// NOTE: The TargetMachine owns TLOF.
2872  explicit TargetLowering(const TargetMachine &TM);
2873 
2874  bool isPositionIndependent() const;
2875 
2876  virtual bool isSDNodeSourceOfDivergence(const SDNode *N,
2877  FunctionLoweringInfo *FLI,
2878  LegacyDivergenceAnalysis *DA) const {
2879  return false;
2880  }
2881 
2882  virtual bool isSDNodeAlwaysUniform(const SDNode * N) const {
2883  return false;
2884  }
2885 
2886  /// Returns true by value, base pointer and offset pointer and addressing mode
2887  /// by reference if the node's address can be legally represented as
2888  /// pre-indexed load / store address.
2889  virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
2890  SDValue &/*Offset*/,
2891  ISD::MemIndexedMode &/*AM*/,
2892  SelectionDAG &/*DAG*/) const {
2893  return false;
2894  }
2895 
2896  /// Returns true by value, base pointer and offset pointer and addressing mode
2897  /// by reference if this node can be combined with a load / store to form a
2898  /// post-indexed load / store.
2899  virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
2900  SDValue &/*Base*/,
2901  SDValue &/*Offset*/,
2902  ISD::MemIndexedMode &/*AM*/,
2903  SelectionDAG &/*DAG*/) const {
2904  return false;
2905  }
2906 
2907  /// Return the entry encoding for a jump table in the current function. The
2908  /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
2909  virtual unsigned getJumpTableEncoding() const;
2910 
2911  virtual const MCExpr *
2913  const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
2914  MCContext &/*Ctx*/) const {
2915  llvm_unreachable("Need to implement this hook if target has custom JTIs");
2916  }
2917 
2918  /// Returns relocation base for the given PIC jumptable.
2919  virtual SDValue getPICJumpTableRelocBase(SDValue Table,
2920  SelectionDAG &DAG) const;
2921 
2922  /// This returns the relocation base for the given PIC jumptable, the same as
2923  /// getPICJumpTableRelocBase, but as an MCExpr.
2924  virtual const MCExpr *
2925  getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2926  unsigned JTI, MCContext &Ctx) const;
2927 
2928  /// Return true if folding a constant offset with the given GlobalAddress is
2929  /// legal. It is frequently not legal in PIC relocation models.
2930  virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
2931 
2933  SDValue &Chain) const;
2934 
2935  void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
2936  SDValue &NewRHS, ISD::CondCode &CCCode,
2937  const SDLoc &DL) const;
2938 
2939  /// Returns a pair of (return value, chain).
2940  /// It is an error to pass RTLIB::UNKNOWN_LIBCALL as \p LC.
2941  std::pair<SDValue, SDValue> makeLibCall(
2942  SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT, ArrayRef<SDValue> Ops,
2943  bool isSigned, const SDLoc &dl, bool doesNotReturn = false,
2944  bool isReturnValueUsed = true, bool isPostTypeLegalization = false) const;
2945 
2946  /// Check whether parameters to a call that are passed in callee saved
2947  /// registers are the same as from the calling function. This needs to be
2948  /// checked for tail call eligibility.
2949  bool parametersInCSRMatch(const MachineRegisterInfo &MRI,
2950  const uint32_t *CallerPreservedMask,
2951  const SmallVectorImpl<CCValAssign> &ArgLocs,
2952  const SmallVectorImpl<SDValue> &OutVals) const;
2953 
2954  //===--------------------------------------------------------------------===//
2955  // TargetLowering Optimization Methods
2956  //
2957 
2958  /// A convenience struct that encapsulates a DAG, and two SDValues for
2959  /// returning information from TargetLowering to its clients that want to
2960  /// combine.
2963  bool LegalTys;
2964  bool LegalOps;
2967 
2969  bool LT, bool LO) :
2970  DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
2971 
2972  bool LegalTypes() const { return LegalTys; }
2973  bool LegalOperations() const { return LegalOps; }
2974 
2976  Old = O;
2977  New = N;
2978  return true;
2979  }
2980  };
2981 
2982  /// Determines the optimal series of memory ops to replace the memset / memcpy.
2983  /// Return true if the number of memory ops is below the threshold (Limit).
2984  /// It returns the types of the sequence of memory ops to perform
2985  /// memset / memcpy by reference.
2986  bool findOptimalMemOpLowering(std::vector<EVT> &MemOps,
2987  unsigned Limit, uint64_t Size,
2988  unsigned DstAlign, unsigned SrcAlign,
2989  bool IsMemset,
2990  bool ZeroMemset,
2991  bool MemcpyStrSrc,
2992  bool AllowOverlap,
2993  unsigned DstAS, unsigned SrcAS,
2994  const AttributeList &FuncAttributes) const;
2995 
2996  /// Check to see if the specified operand of the specified instruction is a
2997  /// constant integer. If so, check to see if there are any bits set in the
2998  /// constant that are not demanded. If so, shrink the constant and return
2999  /// true.
3000  bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded,
3001  TargetLoweringOpt &TLO) const;
3002 
3003  // Target hook to do target-specific const optimization, which is called by
3004  // ShrinkDemandedConstant. This function should return true if the target
3005  // doesn't want ShrinkDemandedConstant to further optimize the constant.
3006  virtual bool targetShrinkDemandedConstant(SDValue Op, const APInt &Demanded,
3007  TargetLoweringOpt &TLO) const {
3008  return false;
3009  }
3010 
3011  /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. This
3012  /// uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
3013  /// generalized for targets with other types of implicit widening casts.
3014  bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
3015  TargetLoweringOpt &TLO) const;
3016 
3017  /// Look at Op. At this point, we know that only the DemandedBits bits of the
3018  /// result of Op are ever used downstream. If we can use this information to
3019  /// simplify Op, create a new simplified DAG node and return true, returning
3020  /// the original and new nodes in Old and New. Otherwise, analyze the
3021  /// expression and return a mask of KnownOne and KnownZero bits for the
3022  /// expression (used to simplify the caller). The KnownZero/One bits may only
3023  /// be accurate for those bits in the Demanded masks.
3024  /// \p AssumeSingleUse When this parameter is true, this function will
3025  /// attempt to simplify \p Op even if there are multiple uses.
3026  /// Callers are responsible for correctly updating the DAG based on the
3027  /// results of this function, because simply replacing replacing TLO.Old
3028  /// with TLO.New will be incorrect when this parameter is true and TLO.Old
3029  /// has multiple uses.
3030  bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
3031  const APInt &DemandedElts, KnownBits &Known,
3032  TargetLoweringOpt &TLO, unsigned Depth = 0,
3033  bool AssumeSingleUse = false) const;
3034 
3035  /// Helper wrapper around SimplifyDemandedBits, demanding all elements.
3036  /// Adds Op back to the worklist upon success.
3037  bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
3038  KnownBits &Known, TargetLoweringOpt &TLO,
3039  unsigned Depth = 0,
3040  bool AssumeSingleUse = false) const;
3041 
3042  /// Helper wrapper around SimplifyDemandedBits.
3043  /// Adds Op back to the worklist upon success.
3044  bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
3045  DAGCombinerInfo &DCI) const;
3046 
3047  /// Look at Vector Op. At this point, we know that only the DemandedElts
3048  /// elements of the result of Op are ever used downstream. If we can use
3049  /// this information to simplify Op, create a new simplified DAG node and
3050  /// return true, storing the original and new nodes in TLO.
3051  /// Otherwise, analyze the expression and return a mask of KnownUndef and
3052  /// KnownZero elements for the expression (used to simplify the caller).
3053  /// The KnownUndef/Zero elements may only be accurate for those bits
3054  /// in the DemandedMask.
3055  /// \p AssumeSingleUse When this parameter is true, this function will
3056  /// attempt to simplify \p Op even if there are multiple uses.
3057  /// Callers are responsible for correctly updating the DAG based on the
3058  /// results of this function, because simply replacing replacing TLO.Old
3059  /// with TLO.New will be incorrect when this parameter is true and TLO.Old
3060  /// has multiple uses.
3061  bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedEltMask,
3062  APInt &KnownUndef, APInt &KnownZero,
3063  TargetLoweringOpt &TLO, unsigned Depth = 0,
3064  bool AssumeSingleUse = false) const;
3065 
3066  /// Helper wrapper around SimplifyDemandedVectorElts.
3067  /// Adds Op back to the worklist upon success.
3068  bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedElts,
3069  APInt &KnownUndef, APInt &KnownZero,
3070  DAGCombinerInfo &DCI) const;
3071 
3072  /// Determine which of the bits specified in Mask are known to be either zero
3073  /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
3074  /// argument allows us to only collect the known bits that are shared by the
3075  /// requested vector elements.
3076  virtual void computeKnownBitsForTargetNode(const SDValue Op,
3077  KnownBits &Known,
3078  const APInt &DemandedElts,
3079  const SelectionDAG &DAG,
3080  unsigned Depth = 0) const;
3081 
3082  /// Determine which of the bits of FrameIndex \p FIOp are known to be 0.
3083  /// Default implementation computes low bits based on alignment
3084  /// information. This should preserve known bits passed into it.
3085  virtual void computeKnownBitsForFrameIndex(const SDValue FIOp,
3086  KnownBits &Known,
3087  const APInt &DemandedElts,
3088  const SelectionDAG &DAG,
3089  unsigned Depth = 0) const;
3090 
3091  /// This method can be implemented by targets that want to expose additional
3092  /// information about sign bits to the DAG Combiner. The DemandedElts
3093  /// argument allows us to only collect the minimum sign bits that are shared
3094  /// by the requested vector elements.
3095  virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
3096  const APInt &DemandedElts,
3097  const SelectionDAG &DAG,
3098  unsigned Depth = 0) const;
3099 
3100  /// Attempt to simplify any target nodes based on the demanded vector
3101  /// elements, returning true on success. Otherwise, analyze the expression and
3102  /// return a mask of KnownUndef and KnownZero elements for the expression
3103  /// (used to simplify the caller). The KnownUndef/Zero elements may only be
3104  /// accurate for those bits in the DemandedMask.
3105  virtual bool SimplifyDemandedVectorEltsForTargetNode(
3106  SDValue Op, const APInt &DemandedElts, APInt &KnownUndef,
3107  APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth = 0) const;
3108 
3109  /// Attempt to simplify any target nodes based on the demanded bits/elts,
3110  /// returning true on success. Otherwise, analyze the
3111  /// expression and return a mask of KnownOne and KnownZero bits for the
3112  /// expression (used to simplify the caller). The KnownZero/One bits may only
3113  /// be accurate for those bits in the Demanded masks.
3114  virtual bool SimplifyDemandedBitsForTargetNode(SDValue Op,
3115  const APInt &DemandedBits,
3116  const APInt &DemandedElts,
3117  KnownBits &Known,
3118  TargetLoweringOpt &TLO,
3119  unsigned Depth = 0) const;
3120 
3121  /// If \p SNaN is false, \returns true if \p Op is known to never be any
3122  /// NaN. If \p sNaN is true, returns if \p Op is known to never be a signaling
3123  /// NaN.
3124  virtual bool isKnownNeverNaNForTargetNode(SDValue Op,
3125  const SelectionDAG &DAG,
3126  bool SNaN = false,
3127  unsigned Depth = 0) const;
3129  void *DC; // The DAG Combiner object.
3132 
3133  public:
3135 
3136  DAGCombinerInfo(SelectionDAG &dag, CombineLevel level, bool cl, void *dc)
3137  : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
3138 
3139  bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
3140  bool isBeforeLegalizeOps() const { return Level < AfterLegalizeVectorOps; }
3141  bool isAfterLegalizeDAG() const {
3142  return Level == AfterLegalizeDAG;
3143  }
3145  bool isCalledByLegalizer() const { return CalledByLegalizer; }
3146 
3147  void AddToWorklist(SDNode *N);
3148  SDValue CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo = true);
3149  SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
3150  SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
3151 
3152  void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
3153  };
3154 
3155  /// Return if the N is a constant or constant vector equal to the true value
3156  /// from getBooleanContents().
3157  bool isConstTrueVal(const SDNode *N) const;
3158 
3159  /// Return if the N is a constant or constant vector equal to the false value
3160  /// from getBooleanContents().
3161  bool isConstFalseVal(const SDNode *N) const;
3162 
3163  /// Return if \p N is a True value when extended to \p VT.
3164  bool isExtendedTrueVal(const ConstantSDNode *N, EVT VT, bool SExt) const;
3165 
3166  /// Try to simplify a setcc built with the specified operands and cc. If it is
3167  /// unable to simplify it, return a null SDValue.
3168  SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
3169  bool foldBooleans, DAGCombinerInfo &DCI,
3170  const SDLoc &dl) const;
3171 
3172  // For targets which wrap address, unwrap for analysis.
3173  virtual SDValue unwrapAddress(SDValue N) const { return N; }
3174 
3175  /// Returns true (and the GlobalValue and the offset) if the node is a
3176  /// GlobalAddress + offset.
3177  virtual bool
3178  isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
3179 
3180  /// This method will be invoked for all target nodes and for any
3181  /// target-independent nodes that the target has registered with invoke it
3182  /// for.
3183  ///
3184  /// The semantics are as follows:
3185  /// Return Value:
3186  /// SDValue.Val == 0 - No change was made
3187  /// SDValue.Val == N - N was replaced, is dead, and is already handled.
3188  /// otherwise - N should be replaced by the returned Operand.
3189  ///
3190  /// In addition, methods provided by DAGCombinerInfo may be used to perform
3191  /// more complex transformations.
3192  ///
3193  virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
3194 
3195  /// Return true if it is profitable to move this shift by a constant amount
3196  /// though its operand, adjusting any immediate operands as necessary to
3197  /// preserve semantics. This transformation may not be desirable if it
3198  /// disrupts a particularly auspicious target-specific tree (e.g. bitfield
3199  /// extraction in AArch64). By default, it returns true.
3200  ///
3201  /// @param N the shift node
3202  /// @param Level the current DAGCombine legalization level.
3203  virtual bool isDesirableToCommuteWithShift(const SDNode *N,
3204  CombineLevel Level) const {
3205  return true;
3206  }
3207 
3208  // Return true if it is profitable to combine a BUILD_VECTOR with a stride-pattern
3209  // to a shuffle and a truncate.
3210  // Example of such a combine:
3211  // v4i32 build_vector((extract_elt V, 1),
3212  // (extract_elt V, 3),
3213  // (extract_elt V, 5),
3214  // (extract_elt V, 7))
3215  // -->
3216  // v4i32 truncate (bitcast (shuffle<1,u,3,u,5,u,7,u> V, u) to v4i64)
3218  ArrayRef<int> ShuffleMask, EVT SrcVT, EVT TruncVT) const {
3219  return false;
3220  }
3221 
3222  /// Return true if the target has native support for the specified value type
3223  /// and it is 'desirable' to use the type for the given node type. e.g. On x86
3224  /// i16 is legal, but undesirable since i16 instruction encodings are longer
3225  /// and some i16 instructions are slow.
3226  virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
3227  // By default, assume all legal types are desirable.
3228  return isTypeLegal(VT);
3229  }
3230 
3231  /// Return true if it is profitable for dag combiner to transform a floating
3232  /// point op of specified opcode to a equivalent op of an integer
3233  /// type. e.g. f32 load -> i32 load can be profitable on ARM.
3234  virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
3235  EVT /*VT*/) const {
3236  return false;
3237  }
3238 
3239  /// This method query the target whether it is beneficial for dag combiner to
3240  /// promote the specified node. If true, it should return the desired
3241  /// promotion type by reference.
3242  virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
3243  return false;
3244  }
3245 
3246  /// Return true if the target supports swifterror attribute. It optimizes
3247  /// loads and stores to reading and writing a specific register.
3248  virtual bool supportSwiftError() const {
3249  return false;
3250  }
3251 
3252  /// Return true if the target supports that a subset of CSRs for the given
3253  /// machine function is handled explicitly via copies.
3254  virtual bool supportSplitCSR(MachineFunction *MF) const {
3255  return false;
3256  }
3257 
3258  /// Perform necessary initialization to handle a subset of CSRs explicitly
3259  /// via copies. This function is called at the beginning of instruction
3260  /// selection.
3262  llvm_unreachable("Not Implemented");
3263  }
3264 
3265  /// Insert explicit copies in entry and exit blocks. We copy a subset of
3266  /// CSRs to virtual registers in the entry block, and copy them back to
3267  /// physical registers in the exit blocks. This function is called at the end
3268  /// of instruction selection.
3269  virtual void insertCopiesSplitCSR(
3271  const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
3272  llvm_unreachable("Not Implemented");
3273  }
3274 
3275  //===--------------------------------------------------------------------===//
3276  // Lowering methods - These methods must be implemented by targets so that
3277  // the SelectionDAGBuilder code knows how to lower these.
3278  //
3279 
3280  /// This hook must be implemented to lower the incoming (formal) arguments,
3281  /// described by the Ins array, into the specified DAG. The implementation
3282  /// should fill in the InVals array with legal-type argument values, and
3283  /// return the resulting token chain value.
3285  SDValue /*Chain*/, CallingConv::ID /*CallConv*/, bool /*isVarArg*/,
3286  const SmallVectorImpl<ISD::InputArg> & /*Ins*/, const SDLoc & /*dl*/,
3287  SelectionDAG & /*DAG*/, SmallVectorImpl<SDValue> & /*InVals*/) const {
3288  llvm_unreachable("Not Implemented");
3289  }
3290 
3291  /// This structure contains all information that is necessary for lowering
3292  /// calls. It is passed to TLI::LowerCallTo when the SelectionDAG builder
3293  /// needs to lower a call, and targets will see this struct in their LowerCall
3294  /// implementation.
3297  Type *RetTy = nullptr;
3298  bool RetSExt : 1;
3299  bool RetZExt : 1;
3300  bool IsVarArg : 1;
3301  bool IsInReg : 1;
3302  bool DoesNotReturn : 1;
3304  bool IsConvergent : 1;
3305  bool IsPatchPoint : 1;
3306 
3307  // IsTailCall should be modified by implementations of
3308  // TargetLowering::LowerCall that perform tail call conversions.
3309  bool IsTailCall = false;
3310 
3311  // Is Call lowering done post SelectionDAG type legalization.
3312  bool IsPostTypeLegalization = false;
3313 
3314  unsigned NumFixedArgs = -1;
3317  ArgListTy Args;
3325 
3327  : RetSExt(false), RetZExt(false), IsVarArg(false), IsInReg(false),
3328  DoesNotReturn(false), IsReturnValueUsed(true), IsConvergent(false),
3329  IsPatchPoint(false), DAG(DAG) {}
3330 
3332  DL = dl;
3333  return *this;
3334  }
3335 
3337  Chain = InChain;
3338  return *this;
3339  }
3340 
3341  // setCallee with target/module-specific attributes
3343  SDValue Target, ArgListTy &&ArgsList) {
3344  RetTy = ResultType;
3345  Callee = Target;
3346  CallConv = CC;
3347  NumFixedArgs = ArgsList.size();
3348  Args = std::move(ArgsList);
3349 
3351  &(DAG.getMachineFunction()), CC, Args);
3352  return *this;
3353  }
3354 
3356  SDValue Target, ArgListTy &&ArgsList) {
3357  RetTy = ResultType;
3358  Callee = Target;
3359  CallConv = CC;
3360  NumFixedArgs = ArgsList.size();
3361  Args = std::move(ArgsList);
3362  return *this;
3363  }
3364 
3366  SDValue Target, ArgListTy &&ArgsList,
3367  ImmutableCallSite Call) {
3368  RetTy = ResultType;
3369 
3370  IsInReg = Call.hasRetAttr(Attribute::InReg);
3371  DoesNotReturn =
3372  Call.doesNotReturn() ||
3373  (!Call.isInvoke() &&
3374  isa<UnreachableInst>(Call.getInstruction()->getNextNode()));
3375  IsVarArg = FTy->isVarArg();
3376  IsReturnValueUsed = !Call.getInstruction()->use_empty();
3377  RetSExt = Call.hasRetAttr(Attribute::SExt);
3378  RetZExt = Call.hasRetAttr(Attribute::ZExt);
3379 
3380  Callee = Target;
3381 
3382  CallConv = Call.getCallingConv();
3383  NumFixedArgs = FTy->getNumParams();
3384  Args = std::move(ArgsList);
3385 
3386  CS = Call;
3387 
3388  return *this;
3389  }
3390 
3392  IsInReg = Value;
3393  return *this;
3394  }
3395 
3397  DoesNotReturn = Value;
3398  return *this;
3399  }
3400 
3402  IsVarArg = Value;
3403  return *this;
3404  }
3405 
3407  IsTailCall = Value;
3408  return *this;
3409  }
3410 
3412  IsReturnValueUsed = !Value;
3413  return *this;
3414  }
3415 
3417  IsConvergent = Value;
3418  return *this;
3419  }
3420 
3422  RetSExt = Value;
3423  return *this;
3424  }
3425 
3427  RetZExt = Value;
3428  return *this;
3429  }
3430 
3432  IsPatchPoint = Value;
3433  return *this;
3434  }
3435 
3437  IsPostTypeLegalization = Value;
3438  return *this;
3439  }
3440 
3441  ArgListTy &getArgs() {
3442  return Args;
3443  }
3444  };
3445 
3446  /// This function lowers an abstract call to a function into an actual call.
3447  /// This returns a pair of operands. The first element is the return value
3448  /// for the function (if RetTy is not VoidTy). The second element is the
3449  /// outgoing token chain. It calls LowerCall to do the actual lowering.
3450  std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
3451 
3452  /// This hook must be implemented to lower calls into the specified
3453  /// DAG. The outgoing arguments to the call are described by the Outs array,
3454  /// and the values to be returned by the call are described by the Ins
3455  /// array. The implementation should fill in the InVals array with legal-type
3456  /// return values from the call, and return the resulting token chain value.
3457  virtual SDValue
3459  SmallVectorImpl<SDValue> &/*InVals*/) const {
3460  llvm_unreachable("Not Implemented");
3461  }
3462 
3463  /// Target-specific cleanup for formal ByVal parameters.
3464  virtual void HandleByVal(CCState *, unsigned &, unsigned) const {}
3465 
3466  /// This hook should be implemented to check whether the return values
3467  /// described by the Outs array can fit into the return registers. If false
3468  /// is returned, an sret-demotion is performed.
3469  virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
3470  MachineFunction &/*MF*/, bool /*isVarArg*/,
3471  const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
3472  LLVMContext &/*Context*/) const
3473  {
3474  // Return true by default to get preexisting behavior.
3475  return true;
3476  }
3477 
3478  /// This hook must be implemented to lower outgoing return values, described
3479  /// by the Outs array, into the specified DAG. The implementation should
3480  /// return the resulting token chain value.
3481  virtual SDValue LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
3482  bool /*isVarArg*/,
3483  const SmallVectorImpl<ISD::OutputArg> & /*Outs*/,
3484  const SmallVectorImpl<SDValue> & /*OutVals*/,
3485  const SDLoc & /*dl*/,
3486  SelectionDAG & /*DAG*/) const {
3487  llvm_unreachable("Not Implemented");
3488  }
3489 
3490  /// Return true if result of the specified node is used by a return node
3491  /// only. It also compute and return the input chain for the tail call.
3492  ///
3493  /// This is used to determine whether it is possible to codegen a libcall as
3494  /// tail call at legalization time.
3495  virtual bool isUsedByReturnOnly(SDNode *, SDValue &/*Chain*/) const {
3496  return false;
3497  }
3498 
3499  /// Return true if the target may be able emit the call instruction as a tail
3500  /// call. This is used by optimization passes to determine if it's profitable
3501  /// to duplicate return instructions to enable tailcall optimization.
3502  virtual bool mayBeEmittedAsTailCall(const CallInst *) const {
3503  return false;
3504  }
3505 
3506  /// Return the builtin name for the __builtin___clear_cache intrinsic
3507  /// Default is to invoke the clear cache library call
3508  virtual const char * getClearCacheBuiltinName() const {
3509  return "__clear_cache";
3510  }
3511 
3512  /// Return the register ID of the name passed in. Used by named register
3513  /// global variables extension. There is no target-independent behaviour
3514  /// so the default action is to bail.
3515  virtual unsigned getRegisterByName(const char* RegName, EVT VT,
3516  SelectionDAG &DAG) const {
3517  report_fatal_error("Named registers not implemented for this target");
3518  }
3519 
3520  /// Return the type that should be used to zero or sign extend a
3521  /// zeroext/signext integer return value. FIXME: Some C calling conventions
3522  /// require the return type to be promoted, but this is not true all the time,
3523  /// e.g. i1/i8/i16 on x86/x86_64. It is also not necessary for non-C calling
3524  /// conventions. The frontend should handle this and include all of the
3525  /// necessary information.
3527  ISD::NodeType /*ExtendKind*/) const {
3528  EVT MinVT = getRegisterType(Context, MVT::i32);
3529  return VT.bitsLT(MinVT) ? MinVT : VT;
3530  }
3531 
3532  /// For some targets, an LLVM struct type must be broken down into multiple
3533  /// simple types, but the calling convention specifies that the entire struct
3534  /// must be passed in a block of consecutive registers.
3535  virtual bool
3537  bool isVarArg) const {
3538  return false;
3539  }
3540 
3541  /// For most targets, an LLVM type must be broken down into multiple
3542  /// smaller types. Usually the halves are ordered according to the endianness
3543  /// but for some platform that would break. So this method will default to
3544  /// matching the endianness but can be overridden.
3545  virtual bool
3547  return DL.isLittleEndian();
3548  }
3549 
3550  /// Returns a 0 terminated array of registers that can be safely used as
3551  /// scratch registers.
3552  virtual const MCPhysReg *getScratchRegisters(CallingConv::ID CC) const {
3553  return nullptr;
3554  }
3555 
3556  /// This callback is used to prepare for a volatile or atomic load.
3557  /// It takes a chain node as input and returns the chain for the load itself.
3558  ///
3559  /// Having a callback like this is necessary for targets like SystemZ,
3560  /// which allows a CPU to reuse the result of a previous load indefinitely,
3561  /// even if a cache-coherent store is performed by another CPU. The default
3562  /// implementation does nothing.
3564  SelectionDAG &DAG) const {
3565  return Chain;
3566  }
3567 
3568  /// This callback is used to inspect load/store instructions and add
3569  /// target-specific MachineMemOperand flags to them. The default
3570  /// implementation does nothing.
3573  }
3574 
3575  /// This callback is invoked by the type legalizer to legalize nodes with an
3576  /// illegal operand type but legal result types. It replaces the
3577  /// LowerOperation callback in the type Legalizer. The reason we can not do
3578  /// away with LowerOperation entirely is that LegalizeDAG isn't yet ready to
3579  /// use this callback.
3580  ///
3581  /// TODO: Consider merging with ReplaceNodeResults.
3582  ///
3583  /// The target places new result values for the node in Results (their number
3584  /// and types must exactly match those of the original return values of
3585  /// the node), or leaves Results empty, which indicates that the node is not
3586  /// to be custom lowered after all.
3587  /// The default implementation calls LowerOperation.
3588  virtual void LowerOperationWrapper(SDNode *N,
3590  SelectionDAG &DAG) const;
3591 
3592  /// This callback is invoked for operations that are unsupported by the
3593  /// target, which are registered to use 'custom' lowering, and whose defined
3594  /// values are all legal. If the target has no operations that require custom
3595  /// lowering, it need not implement this. The default implementation of this
3596  /// aborts.
3597  virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
3598 
3599  /// This callback is invoked when a node result type is illegal for the
3600  /// target, and the operation was registered to use 'custom' lowering for that
3601  /// result type. The target places new result values for the node in Results
3602  /// (their number and types must exactly match those of the original return
3603  /// values of the node), or leaves Results empty, which indicates that the
3604  /// node is not to be custom lowered after all.
3605  ///
3606  /// If the target has no operations that require custom lowering, it need not
3607  /// implement this. The default implementation aborts.
3608  virtual void ReplaceNodeResults(SDNode * /*N*/,
3609  SmallVectorImpl<SDValue> &/*Results*/,
3610  SelectionDAG &/*DAG*/) const {
3611  llvm_unreachable("ReplaceNodeResults not implemented for this target!");
3612  }
3613 
3614  /// This method returns the name of a target specific DAG node.
3615  virtual const char *getTargetNodeName(unsigned Opcode) const;
3616 
3617  /// This method returns a target specific FastISel object, or null if the
3618  /// target does not support "fast" ISel.
3620  const TargetLibraryInfo *) const {
3621  return nullptr;
3622  }
3623 
3624  bool verifyReturnAddressArgumentIsConstant(SDValue Op,
3625  SelectionDAG &DAG) const;
3626 
3627  //===--------------------------------------------------------------------===//
3628  // Inline Asm Support hooks
3629  //
3630 
3631  /// This hook allows the target to expand an inline asm call to be explicit
3632  /// llvm code if it wants to. This is useful for turning simple inline asms
3633  /// into LLVM intrinsics, which gives the compiler more information about the
3634  /// behavior of the code.
3635  virtual bool ExpandInlineAsm(CallInst *) const {
3636  return false;
3637  }
3638 
3640  C_Register, // Constraint represents specific register(s).
3641  C_RegisterClass, // Constraint represents any of register(s) in class.
3642  C_Memory, // Memory constraint.
3643  C_Other, // Something else.
3644  C_Unknown // Unsupported constraint.
3645  };
3646 
3648  // Generic weights.
3649  CW_Invalid = -1, // No match.
3650  CW_Okay = 0, // Acceptable.
3651  CW_Good = 1, // Good weight.
3652  CW_Better = 2, // Better weight.
3653  CW_Best = 3, // Best weight.
3654 
3655  // Well-known weights.
3656  CW_SpecificReg = CW_Okay, // Specific register operands.
3657  CW_Register = CW_Good, // Register operands.
3658  CW_Memory = CW_Better, // Memory operands.
3659  CW_Constant = CW_Best, // Constant operand.
3660  CW_Default = CW_Okay // Default or don't know type.
3661  };
3662 
3663  /// This contains information for each constraint that we are lowering.
3665  /// This contains the actual string for the code, like "m". TargetLowering
3666  /// picks the 'best' code from ConstraintInfo::Codes that most closely
3667  /// matches the operand.
3668  std::string ConstraintCode;
3669 
3670  /// Information about the constraint code, e.g. Register, RegisterClass,
3671  /// Memory, Other, Unknown.
3673 
3674  /// If this is the result output operand or a clobber, this is null,
3675  /// otherwise it is the incoming operand to the CallInst. This gets
3676  /// modified as the asm is processed.
3677  Value *CallOperandVal = nullptr;
3678 
3679  /// The ValueType for the operand value.
3680  MVT ConstraintVT = MVT::Other;
3681 
3682  /// Copy constructor for copying from a ConstraintInfo.
3684  : InlineAsm::ConstraintInfo(std::move(Info)) {}
3685 
3686  /// Return true of this is an input operand that is a matching constraint
3687  /// like "4".
3688  bool isMatchingInputConstraint() const;
3689 
3690  /// If this is an input matching constraint, this method returns the output
3691  /// operand it matches.
3692  unsigned getMatchedOperand() const;
3693  };
3694 
3695  using AsmOperandInfoVector = std::vector<AsmOperandInfo>;
3696 
3697  /// Split up the constraint string from the inline assembly value into the
3698  /// specific constraints and their prefixes, and also tie in the associated
3699  /// operand values. If this returns an empty vector, and if the constraint
3700  /// string itself isn't empty, there was an error parsing.
3701  virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL,
3702  const TargetRegisterInfo *TRI,
3703  ImmutableCallSite CS) const;
3704 
3705  /// Examine constraint type and operand type and determine a weight value.
3706  /// The operand object must already have been set up with the operand type.
3707  virtual ConstraintWeight getMultipleConstraintMatchWeight(
3708  AsmOperandInfo &info, int maIndex) const;
3709 
3710  /// Examine constraint string and operand type and determine a weight value.
3711  /// The operand object must already have been set up with the operand type.
3712  virtual ConstraintWeight getSingleConstraintMatchWeight(
3713  AsmOperandInfo &info, const char *constraint) const;
3714 
3715  /// Determines the constraint code and constraint type to use for the specific
3716  /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
3717  /// If the actual operand being passed in is available, it can be passed in as
3718  /// Op, otherwise an empty SDValue can be passed.
3719  virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
3720  SDValue Op,
3721  SelectionDAG *DAG = nullptr) const;
3722 
3723  /// Given a constraint, return the type of constraint it is for this target.
3724  virtual ConstraintType getConstraintType(StringRef Constraint) const;
3725 
3726  /// Given a physical register constraint (e.g. {edx}), return the register
3727  /// number and the register class for the register.
3728  ///
3729  /// Given a register class constraint, like 'r', if this corresponds directly
3730  /// to an LLVM register class, return a register of 0 and the register class
3731  /// pointer.
3732  ///
3733  /// This should only be used for C_Register constraints. On error, this
3734  /// returns a register number of 0 and a null register class pointer.
3735  virtual std::pair<unsigned, const TargetRegisterClass *>
3736  getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
3737  StringRef Constraint, MVT VT) const;
3738 
3739  virtual unsigned getInlineAsmMemConstraint(StringRef ConstraintCode) const {
3740  if (ConstraintCode == "i")
3741  return InlineAsm::Constraint_i;
3742  else if (ConstraintCode == "m")
3743  return InlineAsm::Constraint_m;
3745  }
3746 
3747  /// Try to replace an X constraint, which matches anything, with another that
3748  /// has more specific requirements based on the type of the corresponding
3749  /// operand. This returns null if there is no replacement to make.
3750  virtual const char *LowerXConstraint(EVT ConstraintVT) const;
3751 
3752  /// Lower the specified operand into the Ops vector. If it is invalid, don't
3753  /// add anything to Ops.
3754  virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
3755  std::vector<SDValue> &Ops,
3756  SelectionDAG &DAG) const;
3757 
3758  // Lower custom output constraints. If invalid, return SDValue().
3759  virtual SDValue LowerAsmOutputForConstraint(SDValue &Chain, SDValue &Flag,
3760  SDLoc DL,
3761  const AsmOperandInfo &OpInfo,
3762  SelectionDAG &DAG) const;
3763 
3764  //===--------------------------------------------------------------------===//
3765  // Div utility functions
3766  //
3767  SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
3768  SmallVectorImpl<SDNode *> &Created) const;
3769  SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
3770  SmallVectorImpl<SDNode *> &Created) const;
3771 
3772  /// Targets may override this function to provide custom SDIV lowering for
3773  /// power-of-2 denominators. If the target returns an empty SDValue, LLVM
3774  /// assumes SDIV is expensive and replaces it with a series of other integer
3775  /// operations.
3776  virtual SDValue BuildSDIVPow2(SDNode *N, const APInt &Divisor,
3777  SelectionDAG &DAG,
3778  SmallVectorImpl<SDNode *> &Created) const;
3779 
3780  /// Indicate whether this target prefers to combine FDIVs with the same
3781  /// divisor. If the transform should never be done, return zero. If the
3782  /// transform should be done, return the minimum number of divisor uses
3783  /// that must exist.
3784  virtual unsigned combineRepeatedFPDivisors() const {
3785  return 0;
3786  }
3787 
3788  /// Hooks for building estimates in place of slower divisions and square
3789  /// roots.
3790 
3791  /// Return either a square root or its reciprocal estimate value for the input
3792  /// operand.
3793  /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
3794  /// 'Enabled' as set by a potential default override attribute.
3795  /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
3796  /// refinement iterations required to generate a sufficient (though not
3797  /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
3798  /// The boolean UseOneConstNR output is used to select a Newton-Raphson
3799  /// algorithm implementation that uses either one or two constants.
3800  /// The boolean Reciprocal is used to select whether the estimate is for the
3801  /// square root of the input operand or the reciprocal of its square root.
3802  /// A target may choose to implement its own refinement within this function.
3803  /// If that's true, then return '0' as the number of RefinementSteps to avoid
3804  /// any further refinement of the estimate.
3805  /// An empty SDValue return means no estimate sequence can be created.
3807  int Enabled, int &RefinementSteps,
3808  bool &UseOneConstNR, bool Reciprocal) const {
3809  return SDValue();
3810  }
3811 
3812  /// Return a reciprocal estimate value for the input operand.
3813  /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
3814  /// 'Enabled' as set by a potential default override attribute.
3815  /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
3816  /// refinement iterations required to generate a sufficient (though not
3817  /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
3818  /// A target may choose to implement its own refinement within this function.
3819  /// If that's true, then return '0' as the number of RefinementSteps to avoid
3820  /// any further refinement of the estimate.
3821  /// An empty SDValue return means no estimate sequence can be created.
3823  int Enabled, int &RefinementSteps) const {
3824  return SDValue();
3825  }
3826 
3827  //===--------------------------------------------------------------------===//
3828  // Legalization utility functions
3829  //
3830 
3831  /// Expand a MUL or [US]MUL_LOHI of n-bit values into two or four nodes,
3832  /// respectively, each computing an n/2-bit part of the result.
3833  /// \param Result A vector that will be filled with the parts of the result
3834  /// in little-endian order.
3835  /// \param LL Low bits of the LHS of the MUL. You can use this parameter
3836  /// if you want to control how low bits are extracted from the LHS.
3837  /// \param LH High bits of the LHS of the MUL. See LL for meaning.
3838  /// \param RL Low bits of the RHS of the MUL. See LL for meaning
3839  /// \param RH High bits of the RHS of the MUL. See LL for meaning.
3840  /// \returns true if the node has been expanded, false if it has not
3841  bool expandMUL_LOHI(unsigned Opcode, EVT VT, SDLoc dl, SDValue LHS,
3842  SDValue RHS, SmallVectorImpl<SDValue> &Result, EVT HiLoVT,
3844  SDValue LL = SDValue(), SDValue LH = SDValue(),
3845  SDValue RL = SDValue(), SDValue RH = SDValue()) const;
3846 
3847  /// Expand a MUL into two nodes. One that computes the high bits of
3848  /// the result and one that computes the low bits.
3849  /// \param HiLoVT The value type to use for the Lo and Hi nodes.
3850  /// \param LL Low bits of the LHS of the MUL. You can use this parameter
3851  /// if you want to control how low bits are extracted from the LHS.
3852  /// \param LH High bits of the LHS of the MUL. See LL for meaning.
3853  /// \param RL Low bits of the RHS of the MUL. See LL for meaning
3854  /// \param RH High bits of the RHS of the MUL. See LL for meaning.
3855  /// \returns true if the node has been expanded. false if it has not
3856  bool expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
3857  SelectionDAG &DAG, MulExpansionKind Kind,
3858  SDValue LL = SDValue(), SDValue LH = SDValue(),
3859  SDValue RL = SDValue(), SDValue RH = SDValue()) const;
3860 
3861  /// Expand funnel shift.
3862  /// \param N Node to expand
3863  /// \param Result output after conversion
3864  /// \returns True, if the expansion was successful, false otherwise
3865  bool expandFunnelShift(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
3866 
3867  /// Expand rotations.
3868  /// \param N Node to expand
3869  /// \param Result output after conversion
3870  /// \returns True, if the expansion was successful, false otherwise
3871  bool expandROT(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
3872 
3873  /// Expand float(f32) to SINT(i64) conversion
3874  /// \param N Node to expand
3875  /// \param Result output after conversion
3876  /// \returns True, if the expansion was successful, false otherwise
3877  bool expandFP_TO_SINT(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
3878 
3879  /// Expand float to UINT conversion
3880  /// \param N Node to expand
3881  /// \param Result output after conversion
3882  /// \returns True, if the expansion was successful, false otherwise
3883  bool expandFP_TO_UINT(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
3884 
3885  /// Expand UINT(i64) to double(f64) conversion
3886  /// \param N Node to expand
3887  /// \param Result output after conversion
3888  /// \returns True, if the expansion was successful, false otherwise
3889  bool expandUINT_TO_FP(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
3890 
3891  /// Expand fminnum/fmaxnum into fminnum_ieee/fmaxnum_ieee with quieted inputs.
3892  SDValue expandFMINNUM_FMAXNUM(SDNode *N, SelectionDAG &DAG) const;
3893 
3894  /// Expand CTPOP nodes. Expands vector/scalar CTPOP nodes,
3895  /// vector nodes can only succeed if all operations are legal/custom.
3896  /// \param N Node to expand
3897  /// \param Result output after conversion
3898  /// \returns True, if the expansion was successful, false otherwise
3899  bool expandCTPOP(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
3900 
3901  /// Expand CTLZ/CTLZ_ZERO_UNDEF nodes. Expands vector/scalar CTLZ nodes,
3902  /// vector nodes can only succeed if all operations are legal/custom.
3903  /// \param N Node to expand
3904  /// \param Result output after conversion
3905  /// \returns True, if the expansion was successful, false otherwise
3906  bool expandCTLZ(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
3907 
3908  /// Expand CTTZ/CTTZ_ZERO_UNDEF nodes. Expands vector/scalar CTTZ nodes,
3909  /// vector nodes can only succeed if all operations are legal/custom.
3910  /// \param N Node to expand
3911  /// \param Result output after conversion
3912  /// \returns True, if the expansion was successful, false otherwise
3913  bool expandCTTZ(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
3914 
3915  /// Expand ABS nodes. Expands vector/scalar ABS nodes,
3916  /// vector nodes can only succeed if all operations are legal/custom.
3917  /// (ABS x) -> (XOR (ADD x, (SRA x, type_size)), (SRA x, type_size))
3918  /// \param N Node to expand
3919  /// \param Result output after conversion
3920  /// \returns True, if the expansion was successful, false otherwise
3921  bool expandABS(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
3922 
3923  /// Turn load of vector type into a load of the individual elements.
3924  /// \param LD load to expand
3925  /// \returns MERGE_VALUEs of the scalar loads with their chains.
3926  SDValue scalarizeVectorLoad(LoadSDNode *LD, SelectionDAG &DAG) const;
3927 
3928  // Turn a store of a vector type into stores of the individual elements.
3929  /// \param ST Store with a vector value type
3930  /// \returns MERGE_VALUs of the individual store chains.
3931  SDValue scalarizeVectorStore(StoreSDNode *ST, SelectionDAG &DAG) const;
3932 
3933  /// Expands an unaligned load to 2 half-size loads for an integer, and
3934  /// possibly more for vectors.
3935  std::pair<SDValue, SDValue> expandUnalignedLoad(LoadSDNode *LD,
3936  SelectionDAG &DAG) const;
3937 
3938  /// Expands an unaligned store to 2 half-size stores for integer values, and
3939  /// possibly more for vectors.
3940  SDValue expandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG) const;
3941 
3942  /// Increments memory address \p Addr according to the type of the value
3943  /// \p DataVT that should be stored. If the data is stored in compressed
3944  /// form, the memory address should be incremented according to the number of
3945  /// the stored elements. This number is equal to the number of '1's bits
3946  /// in the \p Mask.
3947  /// \p DataVT is a vector type. \p Mask is a vector value.
3948  /// \p DataVT and \p Mask have the same number of vector elements.
3949  SDValue IncrementMemoryAddress(SDValue Addr, SDValue Mask, const SDLoc &DL,
3950  EVT DataVT, SelectionDAG &DAG,
3951  bool IsCompressedMemory) const;
3952 
3953  /// Get a pointer to vector element \p Idx located in memory for a vector of
3954  /// type \p VecVT starting at a base address of \p VecPtr. If \p Idx is out of
3955  /// bounds the returned pointer is unspecified, but will be within the vector
3956  /// bounds.
3957  SDValue getVectorElementPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT,
3958  SDValue Index) const;
3959 
3960  /// Method for building the DAG expansion of ISD::[US][ADD|SUB]SAT. This
3961  /// method accepts integers as its arguments.
3962  SDValue expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const;
3963 
3964  /// Method for building the DAG expansion of ISD::SMULFIX. This method accepts
3965  /// integers as its arguments.
3966  SDValue expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const;
3967 
3968  /// Method for building the DAG expansion of ISD::U(ADD|SUB)O. Expansion
3969  /// always suceeds and populates the Result and Overflow arguments.
3970  void expandUADDSUBO(SDNode *Node, SDValue &Result, SDValue &Overflow,
3971  SelectionDAG &DAG) const;
3972 
3973  /// Method for building the DAG expansion of ISD::S(ADD|SUB)O. Expansion
3974  /// always suceeds and populates the Result and Overflow arguments.
3975  void expandSADDSUBO(SDNode *Node, SDValue &Result, SDValue &Overflow,
3976  SelectionDAG &DAG) const;
3977 
3978  /// Method for building the DAG expansion of ISD::[US]MULO. Returns whether
3979  /// expansion was successful and populates the Result and Overflow arguments.
3980  bool expandMULO(SDNode *Node, SDValue &Result, SDValue &Overflow,
3981  SelectionDAG &DAG) const;
3982 
3983  /// Expand a VECREDUCE_* into an explicit calculation. If Count is specified,
3984  /// only the first Count elements of the vector are used.
3985  SDValue expandVecReduce(SDNode *Node, SelectionDAG &DAG) const;
3986 
3987  //===--------------------------------------------------------------------===//
3988  // Instruction Emitting Hooks
3989  //
3990 
3991  /// This method should be implemented by targets that mark instructions with
3992  /// the 'usesCustomInserter' flag. These instructions are special in various
3993  /// ways, which require special support to insert. The specified MachineInstr
3994  /// is created but not inserted into any basic blocks, and this method is
3995  /// called to expand it into a sequence of instructions, potentially also
3996  /// creating new basic blocks and control flow.
3997  /// As long as the returned basic block is different (i.e., we created a new
3998  /// one), the custom inserter is free to modify the rest of \p MBB.
3999  virtual MachineBasicBlock *
4000  EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const;
4001 
4002  /// This method should be implemented by targets that mark instructions with
4003  /// the 'hasPostISelHook' flag. These instructions must be adjusted after
4004  /// instruction selection by target hooks. e.g. To fill in optional defs for
4005  /// ARM 's' setting instructions.
4006  virtual void AdjustInstrPostInstrSelection(MachineInstr &MI,
4007  SDNode *Node) const;
4008 
4009  /// If this function returns true, SelectionDAGBuilder emits a
4010  /// LOAD_STACK_GUARD node when it is lowering Intrinsic::stackprotector.
4011  virtual bool useLoadStackGuardNode() const {
4012  return false;
4013  }
4014 
4016  const SDLoc &DL) const {
4017  llvm_unreachable("not implemented for this target");
4018  }
4019 
4020  /// Lower TLS global address SDNode for target independent emulated TLS model.
4021  virtual SDValue LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
4022  SelectionDAG &DAG) const;
4023 
4024  /// Expands target specific indirect branch for the case of JumpTable
4025  /// expanasion.
4027  SelectionDAG &DAG) const {
4028  return DAG.getNode(ISD::BRIND, dl, MVT::Other, Value, Addr);
4029  }
4030 
4031  // seteq(x, 0) -> truncate(srl(ctlz(zext(x)), log2(#bits)))
4032  // If we're comparing for equality to zero and isCtlzFast is true, expose the
4033  // fact that this can be implemented as a ctlz/srl pair, so that the dag
4034  // combiner can fold the new nodes.
4035  SDValue lowerCmpEqZeroToCtlzSrl(SDValue Op, SelectionDAG &DAG) const;
4036 
4037 private:
4038  SDValue foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
4039  const SDLoc &DL, DAGCombinerInfo &DCI) const;
4040  SDValue foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
4041  const SDLoc &DL, DAGCombinerInfo &DCI) const;
4042 
4043  SDValue optimizeSetCCOfSignedTruncationCheck(EVT SCCVT, SDValue N0,
4044  SDValue N1, ISD::CondCode Cond,
4045  DAGCombinerInfo &DCI,
4046  const SDLoc &DL) const;
4047 };
4048 
4049 /// Given an LLVM IR type and return type attributes, compute the return value
4050 /// EVTs and flags, and optionally also the offsets, if the return value is
4051 /// being lowered to memory.
4054  const TargetLowering &TLI, const DataLayout &DL);
4055 
4056 } // end namespace llvm
4057 
4058 #endif // LLVM_CODEGEN_TARGETLOWERING_H
virtual AtomicExpansionKind shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const
Returns how the given atomic cmpxchg should be expanded by the IR-level AtomicExpand pass...
LegalizeAction getLoadExtAction(unsigned ExtType, EVT ValVT, EVT MemVT) const
Return how this load with extension should be treated: either it is legal, needs to be promoted to a ...
virtual bool isJumpTableRelative() const
uint64_t CallInst * C
X = FP_ROUND(Y, TRUNC) - Rounding &#39;Y&#39; from a larger floating point type down to the precision of the ...
Definition: ISDOpcodes.h:557
static MVT getIntegerVT(unsigned BitWidth)
BUILTIN_OP_END - This must be the last enum value in this list.
Definition: ISDOpcodes.h:908
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:110
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:233
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
FMINNUM/FMAXNUM - Perform floating-point minimum or maximum on two values.
Definition: ISDOpcodes.h:617
virtual MVT getVectorIdxTy(const DataLayout &DL) const
Returns the type to be used for the index operand of: ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT...
EVT getValueType() const
Return the ValueType of the referenced return value.
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg If BaseGV is null...
bool isInteger() const
Return true if this is an integer or a vector integer type.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified load with extension does not work with the specified type and indicate wh...
virtual bool canMergeStoresTo(unsigned AS, EVT MemVT, const SelectionDAG &DAG) const
Returns if it&#39;s reasonable to merge stores to MemVT size.
unsigned getIndexSizeInBits(unsigned AS) const
Size in bits of index used for address calculation in getelementptr.
Definition: DataLayout.h:398
virtual bool isCheapAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const
Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g.
Constrained versions of libm-equivalent floating point intrinsics.
Definition: ISDOpcodes.h:295
bool usesUnderscoreLongJmp() const
Determine if we should use _longjmp or longjmp to implement llvm.longjmp.
LLVMContext & Context
virtual bool shouldInsertFencesForAtomic(const Instruction *I) const
Whether AtomicExpandPass should automatically insert fences and reduce ordering for this atomic...
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
Definition: Path.cpp:224
Atomic ordering constants.
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:288
virtual SDValue expandIndirectJTBranch(const SDLoc &dl, SDValue Value, SDValue Addr, SelectionDAG &DAG) const
Expands target specific indirect branch for the case of JumpTable expanasion.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:139
This class represents lattice values for constants.
Definition: AllocatorList.h:23
bool isOperationCustom(unsigned Op, EVT VT) const
Return true if the operation uses custom lowering, regardless of whether the type is legal or not...
C - The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
FMINIMUM/FMAXIMUM - NaN-propagating minimum/maximum that also treat -0.0 as less than 0...
Definition: ISDOpcodes.h:628
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
virtual const TargetRegisterClass * getRepRegClassFor(MVT VT) const
Return the &#39;representative&#39; register class for the specified value type.
virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const
Return if the target supports combining a chain like:
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition: Function.h:603
virtual bool reduceSelectOfFPConstantLoads(bool IsFPSetCC) const
Return true if it is profitable to convert a select of FP constants into a constant pool load whose a...
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
an instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
Definition: Instructions.h:528
CallLoweringInfo & setIsPostTypeLegalization(bool Value=true)
Sched::Preference getSchedulingPreference() const
Return target scheduling preference.
void setJumpBufAlignment(unsigned Align)
Set the target&#39;s required jmp_buf buffer alignment (in bytes); default is 0.
bool usesUnderscoreSetJmp() const
Determine if we should use _setjmp or setjmp to implement llvm.setjmp.
virtual unsigned getRegisterByName(const char *RegName, EVT VT, SelectionDAG &DAG) const
Return the register ID of the name passed in.
Carry-setting nodes for multiple precision addition and subtraction.
Definition: ISDOpcodes.h:222
virtual unsigned getVectorTypeBreakdownForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const
Certain targets such as MIPS require that some types such as vectors are always broken down into scal...
bool isPow2VectorType() const
Returns true if the given vector is a power of 2.
virtual bool enableAggressiveFMAFusion(EVT VT) const
Return true if target always beneficiates from combining into FMA for a given value type...
virtual bool getPreIndexedAddressParts(SDNode *, SDValue &, SDValue &, ISD::MemIndexedMode &, SelectionDAG &) const
Returns true by value, base pointer and offset pointer and addressing mode by reference if the node&#39;s...
virtual SDValue getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, int Enabled, int &RefinementSteps, bool &UseOneConstNR, bool Reciprocal) const
Hooks for building estimates in place of slower divisions and square roots.
This class represents a function call, abstracting a target machine&#39;s calling convention.
virtual bool isFNegFree(EVT VT) const
Return true if an fneg operation is free to the point where it is never worthwhile to replace it with...
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition: ValueTypes.h:252
virtual unsigned combineRepeatedFPDivisors() const
Indicate whether this target prefers to combine FDIVs with the same divisor.
Libcall
RTLIB::Libcall enum - This enum defines all of the runtime library calls the backend can emit...
virtual bool isExtractVecEltCheap(EVT VT, unsigned Index) const
Return true if extraction of a scalar element from the given vector type at the given index is cheap...
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition: ISDOpcodes.h:250
static ISD::NodeType getExtendForContent(BooleanContent Content)
unsigned getVectorNumElements() const
virtual bool isSelectSupported(SelectSupportKind) const
Function Alias Analysis Results
bool isSuitableForBitTests(unsigned NumDests, unsigned NumCmps, const APInt &Low, const APInt &High, const DataLayout &DL) const
Return true if lowering to a bit test is suitable for a set of case clusters which contains NumDests ...
This instruction constructs a fixed permutation of two input vectors.
virtual bool isCommutativeBinOp(unsigned Opcode) const
Returns true if the opcode is a commutative binary operation.
virtual void markLibCallAttributes(MachineFunction *MF, unsigned CC, ArgListTy &Args) const
bool hasRetAttr(Attribute::AttrKind Kind) const
Return true if this return value has the given attribute.
Definition: CallSite.h:380
unsigned getMaxStoresPerMemset(bool OptSize) const
Get maximum # of store operations permitted for llvm.memset.
virtual void HandleByVal(CCState *, unsigned &, unsigned) const
Target-specific cleanup for formal ByVal parameters.
CallLoweringInfo & setNoReturn(bool Value=true)
virtual bool isSafeMemOpType(MVT) const
Returns true if it&#39;s safe to use load / store of the specified type to expand memcpy / memset inline...
void setBooleanVectorContents(BooleanContent Ty)
Specify how the target extends the result of a vector boolean value from a vector of i1 to a wider ty...
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
Definition: DataLayout.h:388
Constrained versions of the binary floating point operators.
Definition: ISDOpcodes.h:288
LegalizeAction getIndexedStoreAction(unsigned IdxMode, MVT VT) const
Return how the indexed store should be treated: either it is legal, needs to be promoted to a larger ...
bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const
Return true if the specified store with truncation is legal on this target.
virtual const TargetRegisterClass * getRegClassFor(MVT VT) const
Return the register class that should be used for the specified value type.
unsigned const TargetRegisterInfo * TRI
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition: ValueTypes.h:140
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1077
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
bool hasMultipleConditionRegisters() const
Return true if multiple condition registers are available.
block Block Frequency true
An instruction for reading from memory.
Definition: Instructions.h:167
virtual AtomicExpansionKind shouldExpandAtomicLoadInIR(LoadInst *LI) const
Returns how the given (atomic) load should be expanded by the IR-level AtomicExpand pass...
virtual bool mayBeEmittedAsTailCall(const CallInst *) const
Return true if the target may be able emit the call instruction as a tail call.
virtual bool isTypeDesirableForOp(unsigned, EVT VT) const
Return true if the target has native support for the specified value type and it is &#39;desirable&#39; to us...
[US]{MIN/MAX} - Binary minimum or maximum or signed or unsigned integers.
Definition: ISDOpcodes.h:403
bool hasExtractBitsInsn() const
Return true if the target has BitExtract instructions.
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
Definition: Instructions.h:691
BooleanContent getBooleanContents(bool isVec, bool isFloat) const
For targets without i1 registers, this gives the nature of the high-bits of boolean values held in ty...
SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
virtual AtomicExpansionKind shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const
Returns how the IR-level AtomicExpand pass should expand the given AtomicRMW, if at all...
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
AtomicExpansionKind
Enum that specifies what an atomic load/AtomicRMWInst is expanded to, if at all.
virtual bool storeOfVectorConstantIsCheap(EVT MemVT, unsigned NumElem, unsigned AddrSpace) const
Return true if it is expected to be cheaper to do a store of a non-zero vector constant with the give...
bool isOperationLegalOrCustom(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
LegalizeAction getFixedPointOperationAction(unsigned Op, EVT VT, unsigned Scale) const
Some fixed point operations may be natively supported by the target but only for specific scales...
unsigned getJumpBufAlignment() const
Returns the target&#39;s jmp_buf alignment in bytes (if never set, the default is 0)
std::pair< LegalizeTypeAction, EVT > LegalizeKind
LegalizeKind holds the legalization kind that needs to happen to EVT in order to type-legalize it...
CallLoweringInfo & setDiscardResult(bool Value=true)
virtual StringRef getStackProbeSymbolName(MachineFunction &MF) const
Returns the name of the symbol used to emit stack probes or the empty string if not applicable...
uint64_t High
virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &, MachineFunction &, unsigned) const
Given an intrinsic, checks if on the target the intrinsic will need to map to a MemIntrinsicNode (tou...
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition: ISDOpcodes.h:38
bool isValid() const
Return true if this is a valid simple valuetype.
bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const
Return true if the specified condition code is legal on this target.
virtual Value * emitMaskedAtomicRMWIntrinsic(IRBuilder<> &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const
Perform a masked atomicrmw using a target-specific intrinsic.
CallLoweringInfo & setCallee(Type *ResultType, FunctionType *FTy, SDValue Target, ArgListTy &&ArgsList, ImmutableCallSite Call)
void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified truncating store does not work with the specified type and indicate what ...
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:129
virtual bool isFPExtFree(EVT DestVT, EVT SrcVT) const
Return true if an fpext operation is free (for instance, because single-precision floating-point numb...
virtual bool isStoreBitCastBeneficial(EVT StoreVT, EVT BitcastVT) const
Return true if the following transform is beneficial: (store (y (conv x)), y*)) -> (store x...
CallingConv::ID getCallingConv() const
Get the calling convention of the call.
Definition: CallSite.h:320
virtual bool isCtlzFast() const
Return true if ctlz instruction is fast.
virtual bool isProfitableToCombineMinNumMaxNum(EVT VT) const
A convenience struct that encapsulates a DAG, and two SDValues for returning information from TargetL...
virtual bool shouldExpandShift(SelectionDAG &DAG, SDNode *N) const
Return true if SHIFT instructions should be expanded to SHIFT_PARTS instructions, and false if a libr...
MVT getRegisterType(MVT VT) const
Return the type of registers that this ValueType will eventually require.
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition: ValueTypes.h:135
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
unsigned getAllocaAddrSpace() const
Definition: DataLayout.h:269
void * PointerTy
Definition: GenericValue.h:21
bool hasOneUse() const
Return true if there is exactly one use of this node.
Definition: BitVector.h:937
virtual bool decomposeMulByConstant(EVT VT, SDValue C) const
Return true if it is profitable to transform an integer multiplication-by-constant into simpler opera...
void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits)
Set the maximum atomic operation size supported by the backend.
Shift and rotation operations.
Definition: ISDOpcodes.h:429
Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
Definition: ValueTypes.cpp:205
virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
virtual bool isSupportedFixedPointOperation(unsigned Op, EVT VT, unsigned Scale) const
Custom method defined by each target to indicate if an operation which may require a scale is support...
CallLoweringInfo & setVarArg(bool Value=true)
CallLoweringInfo & setChain(SDValue InChain)
RESULT = [US]MULFIX(LHS, RHS, SCALE) - Perform fixed point multiplication on 2 integers with the same...
Definition: ISDOpcodes.h:279
virtual uint8_t getRepRegClassCostFor(MVT VT) const
Return the cost of the &#39;representative&#39; register class for the specified value type.
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:742
virtual bool useLoadStackGuardNode() const
If this function returns true, SelectionDAGBuilder emits a LOAD_STACK_GUARD node when it is lowering ...
void setCondCodeAction(ISD::CondCode CC, MVT VT, LegalizeAction Action)
Indicate that the specified condition code is or isn&#39;t supported on the target and indicate what to d...
This file contains the simple types necessary to represent the attributes associated with functions a...
SimpleValueType SimpleTy
void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth)
Tells the code generator which bitwidths to bypass.
virtual bool isVectorShiftByScalarCheap(Type *Ty) const
Return true if it&#39;s significantly cheaper to shift a vector by a uniform scalar than by an amount whi...
bool isLoadExtLegalOrCustom(unsigned ExtType, EVT ValVT, EVT MemVT) const
Return true if the specified load with extension is legal or custom on this target.
bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const
When splitting a value of the specified type into parts, does the Lo or Hi part come first...
virtual bool shouldUseStrictFP_TO_INT(EVT FpVT, EVT IntVT, bool IsSigned) const
Return true if it is more correct/profitable to use strict FP_TO_INT conversion operations - canonica...
void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action)
Indicate that the specified operation does not work with the specified type and indicate what to do a...
virtual bool convertSetCCLogicToBitwiseLogic(EVT VT) const
Use bitwise logic to make pairs of compares more efficient.
virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const
Return true if it is cheaper to split the store of a merged int val from a pair of smaller values int...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
virtual bool aggressivelyPreferBuildVectorSources(EVT VecVT) const
This file implements a class to represent arbitrary precision integral constant values and operations...
virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const
Return true if it&#39;s free to truncate a value of type FromTy to type ToTy.
SmallVector< ISD::InputArg, 32 > Ins
AtomicOrdering
Atomic ordering for LLVM&#39;s memory model.
virtual bool ShouldShrinkFPConstant(EVT) const
If true, then instruction selection should seek to shrink the FP constant of the specified type to a ...
virtual SDValue prepareVolatileOrAtomicLoad(SDValue Chain, const SDLoc &DL, SelectionDAG &DAG) const
This callback is used to prepare for a volatile or atomic load.
Context object for machine code objects.
Definition: MCContext.h:62
virtual void ReplaceNodeResults(SDNode *, SmallVectorImpl< SDValue > &, SelectionDAG &) const
This callback is invoked when a node result type is illegal for the target, and the operation was reg...
InstrTy * getInstruction() const
Definition: CallSite.h:96
virtual EVT getOptimalMemOpType(uint64_t, unsigned, unsigned, bool, bool, bool, const AttributeList &) const
Returns the target specific optimal type for load and store operations as a result of memset...
virtual unsigned getABIAlignmentForCallingConv(Type *ArgTy, DataLayout DL) const
Certain targets have context senstive alignment requirements, where one type has the alignment requir...
virtual bool isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT) const
Return true if the following transform is beneficial: fold (conv (load x)) -> (load (conv*)x) On arch...
This is a fast-path instruction selection class that generates poor code and doesn&#39;t support illegal ...
Definition: FastISel.h:66
Class to represent function types.
Definition: DerivedTypes.h:102
unsigned getSizeInBits() const
Return the size of the specified value type in bits.
Definition: ValueTypes.h:291
#define UINT64_MAX
Definition: DataTypes.h:83
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:244
MachineFunction & getMachineFunction() const
Definition: SelectionDAG.h:400
static cl::opt< unsigned > MaxLoadsPerMemcmpOptSize("max-loads-per-memcmp-opt-size", cl::Hidden, cl::desc("Set maximum number of loads used in expanded memcmp for -Os/Oz"))
virtual bool supportSwiftError() const
Return true if the target supports swifterror attribute.
virtual bool shouldSinkOperands(Instruction *I, SmallVectorImpl< Use *> &Ops) const
Return true if sinking I&#39;s operands to the same basic block as I is profitable, e.g.
CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const
Get the CallingConv that should be used for the specified libcall.
This contains information for each constraint that we are lowering.
Simple integer binary arithmetic operators.
Definition: ISDOpcodes.h:200
bool isVarArg() const
Definition: DerivedTypes.h:122
SmallVector< ISD::OutputArg, 32 > Outs
virtual bool isCheapToSpeculateCtlz() const
Return true if it is cheap to speculate a call to intrinsic ctlz.
Fast - This calling convention attempts to make calls as fast as possible (e.g.
Definition: CallingConv.h:42
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
bool isLittleEndian() const
Layout endianness...
Definition: DataLayout.h:232
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:125
CallLoweringInfo & setZExtResult(bool Value=true)
BooleanContent getBooleanContents(EVT Type) const
virtual bool shouldSplitFunctionArgumentsAsLittleEndian(const DataLayout &DL) const
For most targets, an LLVM type must be broken down into multiple smaller types.
An instruction for storing to memory.
Definition: Instructions.h:320
unsigned getPrefFunctionAlignment() const
Return the preferred function alignment.
MVT getRegisterType(LLVMContext &Context, EVT VT) const
Return the type of registers that this ValueType will eventually require.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out...
Definition: ISDOpcodes.h:990
virtual const MCExpr * LowerCustomJumpTableEntry(const MachineJumpTableInfo *, const MachineBasicBlock *, unsigned, MCContext &) const
virtual bool isCheapToSpeculateCttz() const
Return true if it is cheap to speculate a call to intrinsic cttz.
X = STRICT_FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition: ISDOpcodes.h:318
virtual bool lowerInterleavedStore(StoreInst *SI, ShuffleVectorInst *SVI, unsigned Factor) const
Lower an interleaved store to target specific intrinsics.
virtual unsigned getInlineAsmMemConstraint(StringRef ConstraintCode) const
void setMinCmpXchgSizeInBits(unsigned SizeInBits)
Sets the minimum cmpxchg or ll/sc size supported by the backend.
Value * getOperand(unsigned i) const
Definition: User.h:169
Analysis containing CSE Info
Definition: CSEInfo.cpp:20
Class to represent pointers.
Definition: DerivedTypes.h:498
This class is used to represent ISD::STORE nodes.
void setAttributes(ImmutableCallSite *CS, unsigned ArgIdx)
static cl::opt< unsigned > MaxLoadsPerMemcmp("max-loads-per-memcmp", cl::Hidden, cl::desc("Set maximum number of loads used in expanded memcmp"))
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
bool isJumpExpensive() const
Return true if Flow Control is an expensive operation that should be avoided.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
Definition: MCInstrDesc.h:117
virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx, unsigned &Cost) const
Return true if the target can combine store(extractelement VectorTy, Idx).
virtual bool alignLoopsWithOptSize() const
Should loops be aligned even when the function is marked OptSize (but not MinSize).
virtual Value * emitStoreConditional(IRBuilder<> &Builder, Value *Val, Value *Addr, AtomicOrdering Ord) const
Perform a store-conditional operation to Addr.
EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
std::vector< AsmOperandInfo > AsmOperandInfoVector
virtual bool shouldFormOverflowOp(unsigned Opcode, EVT VT) const
Try to convert math with an overflow comparison into the corresponding DAG node operation.
MVT getSimpleValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the MVT corresponding to this LLVM type. See getValueType.
virtual bool isSuitableForJumpTable(const SwitchInst *SI, uint64_t NumCases, uint64_t Range) const
Return true if lowering to a jump table is suitable for a set of case clusters which may contain NumC...
virtual bool getAddrModeArguments(IntrinsicInst *, SmallVectorImpl< Value *> &, Type *&) const
CodeGenPrepare sinks address calculations into the same BB as Load/Store instructions reading the add...
unsigned const MachineRegisterInfo * MRI
virtual unsigned getExceptionPointerRegister(const Constant *PersonalityFn) const
If a physical register, this returns the register that receives the exception address on entry to an ...
Machine Value Type.
DAGCombinerInfo(SelectionDAG &dag, CombineLevel level, bool cl, void *dc)
CallLoweringInfo & setIsPatchPoint(bool Value=true)
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:64
void setJumpBufSize(unsigned Size)
Set the target&#39;s required jmp_buf buffer size (in bytes); default is 200.
void addRegisterClass(MVT VT, const TargetRegisterClass *RC)
Add the specified register class as an available regclass for the specified value type...
Simple binary floating point operators.
Definition: ISDOpcodes.h:282
void setTargetDAGCombine(ISD::NodeType NT)
Targets should invoke this method for each target independent node that they want to provide a custom...
virtual Value * emitMaskedAtomicCmpXchgIntrinsic(IRBuilder<> &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const
Perform a masked cmpxchg using a target-specific intrinsic.
virtual bool isTruncateFree(EVT FromVT, EVT ToVT) const
virtual ISD::NodeType getExtendForAtomicOps() const
Returns how the platform&#39;s atomic operations are extended (ZERO_EXTEND, SIGN_EXTEND, or ANY_EXTEND).
This is an important base class in LLVM.
Definition: Constant.h:41
virtual bool shouldConvertConstantLoadToIntImm(const APInt &Imm, Type *Ty) const
Return true if it is beneficial to convert a load of a constant to just the constant itself...
bool isFloatingPointOperation() const
Definition: Instructions.h:823
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
Definition: ISDOpcodes.h:965
Carry-using nodes for multiple precision addition and subtraction.
Definition: ISDOpcodes.h:231
bool isSlowDivBypassed() const
Returns true if target has indicated at least one type should be bypassed.
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Definition: DerivedTypes.h:138
virtual Value * emitLoadLinked(IRBuilder<> &Builder, Value *Addr, AtomicOrdering Ord) const
Perform a load-linked operation on Addr, returning a "Value *" with the corresponding pointee type...
virtual unsigned getPrefLoopAlignment(MachineLoop *ML=nullptr) const
Return the preferred loop alignment.
virtual SDValue unwrapAddress(SDValue N) const
void setBooleanContents(BooleanContent Ty)
Specify how the target extends the result of integer and floating point boolean values from i1 to a w...
bool isAcquireOrStronger(AtomicOrdering ao)
virtual SDValue emitStackGuardXorFP(SelectionDAG &DAG, SDValue Val, const SDLoc &DL) const
virtual bool isFPExtFoldable(unsigned Opcode, EVT DestVT, EVT SrcVT) const
Return true if an fpext operation input to an Opcode operation is free (for instance, because half-precision floating-point numbers are implicitly extended to float-precision) for an FMA instruction.
virtual LoadInst * lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *RMWI) const
On some platforms, an AtomicRMW that never actually modifies the value (such as fetch_add of 0) can b...
virtual unsigned getExceptionSelectorRegister(const Constant *PersonalityFn) const
If a physical register, this returns the register that receives the exception typeid on entry to a la...
CombineLevel
Definition: DAGCombine.h:15
LegalizeAction getCondCodeAction(ISD::CondCode CC, MVT VT) const
Return how the condition code should be treated: either it is legal, needs to be expanded to some oth...
virtual bool areJTsAllowed(const Function *Fn) const
Return true if lowering to a jump table is allowed.
void setOperationPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT)
Convenience method to set an operation to Promote and specify the type in a single call...
bool CombineTo(SDValue O, SDValue N)
MVT getPointerMemTy(const DataLayout &DL, uint32_t AS=0) const
Return the in-memory pointer type for the given address space, defaults to the pointer type from the ...
bool isOperationLegalOrCustomOrPromote(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
virtual bool targetShrinkDemandedConstant(SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const
virtual bool ExpandInlineAsm(CallInst *) const
This hook allows the target to expand an inline asm call to be explicit llvm code if it wants to...
void setPrefFunctionAlignment(unsigned Align)
Set the target&#39;s preferred function alignment.
virtual bool hasPairedLoad(EVT, unsigned &) const
Return true if the target supplies and combines to a paired load two loaded values of type LoadedType...
virtual MVT getFenceOperandTy(const DataLayout &DL) const
Return the type for operands of fence.
virtual bool isDesirableToCombineBuildVectorToShuffleTruncate(ArrayRef< int > ShuffleMask, EVT SrcVT, EVT TruncVT) const
bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const
Return true if the specified indexed load is legal on this target.
bool isOperationLegal(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target.
virtual bool isDesirableToTransformToIntegerOp(unsigned, EVT) const
Return true if it is profitable for dag combiner to transform a floating point op of specified opcode...
void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT)
If Opc/OrigVT is specified as being promoted, the promotion code defaults to trying a larger integer/...
lazy value info
unsigned MaxStoresPerMemmove
Specify maximum bytes of store instructions per memmove call.
virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const
Return true if sign-extension from FromTy to ToTy is cheaper than zero-extension. ...
virtual bool isProfitableToHoist(Instruction *I) const
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition: ISDOpcodes.h:575
bool supportsUnalignedAtomics() const
Whether the target supports unaligned atomic operations.
virtual bool hasVectorBlend() const
Return true if the target has a vector blend instruction.
virtual EVT getTypeForExtReturn(LLVMContext &Context, EVT VT, ISD::NodeType) const
Return the type that should be used to zero or sign extend a zeroext/signext integer return value...
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
static unsigned NumFixedArgs
std::vector< ArgListEntry > ArgListTy
Extended Value Type.
Definition: ValueTypes.h:33
virtual bool functionArgumentNeedsConsecutiveRegisters(Type *Ty, CallingConv::ID CallConv, bool isVarArg) const
For some targets, an LLVM struct type must be broken down into multiple simple types, but the calling convention specifies that the entire struct must be passed in a block of consecutive registers.
virtual bool allowTruncateForTailCall(Type *FromTy, Type *ToTy) const
Return true if a truncation from FromTy to ToTy is permitted when deciding whether a call is in tail ...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual Sched::Preference getSchedulingPreference(SDNode *) const
Some scheduler, e.g.
This structure contains all information that is necessary for lowering calls.