1 //===-- llvm/Target/TargetLowering.h - Target Lowering Info -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// This file describes how to lower LLVM code to machine code. This has two
14 /// 1. Which ValueTypes are natively supported by the target.
15 /// 2. Which operations are supported for supported ValueTypes.
16 /// 3. Cost thresholds for alternative implementations of certain operations.
18 /// In addition it has a few other components, like information about FP
21 //===----------------------------------------------------------------------===//
23 #ifndef LLVM_TARGET_TARGETLOWERING_H
24 #define LLVM_TARGET_TARGETLOWERING_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"
31 #include "llvm/CodeGen/DAGCombine.h"
32 #include "llvm/CodeGen/ISDOpcodes.h"
33 #include "llvm/CodeGen/MachineValueType.h"
34 #include "llvm/CodeGen/RuntimeLibcalls.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/CodeGen/SelectionDAGNodes.h"
37 #include "llvm/CodeGen/ValueTypes.h"
38 #include "llvm/IR/Attributes.h"
39 #include "llvm/IR/CallSite.h"
40 #include "llvm/IR/CallingConv.h"
41 #include "llvm/IR/DataLayout.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/IRBuilder.h"
44 #include "llvm/IR/InlineAsm.h"
45 #include "llvm/IR/Instruction.h"
46 #include "llvm/IR/Instructions.h"
47 #include "llvm/IR/Type.h"
48 #include "llvm/MC/MCRegisterInfo.h"
49 #include "llvm/Support/AtomicOrdering.h"
50 #include "llvm/Support/Casting.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Target/TargetCallingConv.h"
53 #include "llvm/Target/TargetMachine.h"
66 class BranchProbability;
70 class FunctionLoweringInfo;
73 class MachineBasicBlock;
74 class MachineFunction;
76 class MachineJumpTableInfo;
78 class MachineRegisterInfo;
81 class TargetRegisterClass;
82 class TargetLibraryInfo;
83 class TargetRegisterInfo;
89 None, // No preference
90 Source, // Follow source order.
91 RegPressure, // Scheduling for lowest register pressure.
92 Hybrid, // Scheduling for both latency and register pressure.
93 ILP, // Scheduling for ILP in low register pressure mode.
94 VLIW // Scheduling for VLIW targets.
97 } // end namespace Sched
99 /// This base class for TargetLowering contains the SelectionDAG-independent
100 /// parts that can be used from the rest of CodeGen.
101 class TargetLoweringBase {
103 /// This enum indicates whether operations are valid for a target, and if not,
104 /// what action should be used to make them valid.
105 enum LegalizeAction : uint8_t {
106 Legal, // The target natively supports this operation.
107 Promote, // This operation should be executed in a larger type.
108 Expand, // Try to expand this to other ops, otherwise use a libcall.
109 LibCall, // Don't try to expand this to other ops, always use a libcall.
110 Custom // Use the LowerOperation hook to implement custom lowering.
113 /// This enum indicates whether a types are legal for a target, and if not,
114 /// what action should be used to make them valid.
115 enum LegalizeTypeAction : uint8_t {
116 TypeLegal, // The target natively supports this type.
117 TypePromoteInteger, // Replace this integer with a larger one.
118 TypeExpandInteger, // Split this integer into two of half the size.
119 TypeSoftenFloat, // Convert this float to a same size integer type,
120 // if an operation is not supported in target HW.
121 TypeExpandFloat, // Split this float into two of half the size.
122 TypeScalarizeVector, // Replace this one-element vector with its element.
123 TypeSplitVector, // Split this vector into two of half the size.
124 TypeWidenVector, // This vector should be widened into a larger vector.
125 TypePromoteFloat // Replace this float with a larger one.
128 /// LegalizeKind holds the legalization kind that needs to happen to EVT
129 /// in order to type-legalize it.
130 typedef std::pair<LegalizeTypeAction, EVT> LegalizeKind;
132 /// Enum that describes how the target represents true/false values.
133 enum BooleanContent {
134 UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
135 ZeroOrOneBooleanContent, // All bits zero except for bit 0.
136 ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
139 /// Enum that describes what type of support for selects the target has.
140 enum SelectSupportKind {
141 ScalarValSelect, // The target supports scalar selects (ex: cmov).
142 ScalarCondVectorVal, // The target supports selects with a scalar condition
143 // and vector values (ex: cmov).
144 VectorMaskSelect // The target supports vector selects with a vector
145 // mask (ex: x86 blends).
148 /// Enum that specifies what an atomic load/AtomicRMWInst is expanded
149 /// to, if at all. Exists because different targets have different levels of
150 /// support for these atomic instructions, and also have different options
151 /// w.r.t. what they should expand to.
152 enum class AtomicExpansionKind {
153 None, // Don't expand the instruction.
154 LLSC, // Expand the instruction into loadlinked/storeconditional; used
156 LLOnly, // Expand the (load) instruction into just a load-linked, which has
157 // greater atomic guarantees than a normal load.
158 CmpXChg, // Expand the instruction into cmpxchg; used by at least X86.
161 /// Enum that specifies when a multiplication should be expanded.
162 enum class MulExpansionKind {
163 Always, // Always expand the instruction.
164 OnlyLegalOrCustom, // Only expand when the resulting instructions are legal
170 Value *Val = nullptr;
171 SDValue Node = SDValue();
181 bool IsSwiftSelf : 1;
182 bool IsSwiftError : 1;
183 uint16_t Alignment = 0;
186 : IsSExt(false), IsZExt(false), IsInReg(false), IsSRet(false),
187 IsNest(false), IsByVal(false), IsInAlloca(false), IsReturned(false),
188 IsSwiftSelf(false), IsSwiftError(false) {}
190 void setAttributes(ImmutableCallSite *CS, unsigned ArgIdx);
192 typedef std::vector<ArgListEntry> ArgListTy;
194 virtual void markLibCallAttributes(MachineFunction *MF, unsigned CC,
195 ArgListTy &Args) const {};
197 static ISD::NodeType getExtendForContent(BooleanContent Content) {
199 case UndefinedBooleanContent:
200 // Extend by adding rubbish bits.
201 return ISD::ANY_EXTEND;
202 case ZeroOrOneBooleanContent:
203 // Extend by adding zero bits.
204 return ISD::ZERO_EXTEND;
205 case ZeroOrNegativeOneBooleanContent:
206 // Extend by copying the sign bit.
207 return ISD::SIGN_EXTEND;
209 llvm_unreachable("Invalid content kind");
212 /// NOTE: The TargetMachine owns TLOF.
213 explicit TargetLoweringBase(const TargetMachine &TM);
214 TargetLoweringBase(const TargetLoweringBase&) = delete;
215 void operator=(const TargetLoweringBase&) = delete;
216 virtual ~TargetLoweringBase() = default;
219 /// \brief Initialize all of the actions to default values.
223 const TargetMachine &getTargetMachine() const { return TM; }
225 virtual bool useSoftFloat() const { return false; }
227 /// Return the pointer type for the given address space, defaults to
228 /// the pointer type from the data layout.
229 /// FIXME: The default needs to be removed once all the code is updated.
230 MVT getPointerTy(const DataLayout &DL, uint32_t AS = 0) const {
231 return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
234 /// Return the type for frame index, which is determined by
235 /// the alloca address space specified through the data layout.
236 MVT getFrameIndexTy(const DataLayout &DL) const {
237 return getPointerTy(DL, DL.getAllocaAddrSpace());
240 /// Return the type for operands of fence.
241 /// TODO: Let fence operands be of i32 type and remove this.
242 virtual MVT getFenceOperandTy(const DataLayout &DL) const {
243 return getPointerTy(DL);
246 /// EVT is not used in-tree, but is used by out-of-tree target.
247 /// A documentation for this function would be nice...
248 virtual MVT getScalarShiftAmountTy(const DataLayout &, EVT) const;
250 EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL) const;
252 /// Returns the type to be used for the index operand of:
253 /// ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
254 /// ISD::INSERT_SUBVECTOR, and ISD::EXTRACT_SUBVECTOR
255 virtual MVT getVectorIdxTy(const DataLayout &DL) const {
256 return getPointerTy(DL);
259 virtual bool isSelectSupported(SelectSupportKind /*kind*/) const {
263 /// Return true if multiple condition registers are available.
264 bool hasMultipleConditionRegisters() const {
265 return HasMultipleConditionRegisters;
268 /// Return true if the target has BitExtract instructions.
269 bool hasExtractBitsInsn() const { return HasExtractBitsInsn; }
271 /// Return the preferred vector type legalization action.
272 virtual TargetLoweringBase::LegalizeTypeAction
273 getPreferredVectorAction(EVT VT) const {
274 // The default action for one element vectors is to scalarize
275 if (VT.getVectorNumElements() == 1)
276 return TypeScalarizeVector;
277 // The default action for other vectors is to promote
278 return TypePromoteInteger;
281 // There are two general methods for expanding a BUILD_VECTOR node:
282 // 1. Use SCALAR_TO_VECTOR on the defined scalar values and then shuffle
284 // 2. Build the vector on the stack and then load it.
285 // If this function returns true, then method (1) will be used, subject to
286 // the constraint that all of the necessary shuffles are legal (as determined
287 // by isShuffleMaskLegal). If this function returns false, then method (2) is
288 // always used. The vector type, and the number of defined values, are
291 shouldExpandBuildVectorWithShuffles(EVT /* VT */,
292 unsigned DefinedValues) const {
293 return DefinedValues < 3;
296 /// Return true if integer divide is usually cheaper than a sequence of
297 /// several shifts, adds, and multiplies for this target.
298 /// The definition of "cheaper" may depend on whether we're optimizing
299 /// for speed or for size.
300 virtual bool isIntDivCheap(EVT VT, AttributeList Attr) const { return false; }
302 /// Return true if the target can handle a standalone remainder operation.
303 virtual bool hasStandaloneRem(EVT VT) const {
307 /// Return true if SQRT(X) shouldn't be replaced with X*RSQRT(X).
308 virtual bool isFsqrtCheap(SDValue X, SelectionDAG &DAG) const {
309 // Default behavior is to replace SQRT(X) with X*RSQRT(X).
313 /// Reciprocal estimate status values used by the functions below.
314 enum ReciprocalEstimate : int {
320 /// Return a ReciprocalEstimate enum value for a square root of the given type
321 /// based on the function's attributes. If the operation is not overridden by
322 /// the function's attributes, "Unspecified" is returned and target defaults
323 /// are expected to be used for instruction selection.
324 int getRecipEstimateSqrtEnabled(EVT VT, MachineFunction &MF) const;
326 /// Return a ReciprocalEstimate enum value for a division of the given type
327 /// based on the function's attributes. If the operation is not overridden by
328 /// the function's attributes, "Unspecified" is returned and target defaults
329 /// are expected to be used for instruction selection.
330 int getRecipEstimateDivEnabled(EVT VT, MachineFunction &MF) const;
332 /// Return the refinement step count for a square root of the given type based
333 /// on the function's attributes. If the operation is not overridden by
334 /// the function's attributes, "Unspecified" is returned and target defaults
335 /// are expected to be used for instruction selection.
336 int getSqrtRefinementSteps(EVT VT, MachineFunction &MF) const;
338 /// Return the refinement step count for a division of the given type based
339 /// on the function's attributes. If the operation is not overridden by
340 /// the function's attributes, "Unspecified" is returned and target defaults
341 /// are expected to be used for instruction selection.
342 int getDivRefinementSteps(EVT VT, MachineFunction &MF) const;
344 /// Returns true if target has indicated at least one type should be bypassed.
345 bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
347 /// Returns map of slow types for division or remainder with corresponding
349 const DenseMap<unsigned int, unsigned int> &getBypassSlowDivWidths() const {
350 return BypassSlowDivWidths;
353 /// Return true if Flow Control is an expensive operation that should be
355 bool isJumpExpensive() const { return JumpIsExpensive; }
357 /// Return true if selects are only cheaper than branches if the branch is
358 /// unlikely to be predicted right.
359 bool isPredictableSelectExpensive() const {
360 return PredictableSelectIsExpensive;
363 /// If a branch or a select condition is skewed in one direction by more than
364 /// this factor, it is very likely to be predicted correctly.
365 virtual BranchProbability getPredictableBranchThreshold() const;
367 /// Return true if the following transform is beneficial:
368 /// fold (conv (load x)) -> (load (conv*)x)
369 /// On architectures that don't natively support some vector loads
370 /// efficiently, casting the load to a smaller vector of larger types and
371 /// loading is more efficient, however, this can be undone by optimizations in
373 virtual bool isLoadBitCastBeneficial(EVT LoadVT,
374 EVT BitcastVT) const {
375 // Don't do if we could do an indexed load on the original type, but not on
377 if (!LoadVT.isSimple() || !BitcastVT.isSimple())
380 MVT LoadMVT = LoadVT.getSimpleVT();
382 // Don't bother doing this if it's just going to be promoted again later, as
383 // doing so might interfere with other combines.
384 if (getOperationAction(ISD::LOAD, LoadMVT) == Promote &&
385 getTypeToPromoteTo(ISD::LOAD, LoadMVT) == BitcastVT.getSimpleVT())
391 /// Return true if the following transform is beneficial:
392 /// (store (y (conv x)), y*)) -> (store x, (x*))
393 virtual bool isStoreBitCastBeneficial(EVT StoreVT, EVT BitcastVT) const {
394 // Default to the same logic as loads.
395 return isLoadBitCastBeneficial(StoreVT, BitcastVT);
398 /// Return true if it is expected to be cheaper to do a store of a non-zero
399 /// vector constant with the given size and type for the address space than to
400 /// store the individual scalar element constants.
401 virtual bool storeOfVectorConstantIsCheap(EVT MemVT,
403 unsigned AddrSpace) const {
407 /// Returns if it's reasonable to merge stores to MemVT size.
408 virtual bool canMergeStoresTo(unsigned AddressSpace, EVT MemVT) const {
412 /// \brief Return true if it is cheap to speculate a call to intrinsic cttz.
413 virtual bool isCheapToSpeculateCttz() const {
417 /// \brief Return true if it is cheap to speculate a call to intrinsic ctlz.
418 virtual bool isCheapToSpeculateCtlz() const {
422 /// \brief Return true if ctlz instruction is fast.
423 virtual bool isCtlzFast() const {
427 /// Return true if it is safe to transform an integer-domain bitwise operation
428 /// into the equivalent floating-point operation. This should be set to true
429 /// if the target has IEEE-754-compliant fabs/fneg operations for the input
431 virtual bool hasBitPreservingFPLogic(EVT VT) const {
435 /// \brief Return true if it is cheaper to split the store of a merged int val
436 /// from a pair of smaller values into multiple stores.
437 virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const {
441 /// \brief Return if the target supports combining a
444 /// %andResult = and %val1, #mask
445 /// %icmpResult = icmp %andResult, 0
447 /// into a single machine instruction of a form like:
449 /// cc = test %register, #mask
451 virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
455 /// Use bitwise logic to make pairs of compares more efficient. For example:
456 /// and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
457 /// This should be true when it takes more than one instruction to lower
458 /// setcc (cmp+set on x86 scalar), when bitwise ops are faster than logic on
459 /// condition bits (crand on PowerPC), and/or when reducing cmp+br is a win.
460 virtual bool convertSetCCLogicToBitwiseLogic(EVT VT) const {
464 /// Return the preferred operand type if the target has a quick way to compare
465 /// integer values of the given size. Assume that any legal integer type can
466 /// be compared efficiently. Targets may override this to allow illegal wide
467 /// types to return a vector type if there is support to compare that type.
468 virtual MVT hasFastEqualityCompare(unsigned NumBits) const {
469 MVT VT = MVT::getIntegerVT(NumBits);
470 return isTypeLegal(VT) ? VT : MVT::INVALID_SIMPLE_VALUE_TYPE;
473 /// Return true if the target should transform:
474 /// (X & Y) == Y ---> (~X & Y) == 0
475 /// (X & Y) != Y ---> (~X & Y) != 0
477 /// This may be profitable if the target has a bitwise and-not operation that
478 /// sets comparison flags. A target may want to limit the transformation based
479 /// on the type of Y or if Y is a constant.
481 /// Note that the transform will not occur if Y is known to be a power-of-2
482 /// because a mask and compare of a single bit can be handled by inverting the
483 /// predicate, for example:
484 /// (X & 8) == 8 ---> (X & 8) != 0
485 virtual bool hasAndNotCompare(SDValue Y) const {
489 /// Return true if the target has a bitwise and-not operation:
491 /// This can be used to simplify select or other instructions.
492 virtual bool hasAndNot(SDValue X) const {
493 // If the target has the more complex version of this operation, assume that
494 // it has this operation too.
495 return hasAndNotCompare(X);
498 /// \brief Return true if the target wants to use the optimization that
499 /// turns ext(promotableInst1(...(promotableInstN(load)))) into
500 /// promotedInst1(...(promotedInstN(ext(load)))).
501 bool enableExtLdPromotion() const { return EnableExtLdPromotion; }
503 /// Return true if the target can combine store(extractelement VectorTy,
505 /// \p Cost[out] gives the cost of that transformation when this is true.
506 virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
507 unsigned &Cost) const {
511 /// Return true if target supports floating point exceptions.
512 bool hasFloatingPointExceptions() const {
513 return HasFloatingPointExceptions;
516 /// Return true if target always beneficiates from combining into FMA for a
517 /// given value type. This must typically return false on targets where FMA
518 /// takes more cycles to execute than FADD.
519 virtual bool enableAggressiveFMAFusion(EVT VT) const {
523 /// Return the ValueType of the result of SETCC operations.
524 virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context,
527 /// Return the ValueType for comparison libcalls. Comparions libcalls include
528 /// floating point comparion calls, and Ordered/Unordered check calls on
529 /// floating point numbers.
531 MVT::SimpleValueType getCmpLibcallReturnType() const;
533 /// For targets without i1 registers, this gives the nature of the high-bits
534 /// of boolean values held in types wider than i1.
536 /// "Boolean values" are special true/false values produced by nodes like
537 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
538 /// Not to be confused with general values promoted from i1. Some cpus
539 /// distinguish between vectors of boolean and scalars; the isVec parameter
540 /// selects between the two kinds. For example on X86 a scalar boolean should
541 /// be zero extended from i1, while the elements of a vector of booleans
542 /// should be sign extended from i1.
544 /// Some cpus also treat floating point types the same way as they treat
545 /// vectors instead of the way they treat scalars.
546 BooleanContent getBooleanContents(bool isVec, bool isFloat) const {
548 return BooleanVectorContents;
549 return isFloat ? BooleanFloatContents : BooleanContents;
552 BooleanContent getBooleanContents(EVT Type) const {
553 return getBooleanContents(Type.isVector(), Type.isFloatingPoint());
556 /// Return target scheduling preference.
557 Sched::Preference getSchedulingPreference() const {
558 return SchedPreferenceInfo;
561 /// Some scheduler, e.g. hybrid, can switch to different scheduling heuristics
562 /// for different nodes. This function returns the preference (or none) for
564 virtual Sched::Preference getSchedulingPreference(SDNode *) const {
568 /// Return the register class that should be used for the specified value
570 virtual const TargetRegisterClass *getRegClassFor(MVT VT) const {
571 const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
572 assert(RC && "This value type is not natively supported!");
576 /// Return the 'representative' register class for the specified value
579 /// The 'representative' register class is the largest legal super-reg
580 /// register class for the register class of the value type. For example, on
581 /// i386 the rep register class for i8, i16, and i32 are GR32; while the rep
582 /// register class is GR64 on x86_64.
583 virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
584 const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
588 /// Return the cost of the 'representative' register class for the specified
590 virtual uint8_t getRepRegClassCostFor(MVT VT) const {
591 return RepRegClassCostForVT[VT.SimpleTy];
594 /// Return true if the target has native support for the specified value type.
595 /// This means that it has a register that directly holds it without
596 /// promotions or expansions.
597 bool isTypeLegal(EVT VT) const {
598 assert(!VT.isSimple() ||
599 (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
600 return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != nullptr;
603 class ValueTypeActionImpl {
604 /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
605 /// that indicates how instruction selection should deal with the type.
606 LegalizeTypeAction ValueTypeActions[MVT::LAST_VALUETYPE];
609 ValueTypeActionImpl() {
610 std::fill(std::begin(ValueTypeActions), std::end(ValueTypeActions),
614 LegalizeTypeAction getTypeAction(MVT VT) const {
615 return ValueTypeActions[VT.SimpleTy];
618 void setTypeAction(MVT VT, LegalizeTypeAction Action) {
619 ValueTypeActions[VT.SimpleTy] = Action;
623 const ValueTypeActionImpl &getValueTypeActions() const {
624 return ValueTypeActions;
627 /// Return how we should legalize values of this type, either it is already
628 /// legal (return 'Legal') or we need to promote it to a larger type (return
629 /// 'Promote'), or we need to expand it into multiple registers of smaller
630 /// integer type (return 'Expand'). 'Custom' is not an option.
631 LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const {
632 return getTypeConversion(Context, VT).first;
634 LegalizeTypeAction getTypeAction(MVT VT) const {
635 return ValueTypeActions.getTypeAction(VT);
638 /// For types supported by the target, this is an identity function. For
639 /// types that must be promoted to larger types, this returns the larger type
640 /// to promote to. For integer types that are larger than the largest integer
641 /// register, this contains one step in the expansion to get to the smaller
642 /// register. For illegal floating point types, this returns the integer type
644 EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
645 return getTypeConversion(Context, VT).second;
648 /// For types supported by the target, this is an identity function. For
649 /// types that must be expanded (i.e. integer types that are larger than the
650 /// largest integer register or illegal floating point types), this returns
651 /// the largest legal type it will be expanded to.
652 EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
653 assert(!VT.isVector());
655 switch (getTypeAction(Context, VT)) {
658 case TypeExpandInteger:
659 VT = getTypeToTransformTo(Context, VT);
662 llvm_unreachable("Type is not legal nor is it to be expanded!");
667 /// Vector types are broken down into some number of legal first class types.
668 /// For example, EVT::v8f32 maps to 2 EVT::v4f32 with Altivec or SSE1, or 8
669 /// promoted EVT::f64 values with the X86 FP stack. Similarly, EVT::v2i64
670 /// turns into 4 EVT::i32 values with both PPC and X86.
672 /// This method returns the number of registers needed, and the VT for each
673 /// register. It also returns the VT and quantity of the intermediate values
674 /// before they are promoted/expanded.
675 unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
677 unsigned &NumIntermediates,
678 MVT &RegisterVT) const;
680 struct IntrinsicInfo {
681 unsigned opc = 0; // target opcode
682 EVT memVT; // memory VT
683 const Value* ptrVal = nullptr; // value representing memory location
684 int offset = 0; // offset off of ptrVal
685 unsigned size = 0; // the size of the memory location
686 // (taken from memVT if zero)
687 unsigned align = 1; // alignment
688 bool vol = false; // is volatile?
689 bool readMem = false; // reads memory?
690 bool writeMem = false; // writes memory?
692 IntrinsicInfo() = default;
695 /// Given an intrinsic, checks if on the target the intrinsic will need to map
696 /// to a MemIntrinsicNode (touches memory). If this is the case, it returns
697 /// true and store the intrinsic information into the IntrinsicInfo that was
698 /// passed to the function.
699 virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
700 unsigned /*Intrinsic*/) const {
704 /// Returns true if the target can instruction select the specified FP
705 /// immediate natively. If false, the legalizer will materialize the FP
706 /// immediate as a load from a constant pool.
707 virtual bool isFPImmLegal(const APFloat &/*Imm*/, EVT /*VT*/) const {
711 /// Targets can use this to indicate that they only support *some*
712 /// VECTOR_SHUFFLE operations, those with specific masks. By default, if a
713 /// target supports the VECTOR_SHUFFLE node, all mask values are assumed to be
715 virtual bool isShuffleMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
720 /// Returns true if the operation can trap for the value type.
722 /// VT must be a legal type. By default, we optimistically assume most
723 /// operations don't trap except for integer divide and remainder.
724 virtual bool canOpTrap(unsigned Op, EVT VT) const;
726 /// Similar to isShuffleMaskLegal. This is used by Targets can use this to
727 /// indicate if there is a suitable VECTOR_SHUFFLE that can be used to replace
728 /// a VAND with a constant pool entry.
729 virtual bool isVectorClearMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
734 /// Return how this operation should be treated: either it is legal, needs to
735 /// be promoted to a larger size, needs to be expanded to some other code
736 /// sequence, or the target has a custom expander for it.
737 LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
738 if (VT.isExtended()) return Expand;
739 // If a target-specific SDNode requires legalization, require the target
740 // to provide custom legalization for it.
741 if (Op >= array_lengthof(OpActions[0])) return Custom;
742 return OpActions[(unsigned)VT.getSimpleVT().SimpleTy][Op];
745 /// Return true if the specified operation is legal on this target or can be
746 /// made legal with custom lowering. This is used to help guide high-level
747 /// lowering decisions.
748 bool isOperationLegalOrCustom(unsigned Op, EVT VT) const {
749 return (VT == MVT::Other || isTypeLegal(VT)) &&
750 (getOperationAction(Op, VT) == Legal ||
751 getOperationAction(Op, VT) == Custom);
754 /// Return true if the specified operation is legal on this target or can be
755 /// made legal using promotion. This is used to help guide high-level lowering
757 bool isOperationLegalOrPromote(unsigned Op, EVT VT) const {
758 return (VT == MVT::Other || isTypeLegal(VT)) &&
759 (getOperationAction(Op, VT) == Legal ||
760 getOperationAction(Op, VT) == Promote);
763 /// Return true if the specified operation is legal on this target or can be
764 /// made legal with custom lowering or using promotion. This is used to help
765 /// guide high-level lowering decisions.
766 bool isOperationLegalOrCustomOrPromote(unsigned Op, EVT VT) const {
767 return (VT == MVT::Other || isTypeLegal(VT)) &&
768 (getOperationAction(Op, VT) == Legal ||
769 getOperationAction(Op, VT) == Custom ||
770 getOperationAction(Op, VT) == Promote);
773 /// Return true if the specified operation is illegal but has a custom lowering
774 /// on that type. This is used to help guide high-level lowering
776 bool isOperationCustom(unsigned Op, EVT VT) const {
777 return (!isTypeLegal(VT) && getOperationAction(Op, VT) == Custom);
780 /// Return true if lowering to a jump table is allowed.
781 bool areJTsAllowed(const Function *Fn) const {
782 if (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true")
785 return isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
786 isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
789 /// Check whether the range [Low,High] fits in a machine word.
790 bool rangeFitsInWord(const APInt &Low, const APInt &High,
791 const DataLayout &DL) const {
792 // FIXME: Using the pointer type doesn't seem ideal.
793 uint64_t BW = DL.getPointerSizeInBits();
794 uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1;
798 /// Return true if lowering to a jump table is suitable for a set of case
799 /// clusters which may contain \p NumCases cases, \p Range range of values.
800 /// FIXME: This function check the maximum table size and density, but the
801 /// minimum size is not checked. It would be nice if the the minimum size is
802 /// also combined within this function. Currently, the minimum size check is
803 /// performed in findJumpTable() in SelectionDAGBuiler and
804 /// getEstimatedNumberOfCaseClusters() in BasicTTIImpl.
805 bool isSuitableForJumpTable(const SwitchInst *SI, uint64_t NumCases,
806 uint64_t Range) const {
807 const bool OptForSize = SI->getParent()->getParent()->optForSize();
808 const unsigned MinDensity = getMinimumJumpTableDensity(OptForSize);
809 const unsigned MaxJumpTableSize =
810 OptForSize || getMaximumJumpTableSize() == 0
812 : getMaximumJumpTableSize();
813 // Check whether a range of clusters is dense enough for a jump table.
814 if (Range <= MaxJumpTableSize &&
815 (NumCases * 100 >= Range * MinDensity)) {
821 /// Return true if lowering to a bit test is suitable for a set of case
822 /// clusters which contains \p NumDests unique destinations, \p Low and
823 /// \p High as its lowest and highest case values, and expects \p NumCmps
824 /// case value comparisons. Check if the number of destinations, comparison
825 /// metric, and range are all suitable.
826 bool isSuitableForBitTests(unsigned NumDests, unsigned NumCmps,
827 const APInt &Low, const APInt &High,
828 const DataLayout &DL) const {
829 // FIXME: I don't think NumCmps is the correct metric: a single case and a
830 // range of cases both require only one branch to lower. Just looking at the
831 // number of clusters and destinations should be enough to decide whether to
834 // To lower a range with bit tests, the range must fit the bitwidth of a
836 if (!rangeFitsInWord(Low, High, DL))
839 // Decide whether it's profitable to lower this range with bit tests. Each
840 // destination requires a bit test and branch, and there is an overall range
841 // check branch. For a small number of clusters, separate comparisons might
842 // be cheaper, and for many destinations, splitting the range might be
844 return (NumDests == 1 && NumCmps >= 3) || (NumDests == 2 && NumCmps >= 5) ||
845 (NumDests == 3 && NumCmps >= 6);
848 /// Return true if the specified operation is illegal on this target or
849 /// unlikely to be made legal with custom lowering. This is used to help guide
850 /// high-level lowering decisions.
851 bool isOperationExpand(unsigned Op, EVT VT) const {
852 return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
855 /// Return true if the specified operation is legal on this target.
856 bool isOperationLegal(unsigned Op, EVT VT) const {
857 return (VT == MVT::Other || isTypeLegal(VT)) &&
858 getOperationAction(Op, VT) == Legal;
861 /// Return how this load with extension should be treated: either it is legal,
862 /// needs to be promoted to a larger size, needs to be expanded to some other
863 /// code sequence, or the target has a custom expander for it.
864 LegalizeAction getLoadExtAction(unsigned ExtType, EVT ValVT,
866 if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
867 unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
868 unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
869 assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValI < MVT::LAST_VALUETYPE &&
870 MemI < MVT::LAST_VALUETYPE && "Table isn't big enough!");
871 unsigned Shift = 4 * ExtType;
872 return (LegalizeAction)((LoadExtActions[ValI][MemI] >> Shift) & 0xf);
875 /// Return true if the specified load with extension is legal on this target.
876 bool isLoadExtLegal(unsigned ExtType, EVT ValVT, EVT MemVT) const {
877 return getLoadExtAction(ExtType, ValVT, MemVT) == Legal;
880 /// Return true if the specified load with extension is legal or custom
882 bool isLoadExtLegalOrCustom(unsigned ExtType, EVT ValVT, EVT MemVT) const {
883 return getLoadExtAction(ExtType, ValVT, MemVT) == Legal ||
884 getLoadExtAction(ExtType, ValVT, MemVT) == Custom;
887 /// Return how this store with truncation should be treated: either it is
888 /// legal, needs to be promoted to a larger size, needs to be expanded to some
889 /// other code sequence, or the target has a custom expander for it.
890 LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT) const {
891 if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
892 unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
893 unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
894 assert(ValI < MVT::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE &&
895 "Table isn't big enough!");
896 return TruncStoreActions[ValI][MemI];
899 /// Return true if the specified store with truncation is legal on this
901 bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
902 return isTypeLegal(ValVT) && getTruncStoreAction(ValVT, MemVT) == Legal;
905 /// Return true if the specified store with truncation has solution on this
907 bool isTruncStoreLegalOrCustom(EVT ValVT, EVT MemVT) const {
908 return isTypeLegal(ValVT) &&
909 (getTruncStoreAction(ValVT, MemVT) == Legal ||
910 getTruncStoreAction(ValVT, MemVT) == Custom);
913 /// Return how the indexed load should be treated: either it is legal, needs
914 /// to be promoted to a larger size, needs to be expanded to some other code
915 /// sequence, or the target has a custom expander for it.
917 getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
918 assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&
919 "Table isn't big enough!");
920 unsigned Ty = (unsigned)VT.SimpleTy;
921 return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] & 0xf0) >> 4);
924 /// Return true if the specified indexed load is legal on this target.
925 bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
926 return VT.isSimple() &&
927 (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
928 getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
931 /// Return how the indexed store should be treated: either it is legal, needs
932 /// to be promoted to a larger size, needs to be expanded to some other code
933 /// sequence, or the target has a custom expander for it.
935 getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
936 assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&
937 "Table isn't big enough!");
938 unsigned Ty = (unsigned)VT.SimpleTy;
939 return (LegalizeAction)(IndexedModeActions[Ty][IdxMode] & 0x0f);
942 /// Return true if the specified indexed load is legal on this target.
943 bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
944 return VT.isSimple() &&
945 (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
946 getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
949 /// Return how the condition code should be treated: either it is legal, needs
950 /// to be expanded to some other code sequence, or the target has a custom
953 getCondCodeAction(ISD::CondCode CC, MVT VT) const {
954 assert((unsigned)CC < array_lengthof(CondCodeActions) &&
955 ((unsigned)VT.SimpleTy >> 3) < array_lengthof(CondCodeActions[0]) &&
956 "Table isn't big enough!");
957 // See setCondCodeAction for how this is encoded.
958 uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
959 uint32_t Value = CondCodeActions[CC][VT.SimpleTy >> 3];
960 LegalizeAction Action = (LegalizeAction) ((Value >> Shift) & 0xF);
961 assert(Action != Promote && "Can't promote condition code!");
965 /// Return true if the specified condition code is legal on this target.
966 bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
968 getCondCodeAction(CC, VT) == Legal ||
969 getCondCodeAction(CC, VT) == Custom;
972 /// If the action for this operation is to promote, this method returns the
973 /// ValueType to promote to.
974 MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
975 assert(getOperationAction(Op, VT) == Promote &&
976 "This operation isn't promoted!");
978 // See if this has an explicit type specified.
979 std::map<std::pair<unsigned, MVT::SimpleValueType>,
980 MVT::SimpleValueType>::const_iterator PTTI =
981 PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
982 if (PTTI != PromoteToType.end()) return PTTI->second;
984 assert((VT.isInteger() || VT.isFloatingPoint()) &&
985 "Cannot autopromote this type, add it with AddPromotedToType.");
989 NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
990 assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
991 "Didn't find type to promote to!");
992 } while (!isTypeLegal(NVT) ||
993 getOperationAction(Op, NVT) == Promote);
997 /// Return the EVT corresponding to this LLVM type. This is fixed by the LLVM
998 /// operations except for the pointer size. If AllowUnknown is true, this
999 /// will return MVT::Other for types with no EVT counterpart (e.g. structs),
1000 /// otherwise it will assert.
1001 EVT getValueType(const DataLayout &DL, Type *Ty,
1002 bool AllowUnknown = false) const {
1003 // Lower scalar pointers to native pointer types.
1004 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
1005 return getPointerTy(DL, PTy->getAddressSpace());
1007 if (Ty->isVectorTy()) {
1008 VectorType *VTy = cast<VectorType>(Ty);
1009 Type *Elm = VTy->getElementType();
1010 // Lower vectors of pointers to native pointer types.
1011 if (PointerType *PT = dyn_cast<PointerType>(Elm)) {
1012 EVT PointerTy(getPointerTy(DL, PT->getAddressSpace()));
1013 Elm = PointerTy.getTypeForEVT(Ty->getContext());
1016 return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
1017 VTy->getNumElements());
1019 return EVT::getEVT(Ty, AllowUnknown);
1022 /// Return the MVT corresponding to this LLVM type. See getValueType.
1023 MVT getSimpleValueType(const DataLayout &DL, Type *Ty,
1024 bool AllowUnknown = false) const {
1025 return getValueType(DL, Ty, AllowUnknown).getSimpleVT();
1028 /// Return the desired alignment for ByVal or InAlloca aggregate function
1029 /// arguments in the caller parameter area. This is the actual alignment, not
1031 virtual unsigned getByValTypeAlignment(Type *Ty, const DataLayout &DL) const;
1033 /// Return the type of registers that this ValueType will eventually require.
1034 MVT getRegisterType(MVT VT) const {
1035 assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
1036 return RegisterTypeForVT[VT.SimpleTy];
1039 /// Return the type of registers that this ValueType will eventually require.
1040 MVT getRegisterType(LLVMContext &Context, EVT VT) const {
1041 if (VT.isSimple()) {
1042 assert((unsigned)VT.getSimpleVT().SimpleTy <
1043 array_lengthof(RegisterTypeForVT));
1044 return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
1046 if (VT.isVector()) {
1049 unsigned NumIntermediates;
1050 (void)getVectorTypeBreakdown(Context, VT, VT1,
1051 NumIntermediates, RegisterVT);
1054 if (VT.isInteger()) {
1055 return getRegisterType(Context, getTypeToTransformTo(Context, VT));
1057 llvm_unreachable("Unsupported extended type!");
1060 /// Return the number of registers that this ValueType will eventually
1063 /// This is one for any types promoted to live in larger registers, but may be
1064 /// more than one for types (like i64) that are split into pieces. For types
1065 /// like i140, which are first promoted then expanded, it is the number of
1066 /// registers needed to hold all the bits of the original type. For an i140
1067 /// on a 32 bit machine this means 5 registers.
1068 unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
1069 if (VT.isSimple()) {
1070 assert((unsigned)VT.getSimpleVT().SimpleTy <
1071 array_lengthof(NumRegistersForVT));
1072 return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
1074 if (VT.isVector()) {
1077 unsigned NumIntermediates;
1078 return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
1080 if (VT.isInteger()) {
1081 unsigned BitWidth = VT.getSizeInBits();
1082 unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
1083 return (BitWidth + RegWidth - 1) / RegWidth;
1085 llvm_unreachable("Unsupported extended type!");
1088 /// If true, then instruction selection should seek to shrink the FP constant
1089 /// of the specified type to a smaller type in order to save space and / or
1091 virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
1093 // Return true if it is profitable to reduce the given load node to a smaller
1096 // e.g. (i16 (trunc (i32 (load x))) -> i16 load x should be performed
1097 virtual bool shouldReduceLoadWidth(SDNode *Load,
1098 ISD::LoadExtType ExtTy,
1103 /// When splitting a value of the specified type into parts, does the Lo
1104 /// or Hi part come first? This usually follows the endianness, except
1105 /// for ppcf128, where the Hi part always comes first.
1106 bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const {
1107 return DL.isBigEndian() || VT == MVT::ppcf128;
1110 /// If true, the target has custom DAG combine transformations that it can
1111 /// perform for the specified node.
1112 bool hasTargetDAGCombine(ISD::NodeType NT) const {
1113 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1114 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
1117 unsigned getGatherAllAliasesMaxDepth() const {
1118 return GatherAllAliasesMaxDepth;
1121 /// Returns the size of the platform's va_list object.
1122 virtual unsigned getVaListSizeInBits(const DataLayout &DL) const {
1123 return getPointerTy(DL).getSizeInBits();
1126 /// \brief Get maximum # of store operations permitted for llvm.memset
1128 /// This function returns the maximum number of store operations permitted
1129 /// to replace a call to llvm.memset. The value is set by the target at the
1130 /// performance threshold for such a replacement. If OptSize is true,
1131 /// return the limit for functions that have OptSize attribute.
1132 unsigned getMaxStoresPerMemset(bool OptSize) const {
1133 return OptSize ? MaxStoresPerMemsetOptSize : MaxStoresPerMemset;
1136 /// \brief Get maximum # of store operations permitted for llvm.memcpy
1138 /// This function returns the maximum number of store operations permitted
1139 /// to replace a call to llvm.memcpy. The value is set by the target at the
1140 /// performance threshold for such a replacement. If OptSize is true,
1141 /// return the limit for functions that have OptSize attribute.
1142 unsigned getMaxStoresPerMemcpy(bool OptSize) const {
1143 return OptSize ? MaxStoresPerMemcpyOptSize : MaxStoresPerMemcpy;
1146 /// \brief Get maximum # of store operations permitted for llvm.memmove
1148 /// This function returns the maximum number of store operations permitted
1149 /// to replace a call to llvm.memmove. The value is set by the target at the
1150 /// performance threshold for such a replacement. If OptSize is true,
1151 /// return the limit for functions that have OptSize attribute.
1152 unsigned getMaxStoresPerMemmove(bool OptSize) const {
1153 return OptSize ? MaxStoresPerMemmoveOptSize : MaxStoresPerMemmove;
1156 /// \brief Determine if the target supports unaligned memory accesses.
1158 /// This function returns true if the target allows unaligned memory accesses
1159 /// of the specified type in the given address space. If true, it also returns
1160 /// whether the unaligned memory access is "fast" in the last argument by
1161 /// reference. This is used, for example, in situations where an array
1162 /// copy/move/set is converted to a sequence of store operations. Its use
1163 /// helps to ensure that such replacements don't generate code that causes an
1164 /// alignment error (trap) on the target machine.
1165 virtual bool allowsMisalignedMemoryAccesses(EVT,
1166 unsigned AddrSpace = 0,
1168 bool * /*Fast*/ = nullptr) const {
1172 /// Return true if the target supports a memory access of this type for the
1173 /// given address space and alignment. If the access is allowed, the optional
1174 /// final parameter returns if the access is also fast (as defined by the
1176 bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT,
1177 unsigned AddrSpace = 0, unsigned Alignment = 1,
1178 bool *Fast = nullptr) const;
1180 /// Returns the target specific optimal type for load and store operations as
1181 /// a result of memset, memcpy, and memmove lowering.
1183 /// If DstAlign is zero that means it's safe to destination alignment can
1184 /// satisfy any constraint. Similarly if SrcAlign is zero it means there isn't
1185 /// a need to check it against alignment requirement, probably because the
1186 /// source does not need to be loaded. If 'IsMemset' is true, that means it's
1187 /// expanding a memset. If 'ZeroMemset' is true, that means it's a memset of
1188 /// zero. 'MemcpyStrSrc' indicates whether the memcpy source is constant so it
1189 /// does not need to be loaded. It returns EVT::Other if the type should be
1190 /// determined using generic target-independent logic.
1191 virtual EVT getOptimalMemOpType(uint64_t /*Size*/,
1192 unsigned /*DstAlign*/, unsigned /*SrcAlign*/,
1194 bool /*ZeroMemset*/,
1195 bool /*MemcpyStrSrc*/,
1196 MachineFunction &/*MF*/) const {
1200 /// Returns true if it's safe to use load / store of the specified type to
1201 /// expand memcpy / memset inline.
1203 /// This is mostly true for all types except for some special cases. For
1204 /// example, on X86 targets without SSE2 f64 load / store are done with fldl /
1205 /// fstpl which also does type conversion. Note the specified type doesn't
1206 /// have to be legal as the hook is used before type legalization.
1207 virtual bool isSafeMemOpType(MVT /*VT*/) const { return true; }
1209 /// Determine if we should use _setjmp or setjmp to implement llvm.setjmp.
1210 bool usesUnderscoreSetJmp() const {
1211 return UseUnderscoreSetJmp;
1214 /// Determine if we should use _longjmp or longjmp to implement llvm.longjmp.
1215 bool usesUnderscoreLongJmp() const {
1216 return UseUnderscoreLongJmp;
1219 /// Return lower limit for number of blocks in a jump table.
1220 unsigned getMinimumJumpTableEntries() const;
1222 /// Return lower limit of the density in a jump table.
1223 unsigned getMinimumJumpTableDensity(bool OptForSize) const;
1225 /// Return upper limit for number of entries in a jump table.
1226 /// Zero if no limit.
1227 unsigned getMaximumJumpTableSize() const;
1229 virtual bool isJumpTableRelative() const {
1230 return TM.isPositionIndependent();
1233 /// If a physical register, this specifies the register that
1234 /// llvm.savestack/llvm.restorestack should save and restore.
1235 unsigned getStackPointerRegisterToSaveRestore() const {
1236 return StackPointerRegisterToSaveRestore;
1239 /// If a physical register, this returns the register that receives the
1240 /// exception address on entry to an EH pad.
1242 getExceptionPointerRegister(const Constant *PersonalityFn) const {
1243 // 0 is guaranteed to be the NoRegister value on all targets
1247 /// If a physical register, this returns the register that receives the
1248 /// exception typeid on entry to a landing pad.
1250 getExceptionSelectorRegister(const Constant *PersonalityFn) const {
1251 // 0 is guaranteed to be the NoRegister value on all targets
1255 virtual bool needsFixedCatchObjects() const {
1256 report_fatal_error("Funclet EH is not implemented for this target");
1259 /// Returns the target's jmp_buf size in bytes (if never set, the default is
1261 unsigned getJumpBufSize() const {
1265 /// Returns the target's jmp_buf alignment in bytes (if never set, the default
1267 unsigned getJumpBufAlignment() const {
1268 return JumpBufAlignment;
1271 /// Return the minimum stack alignment of an argument.
1272 unsigned getMinStackArgumentAlignment() const {
1273 return MinStackArgumentAlignment;
1276 /// Return the minimum function alignment.
1277 unsigned getMinFunctionAlignment() const {
1278 return MinFunctionAlignment;
1281 /// Return the preferred function alignment.
1282 unsigned getPrefFunctionAlignment() const {
1283 return PrefFunctionAlignment;
1286 /// Return the preferred loop alignment.
1287 virtual unsigned getPrefLoopAlignment(MachineLoop *ML = nullptr) const {
1288 return PrefLoopAlignment;
1291 /// If the target has a standard location for the stack protector guard,
1292 /// returns the address of that location. Otherwise, returns nullptr.
1293 /// DEPRECATED: please override useLoadStackGuardNode and customize
1294 /// LOAD_STACK_GUARD, or customize @llvm.stackguard().
1295 virtual Value *getIRStackGuard(IRBuilder<> &IRB) const;
1297 /// Inserts necessary declarations for SSP (stack protection) purpose.
1298 /// Should be used only when getIRStackGuard returns nullptr.
1299 virtual void insertSSPDeclarations(Module &M) const;
1301 /// Return the variable that's previously inserted by insertSSPDeclarations,
1302 /// if any, otherwise return nullptr. Should be used only when
1303 /// getIRStackGuard returns nullptr.
1304 virtual Value *getSDagStackGuard(const Module &M) const;
1306 /// If the target has a standard stack protection check function that
1307 /// performs validation and error handling, returns the function. Otherwise,
1308 /// returns nullptr. Must be previously inserted by insertSSPDeclarations.
1309 /// Should be used only when getIRStackGuard returns nullptr.
1310 virtual Value *getSSPStackGuardCheck(const Module &M) const;
1313 Value *getDefaultSafeStackPointerLocation(IRBuilder<> &IRB,
1317 /// Returns the target-specific address of the unsafe stack pointer.
1318 virtual Value *getSafeStackPointerLocation(IRBuilder<> &IRB) const;
1320 /// Returns true if a cast between SrcAS and DestAS is a noop.
1321 virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const {
1325 /// Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g. we
1326 /// are happy to sink it into basic blocks.
1327 virtual bool isCheapAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const {
1328 return isNoopAddrSpaceCast(SrcAS, DestAS);
1331 /// Return true if the pointer arguments to CI should be aligned by aligning
1332 /// the object whose address is being passed. If so then MinSize is set to the
1333 /// minimum size the object must be to be aligned and PrefAlign is set to the
1334 /// preferred alignment.
1335 virtual bool shouldAlignPointerArgs(CallInst * /*CI*/, unsigned & /*MinSize*/,
1336 unsigned & /*PrefAlign*/) const {
1340 //===--------------------------------------------------------------------===//
1341 /// \name Helpers for TargetTransformInfo implementations
1344 /// Get the ISD node that corresponds to the Instruction class opcode.
1345 int InstructionOpcodeToISD(unsigned Opcode) const;
1347 /// Estimate the cost of type-legalization and the legalized type.
1348 std::pair<int, MVT> getTypeLegalizationCost(const DataLayout &DL,
1353 //===--------------------------------------------------------------------===//
1354 /// \name Helpers for atomic expansion.
1357 /// Returns the maximum atomic operation size (in bits) supported by
1358 /// the backend. Atomic operations greater than this size (as well
1359 /// as ones that are not naturally aligned), will be expanded by
1360 /// AtomicExpandPass into an __atomic_* library call.
1361 unsigned getMaxAtomicSizeInBitsSupported() const {
1362 return MaxAtomicSizeInBitsSupported;
1365 /// Returns the size of the smallest cmpxchg or ll/sc instruction
1366 /// the backend supports. Any smaller operations are widened in
1367 /// AtomicExpandPass.
1369 /// Note that *unlike* operations above the maximum size, atomic ops
1370 /// are still natively supported below the minimum; they just
1371 /// require a more complex expansion.
1372 unsigned getMinCmpXchgSizeInBits() const { return MinCmpXchgSizeInBits; }
1374 /// Whether AtomicExpandPass should automatically insert fences and reduce
1375 /// ordering for this atomic. This should be true for most architectures with
1376 /// weak memory ordering. Defaults to false.
1377 virtual bool shouldInsertFencesForAtomic(const Instruction *I) const {
1381 /// Perform a load-linked operation on Addr, returning a "Value *" with the
1382 /// corresponding pointee type. This may entail some non-trivial operations to
1383 /// truncate or reconstruct types that will be illegal in the backend. See
1384 /// ARMISelLowering for an example implementation.
1385 virtual Value *emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
1386 AtomicOrdering Ord) const {
1387 llvm_unreachable("Load linked unimplemented on this target");
1390 /// Perform a store-conditional operation to Addr. Return the status of the
1391 /// store. This should be 0 if the store succeeded, non-zero otherwise.
1392 virtual Value *emitStoreConditional(IRBuilder<> &Builder, Value *Val,
1393 Value *Addr, AtomicOrdering Ord) const {
1394 llvm_unreachable("Store conditional unimplemented on this target");
1397 /// Inserts in the IR a target-specific intrinsic specifying a fence.
1398 /// It is called by AtomicExpandPass before expanding an
1399 /// AtomicRMW/AtomicCmpXchg/AtomicStore/AtomicLoad
1400 /// if shouldInsertFencesForAtomic returns true.
1402 /// Inst is the original atomic instruction, prior to other expansions that
1403 /// may be performed.
1405 /// This function should either return a nullptr, or a pointer to an IR-level
1406 /// Instruction*. Even complex fence sequences can be represented by a
1407 /// single Instruction* through an intrinsic to be lowered later.
1408 /// Backends should override this method to produce target-specific intrinsic
1409 /// for their fences.
1410 /// FIXME: Please note that the default implementation here in terms of
1411 /// IR-level fences exists for historical/compatibility reasons and is
1412 /// *unsound* ! Fences cannot, in general, be used to restore sequential
1413 /// consistency. For example, consider the following example:
1414 /// atomic<int> x = y = 0;
1415 /// int r1, r2, r3, r4;
1426 /// r1 = r3 = 1 and r2 = r4 = 0 is impossible as long as the accesses are all
1427 /// seq_cst. But if they are lowered to monotonic accesses, no amount of
1428 /// IR-level fences can prevent it.
1430 virtual Instruction *emitLeadingFence(IRBuilder<> &Builder, Instruction *Inst,
1431 AtomicOrdering Ord) const {
1432 if (isReleaseOrStronger(Ord) && Inst->hasAtomicStore())
1433 return Builder.CreateFence(Ord);
1438 virtual Instruction *emitTrailingFence(IRBuilder<> &Builder,
1440 AtomicOrdering Ord) const {
1441 if (isAcquireOrStronger(Ord))
1442 return Builder.CreateFence(Ord);
1448 // Emits code that executes when the comparison result in the ll/sc
1449 // expansion of a cmpxchg instruction is such that the store-conditional will
1450 // not execute. This makes it possible to balance out the load-linked with
1451 // a dedicated instruction, if desired.
1452 // E.g., on ARM, if ldrex isn't followed by strex, the exclusive monitor would
1453 // be unnecessarily held, except if clrex, inserted by this hook, is executed.
1454 virtual void emitAtomicCmpXchgNoStoreLLBalance(IRBuilder<> &Builder) const {}
1456 /// Returns true if the given (atomic) store should be expanded by the
1457 /// IR-level AtomicExpand pass into an "atomic xchg" which ignores its input.
1458 virtual bool shouldExpandAtomicStoreInIR(StoreInst *SI) const {
1462 /// Returns true if arguments should be sign-extended in lib calls.
1463 virtual bool shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
1467 /// Returns how the given (atomic) load should be expanded by the
1468 /// IR-level AtomicExpand pass.
1469 virtual AtomicExpansionKind shouldExpandAtomicLoadInIR(LoadInst *LI) const {
1470 return AtomicExpansionKind::None;
1473 /// Returns true if the given atomic cmpxchg should be expanded by the
1474 /// IR-level AtomicExpand pass into a load-linked/store-conditional sequence
1475 /// (through emitLoadLinked() and emitStoreConditional()).
1476 virtual bool shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
1480 /// Returns how the IR-level AtomicExpand pass should expand the given
1481 /// AtomicRMW, if at all. Default is to never expand.
1482 virtual AtomicExpansionKind shouldExpandAtomicRMWInIR(AtomicRMWInst *) const {
1483 return AtomicExpansionKind::None;
1486 /// On some platforms, an AtomicRMW that never actually modifies the value
1487 /// (such as fetch_add of 0) can be turned into a fence followed by an
1488 /// atomic load. This may sound useless, but it makes it possible for the
1489 /// processor to keep the cacheline shared, dramatically improving
1490 /// performance. And such idempotent RMWs are useful for implementing some
1491 /// kinds of locks, see for example (justification + benchmarks):
1492 /// http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf
1493 /// This method tries doing that transformation, returning the atomic load if
1494 /// it succeeds, and nullptr otherwise.
1495 /// If shouldExpandAtomicLoadInIR returns true on that load, it will undergo
1496 /// another round of expansion.
1498 lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *RMWI) const {
1502 /// Returns how the platform's atomic operations are extended (ZERO_EXTEND,
1503 /// SIGN_EXTEND, or ANY_EXTEND).
1504 virtual ISD::NodeType getExtendForAtomicOps() const {
1505 return ISD::ZERO_EXTEND;
1510 /// Returns true if we should normalize
1511 /// select(N0&N1, X, Y) => select(N0, select(N1, X, Y), Y) and
1512 /// select(N0|N1, X, Y) => select(N0, select(N1, X, Y, Y)) if it is likely
1513 /// that it saves us from materializing N0 and N1 in an integer register.
1514 /// Targets that are able to perform and/or on flags should return false here.
1515 virtual bool shouldNormalizeToSelectSequence(LLVMContext &Context,
1517 // If a target has multiple condition registers, then it likely has logical
1518 // operations on those registers.
1519 if (hasMultipleConditionRegisters())
1521 // Only do the transform if the value won't be split into multiple
1523 LegalizeTypeAction Action = getTypeAction(Context, VT);
1524 return Action != TypeExpandInteger && Action != TypeExpandFloat &&
1525 Action != TypeSplitVector;
1528 /// Return true if a select of constants (select Cond, C1, C2) should be
1529 /// transformed into simple math ops with the condition value. For example:
1530 /// select Cond, C1, C1-1 --> add (zext Cond), C1-1
1531 virtual bool convertSelectOfConstantsToMath() const {
1535 //===--------------------------------------------------------------------===//
1536 // TargetLowering Configuration Methods - These methods should be invoked by
1537 // the derived class constructor to configure this object for the target.
1540 /// Specify how the target extends the result of integer and floating point
1541 /// boolean values from i1 to a wider type. See getBooleanContents.
1542 void setBooleanContents(BooleanContent Ty) {
1543 BooleanContents = Ty;
1544 BooleanFloatContents = Ty;
1547 /// Specify how the target extends the result of integer and floating point
1548 /// boolean values from i1 to a wider type. See getBooleanContents.
1549 void setBooleanContents(BooleanContent IntTy, BooleanContent FloatTy) {
1550 BooleanContents = IntTy;
1551 BooleanFloatContents = FloatTy;
1554 /// Specify how the target extends the result of a vector boolean value from a
1555 /// vector of i1 to a wider type. See getBooleanContents.
1556 void setBooleanVectorContents(BooleanContent Ty) {
1557 BooleanVectorContents = Ty;
1560 /// Specify the target scheduling preference.
1561 void setSchedulingPreference(Sched::Preference Pref) {
1562 SchedPreferenceInfo = Pref;
1565 /// Indicate whether this target prefers to use _setjmp to implement
1566 /// llvm.setjmp or the version without _. Defaults to false.
1567 void setUseUnderscoreSetJmp(bool Val) {
1568 UseUnderscoreSetJmp = Val;
1571 /// Indicate whether this target prefers to use _longjmp to implement
1572 /// llvm.longjmp or the version without _. Defaults to false.
1573 void setUseUnderscoreLongJmp(bool Val) {
1574 UseUnderscoreLongJmp = Val;
1577 /// Indicate the minimum number of blocks to generate jump tables.
1578 void setMinimumJumpTableEntries(unsigned Val);
1580 /// Indicate the maximum number of entries in jump tables.
1581 /// Set to zero to generate unlimited jump tables.
1582 void setMaximumJumpTableSize(unsigned);
1584 /// If set to a physical register, this specifies the register that
1585 /// llvm.savestack/llvm.restorestack should save and restore.
1586 void setStackPointerRegisterToSaveRestore(unsigned R) {
1587 StackPointerRegisterToSaveRestore = R;
1590 /// Tells the code generator that the target has multiple (allocatable)
1591 /// condition registers that can be used to store the results of comparisons
1592 /// for use by selects and conditional branches. With multiple condition
1593 /// registers, the code generator will not aggressively sink comparisons into
1594 /// the blocks of their users.
1595 void setHasMultipleConditionRegisters(bool hasManyRegs = true) {
1596 HasMultipleConditionRegisters = hasManyRegs;
1599 /// Tells the code generator that the target has BitExtract instructions.
1600 /// The code generator will aggressively sink "shift"s into the blocks of
1601 /// their users if the users will generate "and" instructions which can be
1602 /// combined with "shift" to BitExtract instructions.
1603 void setHasExtractBitsInsn(bool hasExtractInsn = true) {
1604 HasExtractBitsInsn = hasExtractInsn;
1607 /// Tells the code generator not to expand logic operations on comparison
1608 /// predicates into separate sequences that increase the amount of flow
1610 void setJumpIsExpensive(bool isExpensive = true);
1612 /// Tells the code generator that this target supports floating point
1613 /// exceptions and cares about preserving floating point exception behavior.
1614 void setHasFloatingPointExceptions(bool FPExceptions = true) {
1615 HasFloatingPointExceptions = FPExceptions;
1618 /// Tells the code generator which bitwidths to bypass.
1619 void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
1620 BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
1623 /// Add the specified register class as an available regclass for the
1624 /// specified value type. This indicates the selector can handle values of
1625 /// that class natively.
1626 void addRegisterClass(MVT VT, const TargetRegisterClass *RC) {
1627 assert((unsigned)VT.SimpleTy < array_lengthof(RegClassForVT));
1628 RegClassForVT[VT.SimpleTy] = RC;
1631 /// Return the largest legal super-reg register class of the register class
1632 /// for the specified type and its associated "cost".
1633 virtual std::pair<const TargetRegisterClass *, uint8_t>
1634 findRepresentativeClass(const TargetRegisterInfo *TRI, MVT VT) const;
1636 /// Once all of the register classes are added, this allows us to compute
1637 /// derived properties we expose.
1638 void computeRegisterProperties(const TargetRegisterInfo *TRI);
1640 /// Indicate that the specified operation does not work with the specified
1641 /// type and indicate what to do about it. Note that VT may refer to either
1642 /// the type of a result or that of an operand of Op.
1643 void setOperationAction(unsigned Op, MVT VT,
1644 LegalizeAction Action) {
1645 assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
1646 OpActions[(unsigned)VT.SimpleTy][Op] = Action;
1649 /// Indicate that the specified load with extension does not work with the
1650 /// specified type and indicate what to do about it.
1651 void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT,
1652 LegalizeAction Action) {
1653 assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() &&
1654 MemVT.isValid() && "Table isn't big enough!");
1655 assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
1656 unsigned Shift = 4 * ExtType;
1657 LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] &= ~((uint16_t)0xF << Shift);
1658 LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] |= (uint16_t)Action << Shift;
1661 /// Indicate that the specified truncating store does not work with the
1662 /// specified type and indicate what to do about it.
1663 void setTruncStoreAction(MVT ValVT, MVT MemVT,
1664 LegalizeAction Action) {
1665 assert(ValVT.isValid() && MemVT.isValid() && "Table isn't big enough!");
1666 TruncStoreActions[(unsigned)ValVT.SimpleTy][MemVT.SimpleTy] = Action;
1669 /// Indicate that the specified indexed load does or does not work with the
1670 /// specified type and indicate what to do abort it.
1672 /// NOTE: All indexed mode loads are initialized to Expand in
1673 /// TargetLowering.cpp
1674 void setIndexedLoadAction(unsigned IdxMode, MVT VT,
1675 LegalizeAction Action) {
1676 assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&
1677 (unsigned)Action < 0xf && "Table isn't big enough!");
1678 // Load action are kept in the upper half.
1679 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0xf0;
1680 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action) <<4;
1683 /// Indicate that the specified indexed store does or does not work with the
1684 /// specified type and indicate what to do about it.
1686 /// NOTE: All indexed mode stores are initialized to Expand in
1687 /// TargetLowering.cpp
1688 void setIndexedStoreAction(unsigned IdxMode, MVT VT,
1689 LegalizeAction Action) {
1690 assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&
1691 (unsigned)Action < 0xf && "Table isn't big enough!");
1692 // Store action are kept in the lower half.
1693 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0x0f;
1694 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action);
1697 /// Indicate that the specified condition code is or isn't supported on the
1698 /// target and indicate what to do about it.
1699 void setCondCodeAction(ISD::CondCode CC, MVT VT,
1700 LegalizeAction Action) {
1701 assert(VT.isValid() && (unsigned)CC < array_lengthof(CondCodeActions) &&
1702 "Table isn't big enough!");
1703 assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
1704 /// The lower 3 bits of the SimpleTy index into Nth 4bit set from the 32-bit
1705 /// value and the upper 29 bits index into the second dimension of the array
1706 /// to select what 32-bit value to use.
1707 uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
1708 CondCodeActions[CC][VT.SimpleTy >> 3] &= ~((uint32_t)0xF << Shift);
1709 CondCodeActions[CC][VT.SimpleTy >> 3] |= (uint32_t)Action << Shift;
1712 /// If Opc/OrigVT is specified as being promoted, the promotion code defaults
1713 /// to trying a larger integer/fp until it can find one that works. If that
1714 /// default is insufficient, this method can be used by the target to override
1716 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1717 PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
1720 /// Convenience method to set an operation to Promote and specify the type
1721 /// in a single call.
1722 void setOperationPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1723 setOperationAction(Opc, OrigVT, Promote);
1724 AddPromotedToType(Opc, OrigVT, DestVT);
1727 /// Targets should invoke this method for each target independent node that
1728 /// they want to provide a custom DAG combiner for by implementing the
1729 /// PerformDAGCombine virtual method.
1730 void setTargetDAGCombine(ISD::NodeType NT) {
1731 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1732 TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
1735 /// Set the target's required jmp_buf buffer size (in bytes); default is 200
1736 void setJumpBufSize(unsigned Size) {
1740 /// Set the target's required jmp_buf buffer alignment (in bytes); default is
1742 void setJumpBufAlignment(unsigned Align) {
1743 JumpBufAlignment = Align;
1746 /// Set the target's minimum function alignment (in log2(bytes))
1747 void setMinFunctionAlignment(unsigned Align) {
1748 MinFunctionAlignment = Align;
1751 /// Set the target's preferred function alignment. This should be set if
1752 /// there is a performance benefit to higher-than-minimum alignment (in
1754 void setPrefFunctionAlignment(unsigned Align) {
1755 PrefFunctionAlignment = Align;
1758 /// Set the target's preferred loop alignment. Default alignment is zero, it
1759 /// means the target does not care about loop alignment. The alignment is
1760 /// specified in log2(bytes). The target may also override
1761 /// getPrefLoopAlignment to provide per-loop values.
1762 void setPrefLoopAlignment(unsigned Align) {
1763 PrefLoopAlignment = Align;
1766 /// Set the minimum stack alignment of an argument (in log2(bytes)).
1767 void setMinStackArgumentAlignment(unsigned Align) {
1768 MinStackArgumentAlignment = Align;
1771 /// Set the maximum atomic operation size supported by the
1772 /// backend. Atomic operations greater than this size (as well as
1773 /// ones that are not naturally aligned), will be expanded by
1774 /// AtomicExpandPass into an __atomic_* library call.
1775 void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits) {
1776 MaxAtomicSizeInBitsSupported = SizeInBits;
1779 // Sets the minimum cmpxchg or ll/sc size supported by the backend.
1780 void setMinCmpXchgSizeInBits(unsigned SizeInBits) {
1781 MinCmpXchgSizeInBits = SizeInBits;
1785 //===--------------------------------------------------------------------===//
1786 // Addressing mode description hooks (used by LSR etc).
1789 /// CodeGenPrepare sinks address calculations into the same BB as Load/Store
1790 /// instructions reading the address. This allows as much computation as
1791 /// possible to be done in the address mode for that operand. This hook lets
1792 /// targets also pass back when this should be done on intrinsics which
1794 virtual bool getAddrModeArguments(IntrinsicInst * /*I*/,
1795 SmallVectorImpl<Value*> &/*Ops*/,
1796 Type *&/*AccessTy*/) const {
1800 /// This represents an addressing mode of:
1801 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
1802 /// If BaseGV is null, there is no BaseGV.
1803 /// If BaseOffs is zero, there is no base offset.
1804 /// If HasBaseReg is false, there is no base register.
1805 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
1808 GlobalValue *BaseGV = nullptr;
1809 int64_t BaseOffs = 0;
1810 bool HasBaseReg = false;
1812 AddrMode() = default;
1815 /// Return true if the addressing mode represented by AM is legal for this
1816 /// target, for a load/store of the specified type.
1818 /// The type may be VoidTy, in which case only return true if the addressing
1819 /// mode is legal for a load/store of any legal type. TODO: Handle
1820 /// pre/postinc as well.
1822 /// If the address space cannot be determined, it will be -1.
1824 /// TODO: Remove default argument
1825 virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM,
1826 Type *Ty, unsigned AddrSpace) const;
1828 /// \brief Return the cost of the scaling factor used in the addressing mode
1829 /// represented by AM for this target, for a load/store of the specified type.
1831 /// If the AM is supported, the return value must be >= 0.
1832 /// If the AM is not supported, it returns a negative value.
1833 /// TODO: Handle pre/postinc as well.
1834 /// TODO: Remove default argument
1835 virtual int getScalingFactorCost(const DataLayout &DL, const AddrMode &AM,
1836 Type *Ty, unsigned AS = 0) const {
1837 // Default: assume that any scaling factor used in a legal AM is free.
1838 if (isLegalAddressingMode(DL, AM, Ty, AS))
1843 virtual bool isFoldableMemAccessOffset(Instruction *I, int64_t Offset) const {
1847 /// Return true if the specified immediate is legal icmp immediate, that is
1848 /// the target has icmp instructions which can compare a register against the
1849 /// immediate without having to materialize the immediate into a register.
1850 virtual bool isLegalICmpImmediate(int64_t) const {
1854 /// Return true if the specified immediate is legal add immediate, that is the
1855 /// target has add instructions which can add a register with the immediate
1856 /// without having to materialize the immediate into a register.
1857 virtual bool isLegalAddImmediate(int64_t) const {
1861 /// Return true if it's significantly cheaper to shift a vector by a uniform
1862 /// scalar than by an amount which will vary across each lane. On x86, for
1863 /// example, there is a "psllw" instruction for the former case, but no simple
1864 /// instruction for a general "a << b" operation on vectors.
1865 virtual bool isVectorShiftByScalarCheap(Type *Ty) const {
1869 /// Return true if it's free to truncate a value of type FromTy to type
1870 /// ToTy. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
1871 /// by referencing its sub-register AX.
1872 /// Targets must return false when FromTy <= ToTy.
1873 virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const {
1877 /// Return true if a truncation from FromTy to ToTy is permitted when deciding
1878 /// whether a call is in tail position. Typically this means that both results
1879 /// would be assigned to the same register or stack slot, but it could mean
1880 /// the target performs adequate checks of its own before proceeding with the
1881 /// tail call. Targets must return false when FromTy <= ToTy.
1882 virtual bool allowTruncateForTailCall(Type *FromTy, Type *ToTy) const {
1886 virtual bool isTruncateFree(EVT FromVT, EVT ToVT) const {
1890 virtual bool isProfitableToHoist(Instruction *I) const { return true; }
1892 /// Return true if the extension represented by \p I is free.
1893 /// Unlikely the is[Z|FP]ExtFree family which is based on types,
1894 /// this method can use the context provided by \p I to decide
1895 /// whether or not \p I is free.
1896 /// This method extends the behavior of the is[Z|FP]ExtFree family.
1897 /// In other words, if is[Z|FP]Free returns true, then this method
1898 /// returns true as well. The converse is not true.
1899 /// The target can perform the adequate checks by overriding isExtFreeImpl.
1900 /// \pre \p I must be a sign, zero, or fp extension.
1901 bool isExtFree(const Instruction *I) const {
1902 switch (I->getOpcode()) {
1903 case Instruction::FPExt:
1904 if (isFPExtFree(EVT::getEVT(I->getType())))
1907 case Instruction::ZExt:
1908 if (isZExtFree(I->getOperand(0)->getType(), I->getType()))
1911 case Instruction::SExt:
1914 llvm_unreachable("Instruction is not an extension");
1916 return isExtFreeImpl(I);
1919 /// Return true if any actual instruction that defines a value of type FromTy
1920 /// implicitly zero-extends the value to ToTy in the result register.
1922 /// The function should return true when it is likely that the truncate can
1923 /// be freely folded with an instruction defining a value of FromTy. If
1924 /// the defining instruction is unknown (because you're looking at a
1925 /// function argument, PHI, etc.) then the target may require an
1926 /// explicit truncate, which is not necessarily free, but this function
1927 /// does not deal with those cases.
1928 /// Targets must return false when FromTy >= ToTy.
1929 virtual bool isZExtFree(Type *FromTy, Type *ToTy) const {
1933 virtual bool isZExtFree(EVT FromTy, EVT ToTy) const {
1937 /// Return true if the target supplies and combines to a paired load
1938 /// two loaded values of type LoadedType next to each other in memory.
1939 /// RequiredAlignment gives the minimal alignment constraints that must be met
1940 /// to be able to select this paired load.
1942 /// This information is *not* used to generate actual paired loads, but it is
1943 /// used to generate a sequence of loads that is easier to combine into a
1945 /// For instance, something like this:
1946 /// a = load i64* addr
1947 /// b = trunc i64 a to i32
1948 /// c = lshr i64 a, 32
1949 /// d = trunc i64 c to i32
1950 /// will be optimized into:
1951 /// b = load i32* addr1
1952 /// d = load i32* addr2
1953 /// Where addr1 = addr2 +/- sizeof(i32).
1955 /// In other words, unless the target performs a post-isel load combining,
1956 /// this information should not be provided because it will generate more
1958 virtual bool hasPairedLoad(EVT /*LoadedType*/,
1959 unsigned & /*RequiredAligment*/) const {
1963 /// \brief Get the maximum supported factor for interleaved memory accesses.
1964 /// Default to be the minimum interleave factor: 2.
1965 virtual unsigned getMaxSupportedInterleaveFactor() const { return 2; }
1967 /// \brief Lower an interleaved load to target specific intrinsics. Return
1968 /// true on success.
1970 /// \p LI is the vector load instruction.
1971 /// \p Shuffles is the shufflevector list to DE-interleave the loaded vector.
1972 /// \p Indices is the corresponding indices for each shufflevector.
1973 /// \p Factor is the interleave factor.
1974 virtual bool lowerInterleavedLoad(LoadInst *LI,
1975 ArrayRef<ShuffleVectorInst *> Shuffles,
1976 ArrayRef<unsigned> Indices,
1977 unsigned Factor) const {
1981 /// \brief Lower an interleaved store to target specific intrinsics. Return
1982 /// true on success.
1984 /// \p SI is the vector store instruction.
1985 /// \p SVI is the shufflevector to RE-interleave the stored vector.
1986 /// \p Factor is the interleave factor.
1987 virtual bool lowerInterleavedStore(StoreInst *SI, ShuffleVectorInst *SVI,
1988 unsigned Factor) const {
1992 /// Return true if zero-extending the specific node Val to type VT2 is free
1993 /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
1994 /// because it's folded such as X86 zero-extending loads).
1995 virtual bool isZExtFree(SDValue Val, EVT VT2) const {
1996 return isZExtFree(Val.getValueType(), VT2);
1999 /// Return true if an fpext operation is free (for instance, because
2000 /// single-precision floating-point numbers are implicitly extended to
2001 /// double-precision).
2002 virtual bool isFPExtFree(EVT VT) const {
2003 assert(VT.isFloatingPoint());
2007 /// Return true if folding a vector load into ExtVal (a sign, zero, or any
2008 /// extend node) is profitable.
2009 virtual bool isVectorLoadExtDesirable(SDValue ExtVal) const { return false; }
2011 /// Return true if an fneg operation is free to the point where it is never
2012 /// worthwhile to replace it with a bitwise operation.
2013 virtual bool isFNegFree(EVT VT) const {
2014 assert(VT.isFloatingPoint());
2018 /// Return true if an fabs operation is free to the point where it is never
2019 /// worthwhile to replace it with a bitwise operation.
2020 virtual bool isFAbsFree(EVT VT) const {
2021 assert(VT.isFloatingPoint());
2025 /// Return true if an FMA operation is faster than a pair of fmul and fadd
2026 /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
2027 /// returns true, otherwise fmuladd is expanded to fmul + fadd.
2029 /// NOTE: This may be called before legalization on types for which FMAs are
2030 /// not legal, but should return true if those types will eventually legalize
2031 /// to types that support FMAs. After legalization, it will only be called on
2032 /// types that support FMAs (via Legal or Custom actions)
2033 virtual bool isFMAFasterThanFMulAndFAdd(EVT) const {
2037 /// Return true if it's profitable to narrow operations of type VT1 to
2038 /// VT2. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
2040 virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
2044 /// \brief Return true if it is beneficial to convert a load of a constant to
2045 /// just the constant itself.
2046 /// On some targets it might be more efficient to use a combination of
2047 /// arithmetic instructions to materialize the constant instead of loading it
2048 /// from a constant pool.
2049 virtual bool shouldConvertConstantLoadToIntImm(const APInt &Imm,
2054 /// Return true if EXTRACT_SUBVECTOR is cheap for this result type
2055 /// with this index. This is needed because EXTRACT_SUBVECTOR usually
2056 /// has custom lowering that depends on the index of the first element,
2057 /// and only the target knows which lowering is cheap.
2058 virtual bool isExtractSubvectorCheap(EVT ResVT, unsigned Index) const {
2062 // Return true if it is profitable to use a scalar input to a BUILD_VECTOR
2063 // even if the vector itself has multiple uses.
2064 virtual bool aggressivelyPreferBuildVectorSources(EVT VecVT) const {
2068 //===--------------------------------------------------------------------===//
2069 // Runtime Library hooks
2072 /// Rename the default libcall routine name for the specified libcall.
2073 void setLibcallName(RTLIB::Libcall Call, const char *Name) {
2074 LibcallRoutineNames[Call] = Name;
2077 /// Get the libcall routine name for the specified libcall.
2078 const char *getLibcallName(RTLIB::Libcall Call) const {
2079 return LibcallRoutineNames[Call];
2082 /// Override the default CondCode to be used to test the result of the
2083 /// comparison libcall against zero.
2084 void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
2085 CmpLibcallCCs[Call] = CC;
2088 /// Get the CondCode that's to be used to test the result of the comparison
2089 /// libcall against zero.
2090 ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
2091 return CmpLibcallCCs[Call];
2094 /// Set the CallingConv that should be used for the specified libcall.
2095 void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
2096 LibcallCallingConvs[Call] = CC;
2099 /// Get the CallingConv that should be used for the specified libcall.
2100 CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
2101 return LibcallCallingConvs[Call];
2104 /// Execute target specific actions to finalize target lowering.
2105 /// This is used to set extra flags in MachineFrameInformation and freezing
2106 /// the set of reserved registers.
2107 /// The default implementation just freezes the set of reserved registers.
2108 virtual void finalizeLowering(MachineFunction &MF) const;
2111 const TargetMachine &TM;
2113 /// Tells the code generator that the target has multiple (allocatable)
2114 /// condition registers that can be used to store the results of comparisons
2115 /// for use by selects and conditional branches. With multiple condition
2116 /// registers, the code generator will not aggressively sink comparisons into
2117 /// the blocks of their users.
2118 bool HasMultipleConditionRegisters;
2120 /// Tells the code generator that the target has BitExtract instructions.
2121 /// The code generator will aggressively sink "shift"s into the blocks of
2122 /// their users if the users will generate "and" instructions which can be
2123 /// combined with "shift" to BitExtract instructions.
2124 bool HasExtractBitsInsn;
2126 /// Tells the code generator to bypass slow divide or remainder
2127 /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
2128 /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
2129 /// div/rem when the operands are positive and less than 256.
2130 DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
2132 /// Tells the code generator that it shouldn't generate extra flow control
2133 /// instructions and should attempt to combine flow control instructions via
2135 bool JumpIsExpensive;
2137 /// Whether the target supports or cares about preserving floating point
2138 /// exception behavior.
2139 bool HasFloatingPointExceptions;
2141 /// This target prefers to use _setjmp to implement llvm.setjmp.
2143 /// Defaults to false.
2144 bool UseUnderscoreSetJmp;
2146 /// This target prefers to use _longjmp to implement llvm.longjmp.
2148 /// Defaults to false.
2149 bool UseUnderscoreLongJmp;
2151 /// Information about the contents of the high-bits in boolean values held in
2152 /// a type wider than i1. See getBooleanContents.
2153 BooleanContent BooleanContents;
2155 /// Information about the contents of the high-bits in boolean values held in
2156 /// a type wider than i1. See getBooleanContents.
2157 BooleanContent BooleanFloatContents;
2159 /// Information about the contents of the high-bits in boolean vector values
2160 /// when the element type is wider than i1. See getBooleanContents.
2161 BooleanContent BooleanVectorContents;
2163 /// The target scheduling preference: shortest possible total cycles or lowest
2165 Sched::Preference SchedPreferenceInfo;
2167 /// The size, in bytes, of the target's jmp_buf buffers
2168 unsigned JumpBufSize;
2170 /// The alignment, in bytes, of the target's jmp_buf buffers
2171 unsigned JumpBufAlignment;
2173 /// The minimum alignment that any argument on the stack needs to have.
2174 unsigned MinStackArgumentAlignment;
2176 /// The minimum function alignment (used when optimizing for size, and to
2177 /// prevent explicitly provided alignment from leading to incorrect code).
2178 unsigned MinFunctionAlignment;
2180 /// The preferred function alignment (used when alignment unspecified and
2181 /// optimizing for speed).
2182 unsigned PrefFunctionAlignment;
2184 /// The preferred loop alignment.
2185 unsigned PrefLoopAlignment;
2187 /// Size in bits of the maximum atomics size the backend supports.
2188 /// Accesses larger than this will be expanded by AtomicExpandPass.
2189 unsigned MaxAtomicSizeInBitsSupported;
2191 /// Size in bits of the minimum cmpxchg or ll/sc operation the
2192 /// backend supports.
2193 unsigned MinCmpXchgSizeInBits;
2195 /// If set to a physical register, this specifies the register that
2196 /// llvm.savestack/llvm.restorestack should save and restore.
2197 unsigned StackPointerRegisterToSaveRestore;
2199 /// This indicates the default register class to use for each ValueType the
2200 /// target supports natively.
2201 const TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
2202 unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
2203 MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
2205 /// This indicates the "representative" register class to use for each
2206 /// ValueType the target supports natively. This information is used by the
2207 /// scheduler to track register pressure. By default, the representative
2208 /// register class is the largest legal super-reg register class of the
2209 /// register class of the specified type. e.g. On x86, i8, i16, and i32's
2210 /// representative class would be GR32.
2211 const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
2213 /// This indicates the "cost" of the "representative" register class for each
2214 /// ValueType. The cost is used by the scheduler to approximate register
2216 uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
2218 /// For any value types we are promoting or expanding, this contains the value
2219 /// type that we are changing to. For Expanded types, this contains one step
2220 /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
2221 /// (e.g. i64 -> i16). For types natively supported by the system, this holds
2222 /// the same type (e.g. i32 -> i32).
2223 MVT TransformToType[MVT::LAST_VALUETYPE];
2225 /// For each operation and each value type, keep a LegalizeAction that
2226 /// indicates how instruction selection should deal with the operation. Most
2227 /// operations are Legal (aka, supported natively by the target), but
2228 /// operations that are not should be described. Note that operations on
2229 /// non-legal value types are not described here.
2230 LegalizeAction OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END];
2232 /// For each load extension type and each value type, keep a LegalizeAction
2233 /// that indicates how instruction selection should deal with a load of a
2234 /// specific value type and extension type. Uses 4-bits to store the action
2235 /// for each of the 4 load ext types.
2236 uint16_t LoadExtActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
2238 /// For each value type pair keep a LegalizeAction that indicates whether a
2239 /// truncating store of a specific value type and truncating type is legal.
2240 LegalizeAction TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
2242 /// For each indexed mode and each value type, keep a pair of LegalizeAction
2243 /// that indicates how instruction selection should deal with the load /
2246 /// The first dimension is the value_type for the reference. The second
2247 /// dimension represents the various modes for load store.
2248 uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
2250 /// For each condition code (ISD::CondCode) keep a LegalizeAction that
2251 /// indicates how instruction selection should deal with the condition code.
2253 /// Because each CC action takes up 4 bits, we need to have the array size be
2254 /// large enough to fit all of the value types. This can be done by rounding
2255 /// up the MVT::LAST_VALUETYPE value to the next multiple of 8.
2256 uint32_t CondCodeActions[ISD::SETCC_INVALID][(MVT::LAST_VALUETYPE + 7) / 8];
2259 ValueTypeActionImpl ValueTypeActions;
2262 LegalizeKind getTypeConversion(LLVMContext &Context, EVT VT) const;
2264 /// Targets can specify ISD nodes that they would like PerformDAGCombine
2265 /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
2268 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
2270 /// For operations that must be promoted to a specific type, this holds the
2271 /// destination type. This map should be sparse, so don't hold it as an
2274 /// Targets add entries to this map with AddPromotedToType(..), clients access
2275 /// this with getTypeToPromoteTo(..).
2276 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
2279 /// Stores the name each libcall.
2280 const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
2282 /// The ISD::CondCode that should be used to test the result of each of the
2283 /// comparison libcall against zero.
2284 ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
2286 /// Stores the CallingConv that should be used for each libcall.
2287 CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
2290 /// Return true if the extension represented by \p I is free.
2291 /// \pre \p I is a sign, zero, or fp extension and
2292 /// is[Z|FP]ExtFree of the related types is not true.
2293 virtual bool isExtFreeImpl(const Instruction *I) const { return false; }
2295 /// Depth that GatherAllAliases should should continue looking for chain
2296 /// dependencies when trying to find a more preferable chain. As an
2297 /// approximation, this should be more than the number of consecutive stores
2298 /// expected to be merged.
2299 unsigned GatherAllAliasesMaxDepth;
2301 /// \brief Specify maximum number of store instructions per memset call.
2303 /// When lowering \@llvm.memset this field specifies the maximum number of
2304 /// store operations that may be substituted for the call to memset. Targets
2305 /// must set this value based on the cost threshold for that target. Targets
2306 /// should assume that the memset will be done using as many of the largest
2307 /// store operations first, followed by smaller ones, if necessary, per
2308 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
2309 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
2310 /// store. This only applies to setting a constant array of a constant size.
2311 unsigned MaxStoresPerMemset;
2313 /// Maximum number of stores operations that may be substituted for the call
2314 /// to memset, used for functions with OptSize attribute.
2315 unsigned MaxStoresPerMemsetOptSize;
2317 /// \brief Specify maximum bytes of store instructions per memcpy call.
2319 /// When lowering \@llvm.memcpy this field specifies the maximum number of
2320 /// store operations that may be substituted for a call to memcpy. Targets
2321 /// must set this value based on the cost threshold for that target. Targets
2322 /// should assume that the memcpy will be done using as many of the largest
2323 /// store operations first, followed by smaller ones, if necessary, per
2324 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
2325 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
2326 /// and one 1-byte store. This only applies to copying a constant array of
2328 unsigned MaxStoresPerMemcpy;
2330 /// Maximum number of store operations that may be substituted for a call to
2331 /// memcpy, used for functions with OptSize attribute.
2332 unsigned MaxStoresPerMemcpyOptSize;
2334 /// \brief Specify maximum bytes of store instructions per memmove call.
2336 /// When lowering \@llvm.memmove this field specifies the maximum number of
2337 /// store instructions that may be substituted for a call to memmove. Targets
2338 /// must set this value based on the cost threshold for that target. Targets
2339 /// should assume that the memmove will be done using as many of the largest
2340 /// store operations first, followed by smaller ones, if necessary, per
2341 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
2342 /// with 8-bit alignment would result in nine 1-byte stores. This only
2343 /// applies to copying a constant array of constant size.
2344 unsigned MaxStoresPerMemmove;
2346 /// Maximum number of store instructions that may be substituted for a call to
2347 /// memmove, used for functions with OptSize attribute.
2348 unsigned MaxStoresPerMemmoveOptSize;
2350 /// Tells the code generator that select is more expensive than a branch if
2351 /// the branch is usually predicted right.
2352 bool PredictableSelectIsExpensive;
2354 /// \see enableExtLdPromotion.
2355 bool EnableExtLdPromotion;
2357 /// Return true if the value types that can be represented by the specified
2358 /// register class are all legal.
2359 bool isLegalRC(const TargetRegisterInfo &TRI,
2360 const TargetRegisterClass &RC) const;
2362 /// Replace/modify any TargetFrameIndex operands with a targte-dependent
2363 /// sequence of memory operands that is recognized by PrologEpilogInserter.
2364 MachineBasicBlock *emitPatchPoint(MachineInstr &MI,
2365 MachineBasicBlock *MBB) const;
2368 /// This class defines information used to lower LLVM code to legal SelectionDAG
2369 /// operators that the target instruction selector can accept natively.
2371 /// This class also defines callbacks that targets must implement to lower
2372 /// target-specific constructs to SelectionDAG operators.
2373 class TargetLowering : public TargetLoweringBase {
2375 struct DAGCombinerInfo;
2377 TargetLowering(const TargetLowering&) = delete;
2378 void operator=(const TargetLowering&) = delete;
2380 /// NOTE: The TargetMachine owns TLOF.
2381 explicit TargetLowering(const TargetMachine &TM);
2383 bool isPositionIndependent() const;
2385 /// Returns true by value, base pointer and offset pointer and addressing mode
2386 /// by reference if the node's address can be legally represented as
2387 /// pre-indexed load / store address.
2388 virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
2389 SDValue &/*Offset*/,
2390 ISD::MemIndexedMode &/*AM*/,
2391 SelectionDAG &/*DAG*/) const {
2395 /// Returns true by value, base pointer and offset pointer and addressing mode
2396 /// by reference if this node can be combined with a load / store to form a
2397 /// post-indexed load / store.
2398 virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
2400 SDValue &/*Offset*/,
2401 ISD::MemIndexedMode &/*AM*/,
2402 SelectionDAG &/*DAG*/) const {
2406 /// Return the entry encoding for a jump table in the current function. The
2407 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
2408 virtual unsigned getJumpTableEncoding() const;
2410 virtual const MCExpr *
2411 LowerCustomJumpTableEntry(const MachineJumpTableInfo * /*MJTI*/,
2412 const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
2413 MCContext &/*Ctx*/) const {
2414 llvm_unreachable("Need to implement this hook if target has custom JTIs");
2417 /// Returns relocation base for the given PIC jumptable.
2418 virtual SDValue getPICJumpTableRelocBase(SDValue Table,
2419 SelectionDAG &DAG) const;
2421 /// This returns the relocation base for the given PIC jumptable, the same as
2422 /// getPICJumpTableRelocBase, but as an MCExpr.
2423 virtual const MCExpr *
2424 getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2425 unsigned JTI, MCContext &Ctx) const;
2427 /// Return true if folding a constant offset with the given GlobalAddress is
2428 /// legal. It is frequently not legal in PIC relocation models.
2429 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
2431 bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
2432 SDValue &Chain) const;
2434 void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
2435 SDValue &NewRHS, ISD::CondCode &CCCode,
2436 const SDLoc &DL) const;
2438 /// Returns a pair of (return value, chain).
2439 /// It is an error to pass RTLIB::UNKNOWN_LIBCALL as \p LC.
2440 std::pair<SDValue, SDValue> makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC,
2441 EVT RetVT, ArrayRef<SDValue> Ops,
2442 bool isSigned, const SDLoc &dl,
2443 bool doesNotReturn = false,
2444 bool isReturnValueUsed = true) const;
2446 /// Check whether parameters to a call that are passed in callee saved
2447 /// registers are the same as from the calling function. This needs to be
2448 /// checked for tail call eligibility.
2449 bool parametersInCSRMatch(const MachineRegisterInfo &MRI,
2450 const uint32_t *CallerPreservedMask,
2451 const SmallVectorImpl<CCValAssign> &ArgLocs,
2452 const SmallVectorImpl<SDValue> &OutVals) const;
2454 //===--------------------------------------------------------------------===//
2455 // TargetLowering Optimization Methods
2458 /// A convenience struct that encapsulates a DAG, and two SDValues for
2459 /// returning information from TargetLowering to its clients that want to
2461 struct TargetLoweringOpt {
2468 explicit TargetLoweringOpt(SelectionDAG &InDAG,
2470 DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
2472 bool LegalTypes() const { return LegalTys; }
2473 bool LegalOperations() const { return LegalOps; }
2475 bool CombineTo(SDValue O, SDValue N) {
2482 /// Check to see if the specified operand of the specified instruction is a
2483 /// constant integer. If so, check to see if there are any bits set in the
2484 /// constant that are not demanded. If so, shrink the constant and return
2486 bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded,
2487 TargetLoweringOpt &TLO) const;
2489 // Target hook to do target-specific const optimization, which is called by
2490 // ShrinkDemandedConstant. This function should return true if the target
2491 // doesn't want ShrinkDemandedConstant to further optimize the constant.
2492 virtual bool targetShrinkDemandedConstant(SDValue Op, const APInt &Demanded,
2493 TargetLoweringOpt &TLO) const {
2497 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. This
2498 /// uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
2499 /// generalized for targets with other types of implicit widening casts.
2500 bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
2501 TargetLoweringOpt &TLO) const;
2503 /// Helper for SimplifyDemandedBits that can simplify an operation with
2504 /// multiple uses. This function simplifies operand \p OpIdx of \p User and
2505 /// then updates \p User with the simplified version. No other uses of
2506 /// \p OpIdx are updated. If \p User is the only user of \p OpIdx, this
2507 /// function behaves exactly like function SimplifyDemandedBits declared
2508 /// below except that it also updates the DAG by calling
2509 /// DCI.CommitTargetLoweringOpt.
2510 bool SimplifyDemandedBits(SDNode *User, unsigned OpIdx, const APInt &Demanded,
2511 DAGCombinerInfo &DCI, TargetLoweringOpt &TLO) const;
2513 /// Look at Op. At this point, we know that only the DemandedMask bits of the
2514 /// result of Op are ever used downstream. If we can use this information to
2515 /// simplify Op, create a new simplified DAG node and return true, returning
2516 /// the original and new nodes in Old and New. Otherwise, analyze the
2517 /// expression and return a mask of KnownOne and KnownZero bits for the
2518 /// expression (used to simplify the caller). The KnownZero/One bits may only
2519 /// be accurate for those bits in the DemandedMask.
2520 /// \p AssumeSingleUse When this parameter is true, this function will
2521 /// attempt to simplify \p Op even if there are multiple uses.
2522 /// Callers are responsible for correctly updating the DAG based on the
2523 /// results of this function, because simply replacing replacing TLO.Old
2524 /// with TLO.New will be incorrect when this parameter is true and TLO.Old
2525 /// has multiple uses.
2526 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
2528 TargetLoweringOpt &TLO,
2530 bool AssumeSingleUse = false) const;
2532 /// Helper wrapper around SimplifyDemandedBits
2533 bool SimplifyDemandedBits(SDValue Op, APInt &DemandedMask,
2534 DAGCombinerInfo &DCI) const;
2536 /// Determine which of the bits specified in Mask are known to be either zero
2537 /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
2538 /// argument allows us to only collect the known bits that are shared by the
2539 /// requested vector elements.
2540 virtual void computeKnownBitsForTargetNode(const SDValue Op,
2542 const APInt &DemandedElts,
2543 const SelectionDAG &DAG,
2544 unsigned Depth = 0) const;
2546 /// This method can be implemented by targets that want to expose additional
2547 /// information about sign bits to the DAG Combiner. The DemandedElts
2548 /// argument allows us to only collect the minimum sign bits that are shared
2549 /// by the requested vector elements.
2550 virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
2551 const APInt &DemandedElts,
2552 const SelectionDAG &DAG,
2553 unsigned Depth = 0) const;
2555 struct DAGCombinerInfo {
2556 void *DC; // The DAG Combiner object.
2558 bool CalledByLegalizer;
2563 DAGCombinerInfo(SelectionDAG &dag, CombineLevel level, bool cl, void *dc)
2564 : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
2566 bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
2567 bool isBeforeLegalizeOps() const { return Level < AfterLegalizeVectorOps; }
2568 bool isAfterLegalizeVectorOps() const {
2569 return Level == AfterLegalizeDAG;
2571 CombineLevel getDAGCombineLevel() { return Level; }
2572 bool isCalledByLegalizer() const { return CalledByLegalizer; }
2574 void AddToWorklist(SDNode *N);
2575 SDValue CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo = true);
2576 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
2577 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
2579 void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
2582 /// Return if the N is a constant or constant vector equal to the true value
2583 /// from getBooleanContents().
2584 bool isConstTrueVal(const SDNode *N) const;
2586 /// Return if the N is a constant or constant vector equal to the false value
2587 /// from getBooleanContents().
2588 bool isConstFalseVal(const SDNode *N) const;
2590 /// Return a constant of type VT that contains a true value that respects
2591 /// getBooleanContents()
2592 SDValue getConstTrueVal(SelectionDAG &DAG, EVT VT, const SDLoc &DL) const;
2594 /// Return if \p N is a True value when extended to \p VT.
2595 bool isExtendedTrueVal(const ConstantSDNode *N, EVT VT, bool Signed) const;
2597 /// Try to simplify a setcc built with the specified operands and cc. If it is
2598 /// unable to simplify it, return a null SDValue.
2599 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
2600 bool foldBooleans, DAGCombinerInfo &DCI,
2601 const SDLoc &dl) const;
2603 /// Returns true (and the GlobalValue and the offset) if the node is a
2604 /// GlobalAddress + offset.
2606 isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
2608 /// This method will be invoked for all target nodes and for any
2609 /// target-independent nodes that the target has registered with invoke it
2612 /// The semantics are as follows:
2614 /// SDValue.Val == 0 - No change was made
2615 /// SDValue.Val == N - N was replaced, is dead, and is already handled.
2616 /// otherwise - N should be replaced by the returned Operand.
2618 /// In addition, methods provided by DAGCombinerInfo may be used to perform
2619 /// more complex transformations.
2621 virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
2623 /// Return true if it is profitable to move a following shift through this
2624 // node, adjusting any immediate operands as necessary to preserve semantics.
2625 // This transformation may not be desirable if it disrupts a particularly
2626 // auspicious target-specific tree (e.g. bitfield extraction in AArch64).
2627 // By default, it returns true.
2628 virtual bool isDesirableToCommuteWithShift(const SDNode *N /*Op*/) const {
2632 /// Return true if the target has native support for the specified value type
2633 /// and it is 'desirable' to use the type for the given node type. e.g. On x86
2634 /// i16 is legal, but undesirable since i16 instruction encodings are longer
2635 /// and some i16 instructions are slow.
2636 virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
2637 // By default, assume all legal types are desirable.
2638 return isTypeLegal(VT);
2641 /// Return true if it is profitable for dag combiner to transform a floating
2642 /// point op of specified opcode to a equivalent op of an integer
2643 /// type. e.g. f32 load -> i32 load can be profitable on ARM.
2644 virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
2649 /// This method query the target whether it is beneficial for dag combiner to
2650 /// promote the specified node. If true, it should return the desired
2651 /// promotion type by reference.
2652 virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
2656 /// Return true if the target supports swifterror attribute. It optimizes
2657 /// loads and stores to reading and writing a specific register.
2658 virtual bool supportSwiftError() const {
2662 /// Return true if the target supports that a subset of CSRs for the given
2663 /// machine function is handled explicitly via copies.
2664 virtual bool supportSplitCSR(MachineFunction *MF) const {
2668 /// Perform necessary initialization to handle a subset of CSRs explicitly
2669 /// via copies. This function is called at the beginning of instruction
2671 virtual void initializeSplitCSR(MachineBasicBlock *Entry) const {
2672 llvm_unreachable("Not Implemented");
2675 /// Insert explicit copies in entry and exit blocks. We copy a subset of
2676 /// CSRs to virtual registers in the entry block, and copy them back to
2677 /// physical registers in the exit blocks. This function is called at the end
2678 /// of instruction selection.
2679 virtual void insertCopiesSplitCSR(
2680 MachineBasicBlock *Entry,
2681 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2682 llvm_unreachable("Not Implemented");
2685 //===--------------------------------------------------------------------===//
2686 // Lowering methods - These methods must be implemented by targets so that
2687 // the SelectionDAGBuilder code knows how to lower these.
2690 /// This hook must be implemented to lower the incoming (formal) arguments,
2691 /// described by the Ins array, into the specified DAG. The implementation
2692 /// should fill in the InVals array with legal-type argument values, and
2693 /// return the resulting token chain value.
2695 virtual SDValue LowerFormalArguments(
2696 SDValue /*Chain*/, CallingConv::ID /*CallConv*/, bool /*isVarArg*/,
2697 const SmallVectorImpl<ISD::InputArg> & /*Ins*/, const SDLoc & /*dl*/,
2698 SelectionDAG & /*DAG*/, SmallVectorImpl<SDValue> & /*InVals*/) const {
2699 llvm_unreachable("Not Implemented");
2702 /// This structure contains all information that is necessary for lowering
2703 /// calls. It is passed to TLI::LowerCallTo when the SelectionDAG builder
2704 /// needs to lower a call, and targets will see this struct in their LowerCall
2706 struct CallLoweringInfo {
2713 bool DoesNotReturn : 1;
2714 bool IsReturnValueUsed : 1;
2715 bool IsConvergent : 1;
2717 // IsTailCall should be modified by implementations of
2718 // TargetLowering::LowerCall that perform tail call conversions.
2721 unsigned NumFixedArgs;
2722 CallingConv::ID CallConv;
2727 ImmutableCallSite *CS;
2729 SmallVector<ISD::OutputArg, 32> Outs;
2730 SmallVector<SDValue, 32> OutVals;
2731 SmallVector<ISD::InputArg, 32> Ins;
2732 SmallVector<SDValue, 4> InVals;
2734 CallLoweringInfo(SelectionDAG &DAG)
2735 : RetTy(nullptr), RetSExt(false), RetZExt(false), IsVarArg(false),
2736 IsInReg(false), DoesNotReturn(false), IsReturnValueUsed(true),
2737 IsConvergent(false), IsTailCall(false), NumFixedArgs(-1),
2738 CallConv(CallingConv::C), DAG(DAG), CS(nullptr), IsPatchPoint(false) {
2741 CallLoweringInfo &setDebugLoc(const SDLoc &dl) {
2746 CallLoweringInfo &setChain(SDValue InChain) {
2751 // setCallee with target/module-specific attributes
2752 CallLoweringInfo &setLibCallee(CallingConv::ID CC, Type *ResultType,
2753 SDValue Target, ArgListTy &&ArgsList) {
2757 NumFixedArgs = Args.size();
2758 Args = std::move(ArgsList);
2760 DAG.getTargetLoweringInfo().markLibCallAttributes(
2761 &(DAG.getMachineFunction()), CC, Args);
2765 CallLoweringInfo &setCallee(CallingConv::ID CC, Type *ResultType,
2766 SDValue Target, ArgListTy &&ArgsList) {
2770 NumFixedArgs = Args.size();
2771 Args = std::move(ArgsList);
2775 CallLoweringInfo &setCallee(Type *ResultType, FunctionType *FTy,
2776 SDValue Target, ArgListTy &&ArgsList,
2777 ImmutableCallSite &Call) {
2780 IsInReg = Call.hasRetAttr(Attribute::InReg);
2782 Call.doesNotReturn() ||
2783 (!Call.isInvoke() &&
2784 isa<UnreachableInst>(Call.getInstruction()->getNextNode()));
2785 IsVarArg = FTy->isVarArg();
2786 IsReturnValueUsed = !Call.getInstruction()->use_empty();
2787 RetSExt = Call.hasRetAttr(Attribute::SExt);
2788 RetZExt = Call.hasRetAttr(Attribute::ZExt);
2792 CallConv = Call.getCallingConv();
2793 NumFixedArgs = FTy->getNumParams();
2794 Args = std::move(ArgsList);
2801 CallLoweringInfo &setInRegister(bool Value = true) {
2806 CallLoweringInfo &setNoReturn(bool Value = true) {
2807 DoesNotReturn = Value;
2811 CallLoweringInfo &setVarArg(bool Value = true) {
2816 CallLoweringInfo &setTailCall(bool Value = true) {
2821 CallLoweringInfo &setDiscardResult(bool Value = true) {
2822 IsReturnValueUsed = !Value;
2826 CallLoweringInfo &setConvergent(bool Value = true) {
2827 IsConvergent = Value;
2831 CallLoweringInfo &setSExtResult(bool Value = true) {
2836 CallLoweringInfo &setZExtResult(bool Value = true) {
2841 CallLoweringInfo &setIsPatchPoint(bool Value = true) {
2842 IsPatchPoint = Value;
2846 ArgListTy &getArgs() {
2851 /// This function lowers an abstract call to a function into an actual call.
2852 /// This returns a pair of operands. The first element is the return value
2853 /// for the function (if RetTy is not VoidTy). The second element is the
2854 /// outgoing token chain. It calls LowerCall to do the actual lowering.
2855 std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
2857 /// This hook must be implemented to lower calls into the specified
2858 /// DAG. The outgoing arguments to the call are described by the Outs array,
2859 /// and the values to be returned by the call are described by the Ins
2860 /// array. The implementation should fill in the InVals array with legal-type
2861 /// return values from the call, and return the resulting token chain value.
2863 LowerCall(CallLoweringInfo &/*CLI*/,
2864 SmallVectorImpl<SDValue> &/*InVals*/) const {
2865 llvm_unreachable("Not Implemented");
2868 /// Target-specific cleanup for formal ByVal parameters.
2869 virtual void HandleByVal(CCState *, unsigned &, unsigned) const {}
2871 /// This hook should be implemented to check whether the return values
2872 /// described by the Outs array can fit into the return registers. If false
2873 /// is returned, an sret-demotion is performed.
2874 virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
2875 MachineFunction &/*MF*/, bool /*isVarArg*/,
2876 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
2877 LLVMContext &/*Context*/) const
2879 // Return true by default to get preexisting behavior.
2883 /// This hook must be implemented to lower outgoing return values, described
2884 /// by the Outs array, into the specified DAG. The implementation should
2885 /// return the resulting token chain value.
2886 virtual SDValue LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
2888 const SmallVectorImpl<ISD::OutputArg> & /*Outs*/,
2889 const SmallVectorImpl<SDValue> & /*OutVals*/,
2890 const SDLoc & /*dl*/,
2891 SelectionDAG & /*DAG*/) const {
2892 llvm_unreachable("Not Implemented");
2895 /// Return true if result of the specified node is used by a return node
2896 /// only. It also compute and return the input chain for the tail call.
2898 /// This is used to determine whether it is possible to codegen a libcall as
2899 /// tail call at legalization time.
2900 virtual bool isUsedByReturnOnly(SDNode *, SDValue &/*Chain*/) const {
2904 /// Return true if the target may be able emit the call instruction as a tail
2905 /// call. This is used by optimization passes to determine if it's profitable
2906 /// to duplicate return instructions to enable tailcall optimization.
2907 virtual bool mayBeEmittedAsTailCall(const CallInst *) const {
2911 /// Return the builtin name for the __builtin___clear_cache intrinsic
2912 /// Default is to invoke the clear cache library call
2913 virtual const char * getClearCacheBuiltinName() const {
2914 return "__clear_cache";
2917 /// Return the register ID of the name passed in. Used by named register
2918 /// global variables extension. There is no target-independent behaviour
2919 /// so the default action is to bail.
2920 virtual unsigned getRegisterByName(const char* RegName, EVT VT,
2921 SelectionDAG &DAG) const {
2922 report_fatal_error("Named registers not implemented for this target");
2925 /// Return the type that should be used to zero or sign extend a
2926 /// zeroext/signext integer return value. FIXME: Some C calling conventions
2927 /// require the return type to be promoted, but this is not true all the time,
2928 /// e.g. i1/i8/i16 on x86/x86_64. It is also not necessary for non-C calling
2929 /// conventions. The frontend should handle this and include all of the
2930 /// necessary information.
2931 virtual EVT getTypeForExtReturn(LLVMContext &Context, EVT VT,
2932 ISD::NodeType /*ExtendKind*/) const {
2933 EVT MinVT = getRegisterType(Context, MVT::i32);
2934 return VT.bitsLT(MinVT) ? MinVT : VT;
2937 /// For some targets, an LLVM struct type must be broken down into multiple
2938 /// simple types, but the calling convention specifies that the entire struct
2939 /// must be passed in a block of consecutive registers.
2941 functionArgumentNeedsConsecutiveRegisters(Type *Ty, CallingConv::ID CallConv,
2942 bool isVarArg) const {
2946 /// Returns a 0 terminated array of registers that can be safely used as
2947 /// scratch registers.
2948 virtual const MCPhysReg *getScratchRegisters(CallingConv::ID CC) const {
2952 /// This callback is used to prepare for a volatile or atomic load.
2953 /// It takes a chain node as input and returns the chain for the load itself.
2955 /// Having a callback like this is necessary for targets like SystemZ,
2956 /// which allows a CPU to reuse the result of a previous load indefinitely,
2957 /// even if a cache-coherent store is performed by another CPU. The default
2958 /// implementation does nothing.
2959 virtual SDValue prepareVolatileOrAtomicLoad(SDValue Chain, const SDLoc &DL,
2960 SelectionDAG &DAG) const {
2964 /// This callback is invoked by the type legalizer to legalize nodes with an
2965 /// illegal operand type but legal result types. It replaces the
2966 /// LowerOperation callback in the type Legalizer. The reason we can not do
2967 /// away with LowerOperation entirely is that LegalizeDAG isn't yet ready to
2968 /// use this callback.
2970 /// TODO: Consider merging with ReplaceNodeResults.
2972 /// The target places new result values for the node in Results (their number
2973 /// and types must exactly match those of the original return values of
2974 /// the node), or leaves Results empty, which indicates that the node is not
2975 /// to be custom lowered after all.
2976 /// The default implementation calls LowerOperation.
2977 virtual void LowerOperationWrapper(SDNode *N,
2978 SmallVectorImpl<SDValue> &Results,
2979 SelectionDAG &DAG) const;
2981 /// This callback is invoked for operations that are unsupported by the
2982 /// target, which are registered to use 'custom' lowering, and whose defined
2983 /// values are all legal. If the target has no operations that require custom
2984 /// lowering, it need not implement this. The default implementation of this
2986 virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
2988 /// This callback is invoked when a node result type is illegal for the
2989 /// target, and the operation was registered to use 'custom' lowering for that
2990 /// result type. The target places new result values for the node in Results
2991 /// (their number and types must exactly match those of the original return
2992 /// values of the node), or leaves Results empty, which indicates that the
2993 /// node is not to be custom lowered after all.
2995 /// If the target has no operations that require custom lowering, it need not
2996 /// implement this. The default implementation aborts.
2997 virtual void ReplaceNodeResults(SDNode * /*N*/,
2998 SmallVectorImpl<SDValue> &/*Results*/,
2999 SelectionDAG &/*DAG*/) const {
3000 llvm_unreachable("ReplaceNodeResults not implemented for this target!");
3003 /// This method returns the name of a target specific DAG node.
3004 virtual const char *getTargetNodeName(unsigned Opcode) const;
3006 /// This method returns a target specific FastISel object, or null if the
3007 /// target does not support "fast" ISel.
3008 virtual FastISel *createFastISel(FunctionLoweringInfo &,
3009 const TargetLibraryInfo *) const {
3014 bool verifyReturnAddressArgumentIsConstant(SDValue Op,
3015 SelectionDAG &DAG) const;
3017 //===--------------------------------------------------------------------===//
3018 // Inline Asm Support hooks
3021 /// This hook allows the target to expand an inline asm call to be explicit
3022 /// llvm code if it wants to. This is useful for turning simple inline asms
3023 /// into LLVM intrinsics, which gives the compiler more information about the
3024 /// behavior of the code.
3025 virtual bool ExpandInlineAsm(CallInst *) const {
3029 enum ConstraintType {
3030 C_Register, // Constraint represents specific register(s).
3031 C_RegisterClass, // Constraint represents any of register(s) in class.
3032 C_Memory, // Memory constraint.
3033 C_Other, // Something else.
3034 C_Unknown // Unsupported constraint.
3037 enum ConstraintWeight {
3039 CW_Invalid = -1, // No match.
3040 CW_Okay = 0, // Acceptable.
3041 CW_Good = 1, // Good weight.
3042 CW_Better = 2, // Better weight.
3043 CW_Best = 3, // Best weight.
3045 // Well-known weights.
3046 CW_SpecificReg = CW_Okay, // Specific register operands.
3047 CW_Register = CW_Good, // Register operands.
3048 CW_Memory = CW_Better, // Memory operands.
3049 CW_Constant = CW_Best, // Constant operand.
3050 CW_Default = CW_Okay // Default or don't know type.
3053 /// This contains information for each constraint that we are lowering.
3054 struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
3055 /// This contains the actual string for the code, like "m". TargetLowering
3056 /// picks the 'best' code from ConstraintInfo::Codes that most closely
3057 /// matches the operand.
3058 std::string ConstraintCode;
3060 /// Information about the constraint code, e.g. Register, RegisterClass,
3061 /// Memory, Other, Unknown.
3062 TargetLowering::ConstraintType ConstraintType;
3064 /// If this is the result output operand or a clobber, this is null,
3065 /// otherwise it is the incoming operand to the CallInst. This gets
3066 /// modified as the asm is processed.
3067 Value *CallOperandVal;
3069 /// The ValueType for the operand value.
3072 /// Return true of this is an input operand that is a matching constraint
3074 bool isMatchingInputConstraint() const;
3076 /// If this is an input matching constraint, this method returns the output
3077 /// operand it matches.
3078 unsigned getMatchedOperand() const;
3080 /// Copy constructor for copying from a ConstraintInfo.
3081 AsmOperandInfo(InlineAsm::ConstraintInfo Info)
3082 : InlineAsm::ConstraintInfo(std::move(Info)),
3083 ConstraintType(TargetLowering::C_Unknown), CallOperandVal(nullptr),
3084 ConstraintVT(MVT::Other) {}
3087 typedef std::vector<AsmOperandInfo> AsmOperandInfoVector;
3089 /// Split up the constraint string from the inline assembly value into the
3090 /// specific constraints and their prefixes, and also tie in the associated
3091 /// operand values. If this returns an empty vector, and if the constraint
3092 /// string itself isn't empty, there was an error parsing.
3093 virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL,
3094 const TargetRegisterInfo *TRI,
3095 ImmutableCallSite CS) const;
3097 /// Examine constraint type and operand type and determine a weight value.
3098 /// The operand object must already have been set up with the operand type.
3099 virtual ConstraintWeight getMultipleConstraintMatchWeight(
3100 AsmOperandInfo &info, int maIndex) const;
3102 /// Examine constraint string and operand type and determine a weight value.
3103 /// The operand object must already have been set up with the operand type.
3104 virtual ConstraintWeight getSingleConstraintMatchWeight(
3105 AsmOperandInfo &info, const char *constraint) const;
3107 /// Determines the constraint code and constraint type to use for the specific
3108 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
3109 /// If the actual operand being passed in is available, it can be passed in as
3110 /// Op, otherwise an empty SDValue can be passed.
3111 virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
3113 SelectionDAG *DAG = nullptr) const;
3115 /// Given a constraint, return the type of constraint it is for this target.
3116 virtual ConstraintType getConstraintType(StringRef Constraint) const;
3118 /// Given a physical register constraint (e.g. {edx}), return the register
3119 /// number and the register class for the register.
3121 /// Given a register class constraint, like 'r', if this corresponds directly
3122 /// to an LLVM register class, return a register of 0 and the register class
3125 /// This should only be used for C_Register constraints. On error, this
3126 /// returns a register number of 0 and a null register class pointer.
3127 virtual std::pair<unsigned, const TargetRegisterClass *>
3128 getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
3129 StringRef Constraint, MVT VT) const;
3131 virtual unsigned getInlineAsmMemConstraint(StringRef ConstraintCode) const {
3132 if (ConstraintCode == "i")
3133 return InlineAsm::Constraint_i;
3134 else if (ConstraintCode == "m")
3135 return InlineAsm::Constraint_m;
3136 return InlineAsm::Constraint_Unknown;
3139 /// Try to replace an X constraint, which matches anything, with another that
3140 /// has more specific requirements based on the type of the corresponding
3141 /// operand. This returns null if there is no replacement to make.
3142 virtual const char *LowerXConstraint(EVT ConstraintVT) const;
3144 /// Lower the specified operand into the Ops vector. If it is invalid, don't
3145 /// add anything to Ops.
3146 virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
3147 std::vector<SDValue> &Ops,
3148 SelectionDAG &DAG) const;
3150 //===--------------------------------------------------------------------===//
3151 // Div utility functions
3153 SDValue BuildSDIV(SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
3154 bool IsAfterLegalization,
3155 std::vector<SDNode *> *Created) const;
3156 SDValue BuildUDIV(SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
3157 bool IsAfterLegalization,
3158 std::vector<SDNode *> *Created) const;
3160 /// Targets may override this function to provide custom SDIV lowering for
3161 /// power-of-2 denominators. If the target returns an empty SDValue, LLVM
3162 /// assumes SDIV is expensive and replaces it with a series of other integer
3164 virtual SDValue BuildSDIVPow2(SDNode *N, const APInt &Divisor,
3166 std::vector<SDNode *> *Created) const;
3168 /// Indicate whether this target prefers to combine FDIVs with the same
3169 /// divisor. If the transform should never be done, return zero. If the
3170 /// transform should be done, return the minimum number of divisor uses
3171 /// that must exist.
3172 virtual unsigned combineRepeatedFPDivisors() const {
3176 /// Hooks for building estimates in place of slower divisions and square
3179 /// Return either a square root or its reciprocal estimate value for the input
3181 /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
3182 /// 'Enabled' as set by a potential default override attribute.
3183 /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
3184 /// refinement iterations required to generate a sufficient (though not
3185 /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
3186 /// The boolean UseOneConstNR output is used to select a Newton-Raphson
3187 /// algorithm implementation that uses either one or two constants.
3188 /// The boolean Reciprocal is used to select whether the estimate is for the
3189 /// square root of the input operand or the reciprocal of its square root.
3190 /// A target may choose to implement its own refinement within this function.
3191 /// If that's true, then return '0' as the number of RefinementSteps to avoid
3192 /// any further refinement of the estimate.
3193 /// An empty SDValue return means no estimate sequence can be created.
3194 virtual SDValue getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
3195 int Enabled, int &RefinementSteps,
3196 bool &UseOneConstNR, bool Reciprocal) const {
3200 /// Return a reciprocal estimate value for the input operand.
3201 /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
3202 /// 'Enabled' as set by a potential default override attribute.
3203 /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
3204 /// refinement iterations required to generate a sufficient (though not
3205 /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
3206 /// A target may choose to implement its own refinement within this function.
3207 /// If that's true, then return '0' as the number of RefinementSteps to avoid
3208 /// any further refinement of the estimate.
3209 /// An empty SDValue return means no estimate sequence can be created.
3210 virtual SDValue getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
3211 int Enabled, int &RefinementSteps) const {
3215 //===--------------------------------------------------------------------===//
3216 // Legalization utility functions
3219 /// Expand a MUL or [US]MUL_LOHI of n-bit values into two or four nodes,
3220 /// respectively, each computing an n/2-bit part of the result.
3221 /// \param Result A vector that will be filled with the parts of the result
3222 /// in little-endian order.
3223 /// \param LL Low bits of the LHS of the MUL. You can use this parameter
3224 /// if you want to control how low bits are extracted from the LHS.
3225 /// \param LH High bits of the LHS of the MUL. See LL for meaning.
3226 /// \param RL Low bits of the RHS of the MUL. See LL for meaning
3227 /// \param RH High bits of the RHS of the MUL. See LL for meaning.
3228 /// \returns true if the node has been expanded, false if it has not
3229 bool expandMUL_LOHI(unsigned Opcode, EVT VT, SDLoc dl, SDValue LHS,
3230 SDValue RHS, SmallVectorImpl<SDValue> &Result, EVT HiLoVT,
3231 SelectionDAG &DAG, MulExpansionKind Kind,
3232 SDValue LL = SDValue(), SDValue LH = SDValue(),
3233 SDValue RL = SDValue(), SDValue RH = SDValue()) const;
3235 /// Expand a MUL into two nodes. One that computes the high bits of
3236 /// the result and one that computes the low bits.
3237 /// \param HiLoVT The value type to use for the Lo and Hi nodes.
3238 /// \param LL Low bits of the LHS of the MUL. You can use this parameter
3239 /// if you want to control how low bits are extracted from the LHS.
3240 /// \param LH High bits of the LHS of the MUL. See LL for meaning.
3241 /// \param RL Low bits of the RHS of the MUL. See LL for meaning
3242 /// \param RH High bits of the RHS of the MUL. See LL for meaning.
3243 /// \returns true if the node has been expanded. false if it has not
3244 bool expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
3245 SelectionDAG &DAG, MulExpansionKind Kind,
3246 SDValue LL = SDValue(), SDValue LH = SDValue(),
3247 SDValue RL = SDValue(), SDValue RH = SDValue()) const;
3249 /// Expand float(f32) to SINT(i64) conversion
3250 /// \param N Node to expand
3251 /// \param Result output after conversion
3252 /// \returns True, if the expansion was successful, false otherwise
3253 bool expandFP_TO_SINT(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
3255 /// Turn load of vector type into a load of the individual elements.
3256 /// \param LD load to expand
3257 /// \returns MERGE_VALUEs of the scalar loads with their chains.
3258 SDValue scalarizeVectorLoad(LoadSDNode *LD, SelectionDAG &DAG) const;
3260 // Turn a store of a vector type into stores of the individual elements.
3261 /// \param ST Store with a vector value type
3262 /// \returns MERGE_VALUs of the individual store chains.
3263 SDValue scalarizeVectorStore(StoreSDNode *ST, SelectionDAG &DAG) const;
3265 /// Expands an unaligned load to 2 half-size loads for an integer, and
3266 /// possibly more for vectors.
3267 std::pair<SDValue, SDValue> expandUnalignedLoad(LoadSDNode *LD,
3268 SelectionDAG &DAG) const;
3270 /// Expands an unaligned store to 2 half-size stores for integer values, and
3271 /// possibly more for vectors.
3272 SDValue expandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG) const;
3274 /// Increments memory address \p Addr according to the type of the value
3275 /// \p DataVT that should be stored. If the data is stored in compressed
3276 /// form, the memory address should be incremented according to the number of
3277 /// the stored elements. This number is equal to the number of '1's bits
3279 /// \p DataVT is a vector type. \p Mask is a vector value.
3280 /// \p DataVT and \p Mask have the same number of vector elements.
3281 SDValue IncrementMemoryAddress(SDValue Addr, SDValue Mask, const SDLoc &DL,
3282 EVT DataVT, SelectionDAG &DAG,
3283 bool IsCompressedMemory) const;
3285 /// Get a pointer to vector element \p Idx located in memory for a vector of
3286 /// type \p VecVT starting at a base address of \p VecPtr. If \p Idx is out of
3287 /// bounds the returned pointer is unspecified, but will be within the vector
3289 SDValue getVectorElementPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT,
3292 //===--------------------------------------------------------------------===//
3293 // Instruction Emitting Hooks
3296 /// This method should be implemented by targets that mark instructions with
3297 /// the 'usesCustomInserter' flag. These instructions are special in various
3298 /// ways, which require special support to insert. The specified MachineInstr
3299 /// is created but not inserted into any basic blocks, and this method is
3300 /// called to expand it into a sequence of instructions, potentially also
3301 /// creating new basic blocks and control flow.
3302 /// As long as the returned basic block is different (i.e., we created a new
3303 /// one), the custom inserter is free to modify the rest of \p MBB.
3304 virtual MachineBasicBlock *
3305 EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const;
3307 /// This method should be implemented by targets that mark instructions with
3308 /// the 'hasPostISelHook' flag. These instructions must be adjusted after
3309 /// instruction selection by target hooks. e.g. To fill in optional defs for
3310 /// ARM 's' setting instructions.
3311 virtual void AdjustInstrPostInstrSelection(MachineInstr &MI,
3312 SDNode *Node) const;
3314 /// If this function returns true, SelectionDAGBuilder emits a
3315 /// LOAD_STACK_GUARD node when it is lowering Intrinsic::stackprotector.
3316 virtual bool useLoadStackGuardNode() const {
3320 /// Lower TLS global address SDNode for target independent emulated TLS model.
3321 virtual SDValue LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
3322 SelectionDAG &DAG) const;
3324 // seteq(x, 0) -> truncate(srl(ctlz(zext(x)), log2(#bits)))
3325 // If we're comparing for equality to zero and isCtlzFast is true, expose the
3326 // fact that this can be implemented as a ctlz/srl pair, so that the dag
3327 // combiner can fold the new nodes.
3328 SDValue lowerCmpEqZeroToCtlzSrl(SDValue Op, SelectionDAG &DAG) const;
3331 SDValue simplifySetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
3332 ISD::CondCode Cond, DAGCombinerInfo &DCI,
3333 const SDLoc &DL) const;
3336 /// Given an LLVM IR type and return type attributes, compute the return value
3337 /// EVTs and flags, and optionally also the offsets, if the return value is
3338 /// being lowered to memory.
3339 void GetReturnInfo(Type *ReturnType, AttributeList attr,
3340 SmallVectorImpl<ISD::OutputArg> &Outs,
3341 const TargetLowering &TLI, const DataLayout &DL);
3343 } // end namespace llvm
3345 #endif // LLVM_TARGET_TARGETLOWERING_H