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/DenseMap.h"
27 #include "llvm/CodeGen/DAGCombine.h"
28 #include "llvm/CodeGen/RuntimeLibcalls.h"
29 #include "llvm/CodeGen/SelectionDAGNodes.h"
30 #include "llvm/IR/Attributes.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/InlineAsm.h"
33 #include "llvm/Support/CallSite.h"
34 #include "llvm/Target/TargetCallingConv.h"
35 #include "llvm/Target/TargetMachine.h"
44 class FunctionLoweringInfo;
45 class ImmutableCallSite;
47 class MachineBasicBlock;
48 class MachineFunction;
50 class MachineJumpTableInfo;
55 template<typename T> class SmallVectorImpl;
57 class TargetRegisterClass;
58 class TargetLibraryInfo;
59 class TargetLoweringObjectFile;
64 None, // No preference
65 Source, // Follow source order.
66 RegPressure, // Scheduling for lowest register pressure.
67 Hybrid, // Scheduling for both latency and register pressure.
68 ILP, // Scheduling for ILP in low register pressure mode.
69 VLIW // Scheduling for VLIW targets.
73 /// This base class for TargetLowering contains the SelectionDAG-independent
74 /// parts that can be used from the rest of CodeGen.
75 class TargetLoweringBase {
76 TargetLoweringBase(const TargetLoweringBase&) LLVM_DELETED_FUNCTION;
77 void operator=(const TargetLoweringBase&) LLVM_DELETED_FUNCTION;
80 /// This enum indicates whether operations are valid for a target, and if not,
81 /// what action should be used to make them valid.
83 Legal, // The target natively supports this operation.
84 Promote, // This operation should be executed in a larger type.
85 Expand, // Try to expand this to other ops, otherwise use a libcall.
86 Custom // Use the LowerOperation hook to implement custom lowering.
89 /// This enum indicates whether a types are legal for a target, and if not,
90 /// what action should be used to make them valid.
91 enum LegalizeTypeAction {
92 TypeLegal, // The target natively supports this type.
93 TypePromoteInteger, // Replace this integer with a larger one.
94 TypeExpandInteger, // Split this integer into two of half the size.
95 TypeSoftenFloat, // Convert this float to a same size integer type.
96 TypeExpandFloat, // Split this float into two of half the size.
97 TypeScalarizeVector, // Replace this one-element vector with its element.
98 TypeSplitVector, // Split this vector into two of half the size.
99 TypeWidenVector // This vector should be widened into a larger vector.
102 /// LegalizeKind holds the legalization kind that needs to happen to EVT
103 /// in order to type-legalize it.
104 typedef std::pair<LegalizeTypeAction, EVT> LegalizeKind;
106 /// Enum that describes how the target represents true/false values.
107 enum BooleanContent {
108 UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
109 ZeroOrOneBooleanContent, // All bits zero except for bit 0.
110 ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
113 /// Enum that describes what type of support for selects the target has.
114 enum SelectSupportKind {
115 ScalarValSelect, // The target supports scalar selects (ex: cmov).
116 ScalarCondVectorVal, // The target supports selects with a scalar condition
117 // and vector values (ex: cmov).
118 VectorMaskSelect // The target supports vector selects with a vector
119 // mask (ex: x86 blends).
122 static ISD::NodeType getExtendForContent(BooleanContent Content) {
124 case UndefinedBooleanContent:
125 // Extend by adding rubbish bits.
126 return ISD::ANY_EXTEND;
127 case ZeroOrOneBooleanContent:
128 // Extend by adding zero bits.
129 return ISD::ZERO_EXTEND;
130 case ZeroOrNegativeOneBooleanContent:
131 // Extend by copying the sign bit.
132 return ISD::SIGN_EXTEND;
134 llvm_unreachable("Invalid content kind");
137 /// NOTE: The constructor takes ownership of TLOF.
138 explicit TargetLoweringBase(const TargetMachine &TM,
139 const TargetLoweringObjectFile *TLOF);
140 virtual ~TargetLoweringBase();
143 /// \brief Initialize all of the actions to default values.
147 const TargetMachine &getTargetMachine() const { return TM; }
148 const DataLayout *getDataLayout() const { return DL; }
149 const TargetLoweringObjectFile &getObjFileLowering() const { return TLOF; }
151 bool isBigEndian() const { return !IsLittleEndian; }
152 bool isLittleEndian() const { return IsLittleEndian; }
154 /// Return the pointer type for the given address space, defaults to
155 /// the pointer type from the data layout.
156 /// FIXME: The default needs to be removed once all the code is updated.
157 virtual MVT getPointerTy(uint32_t /*AS*/ = 0) const;
158 unsigned getPointerSizeInBits(uint32_t AS = 0) const;
159 unsigned getPointerTypeSizeInBits(Type *Ty) const;
160 virtual MVT getScalarShiftAmountTy(EVT LHSTy) const;
162 EVT getShiftAmountTy(EVT LHSTy) const;
164 /// Returns the type to be used for the index operand of:
165 /// ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
166 /// ISD::INSERT_SUBVECTOR, and ISD::EXTRACT_SUBVECTOR
167 virtual MVT getVectorIdxTy() const {
168 return getPointerTy();
171 /// Return true if the select operation is expensive for this target.
172 bool isSelectExpensive() const { return SelectIsExpensive; }
174 virtual bool isSelectSupported(SelectSupportKind /*kind*/) const {
178 /// Return true if multiple condition registers are available.
179 bool hasMultipleConditionRegisters() const {
180 return HasMultipleConditionRegisters;
183 /// Return true if a vector of the given type should be split
184 /// (TypeSplitVector) instead of promoted (TypePromoteInteger) during type
186 virtual bool shouldSplitVectorElementType(EVT /*VT*/) const { return false; }
188 /// Return true if integer divide is usually cheaper than a sequence of
189 /// several shifts, adds, and multiplies for this target.
190 bool isIntDivCheap() const { return IntDivIsCheap; }
192 /// Returns true if target has indicated at least one type should be bypassed.
193 bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
195 /// Returns map of slow types for division or remainder with corresponding
197 const DenseMap<unsigned int, unsigned int> &getBypassSlowDivWidths() const {
198 return BypassSlowDivWidths;
201 /// Return true if pow2 div is cheaper than a chain of srl/add/sra.
202 bool isPow2DivCheap() const { return Pow2DivIsCheap; }
204 /// Return true if Flow Control is an expensive operation that should be
206 bool isJumpExpensive() const { return JumpIsExpensive; }
208 /// Return true if selects are only cheaper than branches if the branch is
209 /// unlikely to be predicted right.
210 bool isPredictableSelectExpensive() const {
211 return PredictableSelectIsExpensive;
214 /// isLoadBitCastBeneficial() - Return true if the following transform
216 /// fold (conv (load x)) -> (load (conv*)x)
217 /// On architectures that don't natively support some vector loads efficiently,
218 /// casting the load to a smaller vector of larger types and loading
219 /// is more efficient, however, this can be undone by optimizations in
221 virtual bool isLoadBitCastBeneficial(EVT /* Load */, EVT /* Bitcast */) const {
225 /// Return the ValueType of the result of SETCC operations. Also used to
226 /// obtain the target's preferred type for the condition operand of SELECT and
227 /// BRCOND nodes. In the case of BRCOND the argument passed is MVT::Other
228 /// since there are no other operands to get a type hint from.
229 virtual EVT getSetCCResultType(LLVMContext &Context, EVT VT) const;
231 /// Return the ValueType for comparison libcalls. Comparions libcalls include
232 /// floating point comparion calls, and Ordered/Unordered check calls on
233 /// floating point numbers.
235 MVT::SimpleValueType getCmpLibcallReturnType() const;
237 /// For targets without i1 registers, this gives the nature of the high-bits
238 /// of boolean values held in types wider than i1.
240 /// "Boolean values" are special true/false values produced by nodes like
241 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
242 /// Not to be confused with general values promoted from i1. Some cpus
243 /// distinguish between vectors of boolean and scalars; the isVec parameter
244 /// selects between the two kinds. For example on X86 a scalar boolean should
245 /// be zero extended from i1, while the elements of a vector of booleans
246 /// should be sign extended from i1.
247 BooleanContent getBooleanContents(bool isVec) const {
248 return isVec ? BooleanVectorContents : BooleanContents;
251 /// Return target scheduling preference.
252 Sched::Preference getSchedulingPreference() const {
253 return SchedPreferenceInfo;
256 /// Some scheduler, e.g. hybrid, can switch to different scheduling heuristics
257 /// for different nodes. This function returns the preference (or none) for
259 virtual Sched::Preference getSchedulingPreference(SDNode *) const {
263 /// Return the register class that should be used for the specified value
265 virtual const TargetRegisterClass *getRegClassFor(MVT VT) const {
266 const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
267 assert(RC && "This value type is not natively supported!");
271 /// Return the 'representative' register class for the specified value
274 /// The 'representative' register class is the largest legal super-reg
275 /// register class for the register class of the value type. For example, on
276 /// i386 the rep register class for i8, i16, and i32 are GR32; while the rep
277 /// register class is GR64 on x86_64.
278 virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
279 const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
283 /// Return the cost of the 'representative' register class for the specified
285 virtual uint8_t getRepRegClassCostFor(MVT VT) const {
286 return RepRegClassCostForVT[VT.SimpleTy];
289 /// Return true if the target has native support for the specified value type.
290 /// This means that it has a register that directly holds it without
291 /// promotions or expansions.
292 bool isTypeLegal(EVT VT) const {
293 assert(!VT.isSimple() ||
294 (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
295 return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != 0;
298 class ValueTypeActionImpl {
299 /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
300 /// that indicates how instruction selection should deal with the type.
301 uint8_t ValueTypeActions[MVT::LAST_VALUETYPE];
304 ValueTypeActionImpl() {
305 std::fill(ValueTypeActions, array_endof(ValueTypeActions), 0);
308 LegalizeTypeAction getTypeAction(MVT VT) const {
309 return (LegalizeTypeAction)ValueTypeActions[VT.SimpleTy];
312 void setTypeAction(MVT VT, LegalizeTypeAction Action) {
313 unsigned I = VT.SimpleTy;
314 ValueTypeActions[I] = Action;
318 const ValueTypeActionImpl &getValueTypeActions() const {
319 return ValueTypeActions;
322 /// Return how we should legalize values of this type, either it is already
323 /// legal (return 'Legal') or we need to promote it to a larger type (return
324 /// 'Promote'), or we need to expand it into multiple registers of smaller
325 /// integer type (return 'Expand'). 'Custom' is not an option.
326 LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const {
327 return getTypeConversion(Context, VT).first;
329 LegalizeTypeAction getTypeAction(MVT VT) const {
330 return ValueTypeActions.getTypeAction(VT);
333 /// For types supported by the target, this is an identity function. For
334 /// types that must be promoted to larger types, this returns the larger type
335 /// to promote to. For integer types that are larger than the largest integer
336 /// register, this contains one step in the expansion to get to the smaller
337 /// register. For illegal floating point types, this returns the integer type
339 EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
340 return getTypeConversion(Context, VT).second;
343 /// For types supported by the target, this is an identity function. For
344 /// types that must be expanded (i.e. integer types that are larger than the
345 /// largest integer register or illegal floating point types), this returns
346 /// the largest legal type it will be expanded to.
347 EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
348 assert(!VT.isVector());
350 switch (getTypeAction(Context, VT)) {
353 case TypeExpandInteger:
354 VT = getTypeToTransformTo(Context, VT);
357 llvm_unreachable("Type is not legal nor is it to be expanded!");
362 /// Vector types are broken down into some number of legal first class types.
363 /// For example, EVT::v8f32 maps to 2 EVT::v4f32 with Altivec or SSE1, or 8
364 /// promoted EVT::f64 values with the X86 FP stack. Similarly, EVT::v2i64
365 /// turns into 4 EVT::i32 values with both PPC and X86.
367 /// This method returns the number of registers needed, and the VT for each
368 /// register. It also returns the VT and quantity of the intermediate values
369 /// before they are promoted/expanded.
370 unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
372 unsigned &NumIntermediates,
373 MVT &RegisterVT) const;
375 struct IntrinsicInfo {
376 unsigned opc; // target opcode
377 EVT memVT; // memory VT
378 const Value* ptrVal; // value representing memory location
379 int offset; // offset off of ptrVal
380 unsigned align; // alignment
381 bool vol; // is volatile?
382 bool readMem; // reads memory?
383 bool writeMem; // writes memory?
386 /// Given an intrinsic, checks if on the target the intrinsic will need to map
387 /// to a MemIntrinsicNode (touches memory). If this is the case, it returns
388 /// true and store the intrinsic information into the IntrinsicInfo that was
389 /// passed to the function.
390 virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
391 unsigned /*Intrinsic*/) const {
395 /// Returns true if the target can instruction select the specified FP
396 /// immediate natively. If false, the legalizer will materialize the FP
397 /// immediate as a load from a constant pool.
398 virtual bool isFPImmLegal(const APFloat &/*Imm*/, EVT /*VT*/) const {
402 /// Targets can use this to indicate that they only support *some*
403 /// VECTOR_SHUFFLE operations, those with specific masks. By default, if a
404 /// target supports the VECTOR_SHUFFLE node, all mask values are assumed to be
406 virtual bool isShuffleMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
411 /// Returns true if the operation can trap for the value type.
413 /// VT must be a legal type. By default, we optimistically assume most
414 /// operations don't trap except for divide and remainder.
415 virtual bool canOpTrap(unsigned Op, EVT VT) const;
417 /// Similar to isShuffleMaskLegal. This is used by Targets can use this to
418 /// indicate if there is a suitable VECTOR_SHUFFLE that can be used to replace
419 /// a VAND with a constant pool entry.
420 virtual bool isVectorClearMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
425 /// Return how this operation should be treated: either it is legal, needs to
426 /// be promoted to a larger size, needs to be expanded to some other code
427 /// sequence, or the target has a custom expander for it.
428 LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
429 if (VT.isExtended()) return Expand;
430 // If a target-specific SDNode requires legalization, require the target
431 // to provide custom legalization for it.
432 if (Op > array_lengthof(OpActions[0])) return Custom;
433 unsigned I = (unsigned) VT.getSimpleVT().SimpleTy;
434 return (LegalizeAction)OpActions[I][Op];
437 /// Return true if the specified operation is legal on this target or can be
438 /// made legal with custom lowering. This is used to help guide high-level
439 /// lowering decisions.
440 bool isOperationLegalOrCustom(unsigned Op, EVT VT) const {
441 return (VT == MVT::Other || isTypeLegal(VT)) &&
442 (getOperationAction(Op, VT) == Legal ||
443 getOperationAction(Op, VT) == Custom);
446 /// Return true if the specified operation is legal on this target or can be
447 /// made legal using promotion. This is used to help guide high-level lowering
449 bool isOperationLegalOrPromote(unsigned Op, EVT VT) const {
450 return (VT == MVT::Other || isTypeLegal(VT)) &&
451 (getOperationAction(Op, VT) == Legal ||
452 getOperationAction(Op, VT) == Promote);
455 /// Return true if the specified operation is illegal on this target or
456 /// unlikely to be made legal with custom lowering. This is used to help guide
457 /// high-level lowering decisions.
458 bool isOperationExpand(unsigned Op, EVT VT) const {
459 return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
462 /// Return true if the specified operation is legal on this target.
463 bool isOperationLegal(unsigned Op, EVT VT) const {
464 return (VT == MVT::Other || isTypeLegal(VT)) &&
465 getOperationAction(Op, VT) == Legal;
468 /// Return how this load with extension should be treated: either it is legal,
469 /// needs to be promoted to a larger size, needs to be expanded to some other
470 /// code sequence, or the target has a custom expander for it.
471 LegalizeAction getLoadExtAction(unsigned ExtType, MVT VT) const {
472 assert(ExtType < ISD::LAST_LOADEXT_TYPE && VT < MVT::LAST_VALUETYPE &&
473 "Table isn't big enough!");
474 return (LegalizeAction)LoadExtActions[VT.SimpleTy][ExtType];
477 /// Return true if the specified load with extension is legal on this target.
478 bool isLoadExtLegal(unsigned ExtType, EVT VT) const {
479 return VT.isSimple() &&
480 getLoadExtAction(ExtType, VT.getSimpleVT()) == Legal;
483 /// Return how this store with truncation should be treated: either it is
484 /// legal, needs to be promoted to a larger size, needs to be expanded to some
485 /// other code sequence, or the target has a custom expander for it.
486 LegalizeAction getTruncStoreAction(MVT ValVT, MVT MemVT) const {
487 assert(ValVT < MVT::LAST_VALUETYPE && MemVT < MVT::LAST_VALUETYPE &&
488 "Table isn't big enough!");
489 return (LegalizeAction)TruncStoreActions[ValVT.SimpleTy]
493 /// Return true if the specified store with truncation is legal on this
495 bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
496 return isTypeLegal(ValVT) && MemVT.isSimple() &&
497 getTruncStoreAction(ValVT.getSimpleVT(), MemVT.getSimpleVT()) == Legal;
500 /// Return how the indexed load should be treated: either it is legal, needs
501 /// to be promoted to a larger size, needs to be expanded to some other code
502 /// sequence, or the target has a custom expander for it.
504 getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
505 assert(IdxMode < ISD::LAST_INDEXED_MODE && VT < MVT::LAST_VALUETYPE &&
506 "Table isn't big enough!");
507 unsigned Ty = (unsigned)VT.SimpleTy;
508 return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] & 0xf0) >> 4);
511 /// Return true if the specified indexed load is legal on this target.
512 bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
513 return VT.isSimple() &&
514 (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
515 getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
518 /// Return how the indexed store should be treated: either it is legal, needs
519 /// to be promoted to a larger size, needs to be expanded to some other code
520 /// sequence, or the target has a custom expander for it.
522 getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
523 assert(IdxMode < ISD::LAST_INDEXED_MODE && VT < MVT::LAST_VALUETYPE &&
524 "Table isn't big enough!");
525 unsigned Ty = (unsigned)VT.SimpleTy;
526 return (LegalizeAction)(IndexedModeActions[Ty][IdxMode] & 0x0f);
529 /// Return true if the specified indexed load is legal on this target.
530 bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
531 return VT.isSimple() &&
532 (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
533 getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
536 /// Return how the condition code should be treated: either it is legal, needs
537 /// to be expanded to some other code sequence, or the target has a custom
540 getCondCodeAction(ISD::CondCode CC, MVT VT) const {
541 assert((unsigned)CC < array_lengthof(CondCodeActions) &&
542 ((unsigned)VT.SimpleTy >> 4) < array_lengthof(CondCodeActions[0]) &&
543 "Table isn't big enough!");
544 // See setCondCodeAction for how this is encoded.
545 uint32_t Shift = 2 * (VT.SimpleTy & 0xF);
546 uint32_t Value = CondCodeActions[CC][VT.SimpleTy >> 4];
547 LegalizeAction Action = (LegalizeAction) ((Value >> Shift) & 0x3);
548 assert(Action != Promote && "Can't promote condition code!");
552 /// Return true if the specified condition code is legal on this target.
553 bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
555 getCondCodeAction(CC, VT) == Legal ||
556 getCondCodeAction(CC, VT) == Custom;
560 /// If the action for this operation is to promote, this method returns the
561 /// ValueType to promote to.
562 MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
563 assert(getOperationAction(Op, VT) == Promote &&
564 "This operation isn't promoted!");
566 // See if this has an explicit type specified.
567 std::map<std::pair<unsigned, MVT::SimpleValueType>,
568 MVT::SimpleValueType>::const_iterator PTTI =
569 PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
570 if (PTTI != PromoteToType.end()) return PTTI->second;
572 assert((VT.isInteger() || VT.isFloatingPoint()) &&
573 "Cannot autopromote this type, add it with AddPromotedToType.");
577 NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
578 assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
579 "Didn't find type to promote to!");
580 } while (!isTypeLegal(NVT) ||
581 getOperationAction(Op, NVT) == Promote);
585 /// Return the EVT corresponding to this LLVM type. This is fixed by the LLVM
586 /// operations except for the pointer size. If AllowUnknown is true, this
587 /// will return MVT::Other for types with no EVT counterpart (e.g. structs),
588 /// otherwise it will assert.
589 EVT getValueType(Type *Ty, bool AllowUnknown = false) const {
590 // Lower scalar pointers to native pointer types.
591 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
592 return getPointerTy(PTy->getAddressSpace());
594 if (Ty->isVectorTy()) {
595 VectorType *VTy = cast<VectorType>(Ty);
596 Type *Elm = VTy->getElementType();
597 // Lower vectors of pointers to native pointer types.
598 if (PointerType *PT = dyn_cast<PointerType>(Elm)) {
599 EVT PointerTy(getPointerTy(PT->getAddressSpace()));
600 Elm = PointerTy.getTypeForEVT(Ty->getContext());
603 return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
604 VTy->getNumElements());
606 return EVT::getEVT(Ty, AllowUnknown);
609 /// Return the MVT corresponding to this LLVM type. See getValueType.
610 MVT getSimpleValueType(Type *Ty, bool AllowUnknown = false) const {
611 return getValueType(Ty, AllowUnknown).getSimpleVT();
614 /// Return the desired alignment for ByVal or InAlloca aggregate function
615 /// arguments in the caller parameter area. This is the actual alignment, not
617 virtual unsigned getByValTypeAlignment(Type *Ty) const;
619 /// Return the type of registers that this ValueType will eventually require.
620 MVT getRegisterType(MVT VT) const {
621 assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
622 return RegisterTypeForVT[VT.SimpleTy];
625 /// Return the type of registers that this ValueType will eventually require.
626 MVT getRegisterType(LLVMContext &Context, EVT VT) const {
628 assert((unsigned)VT.getSimpleVT().SimpleTy <
629 array_lengthof(RegisterTypeForVT));
630 return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
635 unsigned NumIntermediates;
636 (void)getVectorTypeBreakdown(Context, VT, VT1,
637 NumIntermediates, RegisterVT);
640 if (VT.isInteger()) {
641 return getRegisterType(Context, getTypeToTransformTo(Context, VT));
643 llvm_unreachable("Unsupported extended type!");
646 /// Return the number of registers that this ValueType will eventually
649 /// This is one for any types promoted to live in larger registers, but may be
650 /// more than one for types (like i64) that are split into pieces. For types
651 /// like i140, which are first promoted then expanded, it is the number of
652 /// registers needed to hold all the bits of the original type. For an i140
653 /// on a 32 bit machine this means 5 registers.
654 unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
656 assert((unsigned)VT.getSimpleVT().SimpleTy <
657 array_lengthof(NumRegistersForVT));
658 return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
663 unsigned NumIntermediates;
664 return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
666 if (VT.isInteger()) {
667 unsigned BitWidth = VT.getSizeInBits();
668 unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
669 return (BitWidth + RegWidth - 1) / RegWidth;
671 llvm_unreachable("Unsupported extended type!");
674 /// If true, then instruction selection should seek to shrink the FP constant
675 /// of the specified type to a smaller type in order to save space and / or
677 virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
679 /// If true, the target has custom DAG combine transformations that it can
680 /// perform for the specified node.
681 bool hasTargetDAGCombine(ISD::NodeType NT) const {
682 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
683 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
686 /// \brief Get maximum # of store operations permitted for llvm.memset
688 /// This function returns the maximum number of store operations permitted
689 /// to replace a call to llvm.memset. The value is set by the target at the
690 /// performance threshold for such a replacement. If OptSize is true,
691 /// return the limit for functions that have OptSize attribute.
692 unsigned getMaxStoresPerMemset(bool OptSize) const {
693 return OptSize ? MaxStoresPerMemsetOptSize : MaxStoresPerMemset;
696 /// \brief Get maximum # of store operations permitted for llvm.memcpy
698 /// This function returns the maximum number of store operations permitted
699 /// to replace a call to llvm.memcpy. The value is set by the target at the
700 /// performance threshold for such a replacement. If OptSize is true,
701 /// return the limit for functions that have OptSize attribute.
702 unsigned getMaxStoresPerMemcpy(bool OptSize) const {
703 return OptSize ? MaxStoresPerMemcpyOptSize : MaxStoresPerMemcpy;
706 /// \brief Get maximum # of store operations permitted for llvm.memmove
708 /// This function returns the maximum number of store operations permitted
709 /// to replace a call to llvm.memmove. The value is set by the target at the
710 /// performance threshold for such a replacement. If OptSize is true,
711 /// return the limit for functions that have OptSize attribute.
712 unsigned getMaxStoresPerMemmove(bool OptSize) const {
713 return OptSize ? MaxStoresPerMemmoveOptSize : MaxStoresPerMemmove;
716 /// \brief Determine if the target supports unaligned memory accesses.
718 /// This function returns true if the target allows unaligned memory accesses
719 /// of the specified type in the given address space. If true, it also returns
720 /// whether the unaligned memory access is "fast" in the third argument by
721 /// reference. This is used, for example, in situations where an array
722 /// copy/move/set is converted to a sequence of store operations. Its use
723 /// helps to ensure that such replacements don't generate code that causes an
724 /// alignment error (trap) on the target machine.
725 virtual bool allowsUnalignedMemoryAccesses(EVT,
726 unsigned AddrSpace = 0,
727 bool * /*Fast*/ = 0) const {
731 /// Returns the target specific optimal type for load and store operations as
732 /// a result of memset, memcpy, and memmove lowering.
734 /// If DstAlign is zero that means it's safe to destination alignment can
735 /// satisfy any constraint. Similarly if SrcAlign is zero it means there isn't
736 /// a need to check it against alignment requirement, probably because the
737 /// source does not need to be loaded. If 'IsMemset' is true, that means it's
738 /// expanding a memset. If 'ZeroMemset' is true, that means it's a memset of
739 /// zero. 'MemcpyStrSrc' indicates whether the memcpy source is constant so it
740 /// does not need to be loaded. It returns EVT::Other if the type should be
741 /// determined using generic target-independent logic.
742 virtual EVT getOptimalMemOpType(uint64_t /*Size*/,
743 unsigned /*DstAlign*/, unsigned /*SrcAlign*/,
746 bool /*MemcpyStrSrc*/,
747 MachineFunction &/*MF*/) const {
751 /// Returns true if it's safe to use load / store of the specified type to
752 /// expand memcpy / memset inline.
754 /// This is mostly true for all types except for some special cases. For
755 /// example, on X86 targets without SSE2 f64 load / store are done with fldl /
756 /// fstpl which also does type conversion. Note the specified type doesn't
757 /// have to be legal as the hook is used before type legalization.
758 virtual bool isSafeMemOpType(MVT /*VT*/) const { return true; }
760 /// Determine if we should use _setjmp or setjmp to implement llvm.setjmp.
761 bool usesUnderscoreSetJmp() const {
762 return UseUnderscoreSetJmp;
765 /// Determine if we should use _longjmp or longjmp to implement llvm.longjmp.
766 bool usesUnderscoreLongJmp() const {
767 return UseUnderscoreLongJmp;
770 /// Return whether the target can generate code for jump tables.
771 bool supportJumpTables() const {
772 return SupportJumpTables;
775 /// Return integer threshold on number of blocks to use jump tables rather
776 /// than if sequence.
777 int getMinimumJumpTableEntries() const {
778 return MinimumJumpTableEntries;
781 /// If a physical register, this specifies the register that
782 /// llvm.savestack/llvm.restorestack should save and restore.
783 unsigned getStackPointerRegisterToSaveRestore() const {
784 return StackPointerRegisterToSaveRestore;
787 /// If a physical register, this returns the register that receives the
788 /// exception address on entry to a landing pad.
789 unsigned getExceptionPointerRegister() const {
790 return ExceptionPointerRegister;
793 /// If a physical register, this returns the register that receives the
794 /// exception typeid on entry to a landing pad.
795 unsigned getExceptionSelectorRegister() const {
796 return ExceptionSelectorRegister;
799 /// Returns the target's jmp_buf size in bytes (if never set, the default is
801 unsigned getJumpBufSize() const {
805 /// Returns the target's jmp_buf alignment in bytes (if never set, the default
807 unsigned getJumpBufAlignment() const {
808 return JumpBufAlignment;
811 /// Return the minimum stack alignment of an argument.
812 unsigned getMinStackArgumentAlignment() const {
813 return MinStackArgumentAlignment;
816 /// Return the minimum function alignment.
817 unsigned getMinFunctionAlignment() const {
818 return MinFunctionAlignment;
821 /// Return the preferred function alignment.
822 unsigned getPrefFunctionAlignment() const {
823 return PrefFunctionAlignment;
826 /// Return the preferred loop alignment.
827 unsigned getPrefLoopAlignment() const {
828 return PrefLoopAlignment;
831 /// Return whether the DAG builder should automatically insert fences and
832 /// reduce ordering for atomics.
833 bool getInsertFencesForAtomic() const {
834 return InsertFencesForAtomic;
837 /// Return true if the target stores stack protector cookies at a fixed offset
838 /// in some non-standard address space, and populates the address space and
839 /// offset as appropriate.
840 virtual bool getStackCookieLocation(unsigned &/*AddressSpace*/,
841 unsigned &/*Offset*/) const {
845 /// Returns the maximal possible offset which can be used for loads / stores
847 virtual unsigned getMaximalGlobalOffset() const {
851 /// Returns true if a cast between SrcAS and DestAS is a noop.
852 virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const {
856 //===--------------------------------------------------------------------===//
857 /// \name Helpers for TargetTransformInfo implementations
860 /// Get the ISD node that corresponds to the Instruction class opcode.
861 int InstructionOpcodeToISD(unsigned Opcode) const;
863 /// Estimate the cost of type-legalization and the legalized type.
864 std::pair<unsigned, MVT> getTypeLegalizationCost(Type *Ty) const;
868 //===--------------------------------------------------------------------===//
869 // TargetLowering Configuration Methods - These methods should be invoked by
870 // the derived class constructor to configure this object for the target.
873 /// \brief Reset the operation actions based on target options.
874 virtual void resetOperationActions() {}
877 /// Specify how the target extends the result of a boolean value from i1 to a
878 /// wider type. See getBooleanContents.
879 void setBooleanContents(BooleanContent Ty) { BooleanContents = Ty; }
881 /// Specify how the target extends the result of a vector boolean value from a
882 /// vector of i1 to a wider type. See getBooleanContents.
883 void setBooleanVectorContents(BooleanContent Ty) {
884 BooleanVectorContents = Ty;
887 /// Specify the target scheduling preference.
888 void setSchedulingPreference(Sched::Preference Pref) {
889 SchedPreferenceInfo = Pref;
892 /// Indicate whether this target prefers to use _setjmp to implement
893 /// llvm.setjmp or the version without _. Defaults to false.
894 void setUseUnderscoreSetJmp(bool Val) {
895 UseUnderscoreSetJmp = Val;
898 /// Indicate whether this target prefers to use _longjmp to implement
899 /// llvm.longjmp or the version without _. Defaults to false.
900 void setUseUnderscoreLongJmp(bool Val) {
901 UseUnderscoreLongJmp = Val;
904 /// Indicate whether the target can generate code for jump tables.
905 void setSupportJumpTables(bool Val) {
906 SupportJumpTables = Val;
909 /// Indicate the number of blocks to generate jump tables rather than if
911 void setMinimumJumpTableEntries(int Val) {
912 MinimumJumpTableEntries = Val;
915 /// If set to a physical register, this specifies the register that
916 /// llvm.savestack/llvm.restorestack should save and restore.
917 void setStackPointerRegisterToSaveRestore(unsigned R) {
918 StackPointerRegisterToSaveRestore = R;
921 /// If set to a physical register, this sets the register that receives the
922 /// exception address on entry to a landing pad.
923 void setExceptionPointerRegister(unsigned R) {
924 ExceptionPointerRegister = R;
927 /// If set to a physical register, this sets the register that receives the
928 /// exception typeid on entry to a landing pad.
929 void setExceptionSelectorRegister(unsigned R) {
930 ExceptionSelectorRegister = R;
933 /// Tells the code generator not to expand operations into sequences that use
934 /// the select operations if possible.
935 void setSelectIsExpensive(bool isExpensive = true) {
936 SelectIsExpensive = isExpensive;
939 /// Tells the code generator that the target has multiple (allocatable)
940 /// condition registers that can be used to store the results of comparisons
941 /// for use by selects and conditional branches. With multiple condition
942 /// registers, the code generator will not aggressively sink comparisons into
943 /// the blocks of their users.
944 void setHasMultipleConditionRegisters(bool hasManyRegs = true) {
945 HasMultipleConditionRegisters = hasManyRegs;
948 /// Tells the code generator not to expand sequence of operations into a
949 /// separate sequences that increases the amount of flow control.
950 void setJumpIsExpensive(bool isExpensive = true) {
951 JumpIsExpensive = isExpensive;
954 /// Tells the code generator that integer divide is expensive, and if
955 /// possible, should be replaced by an alternate sequence of instructions not
956 /// containing an integer divide.
957 void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
959 /// Tells the code generator which bitwidths to bypass.
960 void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
961 BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
964 /// Tells the code generator that it shouldn't generate srl/add/sra for a
965 /// signed divide by power of two, and let the target handle it.
966 void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
968 /// Add the specified register class as an available regclass for the
969 /// specified value type. This indicates the selector can handle values of
970 /// that class natively.
971 void addRegisterClass(MVT VT, const TargetRegisterClass *RC) {
972 assert((unsigned)VT.SimpleTy < array_lengthof(RegClassForVT));
973 AvailableRegClasses.push_back(std::make_pair(VT, RC));
974 RegClassForVT[VT.SimpleTy] = RC;
977 /// Remove all register classes.
978 void clearRegisterClasses() {
979 memset(RegClassForVT, 0,MVT::LAST_VALUETYPE * sizeof(TargetRegisterClass*));
981 AvailableRegClasses.clear();
984 /// \brief Remove all operation actions.
985 void clearOperationActions() {
988 /// Return the largest legal super-reg register class of the register class
989 /// for the specified type and its associated "cost".
990 virtual std::pair<const TargetRegisterClass*, uint8_t>
991 findRepresentativeClass(MVT VT) const;
993 /// Once all of the register classes are added, this allows us to compute
994 /// derived properties we expose.
995 void computeRegisterProperties();
997 /// Indicate that the specified operation does not work with the specified
998 /// type and indicate what to do about it.
999 void setOperationAction(unsigned Op, MVT VT,
1000 LegalizeAction Action) {
1001 assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
1002 OpActions[(unsigned)VT.SimpleTy][Op] = (uint8_t)Action;
1005 /// Indicate that the specified load with extension does not work with the
1006 /// specified type and indicate what to do about it.
1007 void setLoadExtAction(unsigned ExtType, MVT VT,
1008 LegalizeAction Action) {
1009 assert(ExtType < ISD::LAST_LOADEXT_TYPE && VT < MVT::LAST_VALUETYPE &&
1010 "Table isn't big enough!");
1011 LoadExtActions[VT.SimpleTy][ExtType] = (uint8_t)Action;
1014 /// Indicate that the specified truncating store does not work with the
1015 /// specified type and indicate what to do about it.
1016 void setTruncStoreAction(MVT ValVT, MVT MemVT,
1017 LegalizeAction Action) {
1018 assert(ValVT < MVT::LAST_VALUETYPE && MemVT < MVT::LAST_VALUETYPE &&
1019 "Table isn't big enough!");
1020 TruncStoreActions[ValVT.SimpleTy][MemVT.SimpleTy] = (uint8_t)Action;
1023 /// Indicate that the specified indexed load does or does not work with the
1024 /// specified type and indicate what to do abort it.
1026 /// NOTE: All indexed mode loads are initialized to Expand in
1027 /// TargetLowering.cpp
1028 void setIndexedLoadAction(unsigned IdxMode, MVT VT,
1029 LegalizeAction Action) {
1030 assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
1031 (unsigned)Action < 0xf && "Table isn't big enough!");
1032 // Load action are kept in the upper half.
1033 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0xf0;
1034 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action) <<4;
1037 /// Indicate that the specified indexed store does or does not work with the
1038 /// specified type and indicate what to do about it.
1040 /// NOTE: All indexed mode stores are initialized to Expand in
1041 /// TargetLowering.cpp
1042 void setIndexedStoreAction(unsigned IdxMode, MVT VT,
1043 LegalizeAction Action) {
1044 assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
1045 (unsigned)Action < 0xf && "Table isn't big enough!");
1046 // Store action are kept in the lower half.
1047 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0x0f;
1048 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action);
1051 /// Indicate that the specified condition code is or isn't supported on the
1052 /// target and indicate what to do about it.
1053 void setCondCodeAction(ISD::CondCode CC, MVT VT,
1054 LegalizeAction Action) {
1055 assert(VT < MVT::LAST_VALUETYPE &&
1056 (unsigned)CC < array_lengthof(CondCodeActions) &&
1057 "Table isn't big enough!");
1058 /// The lower 5 bits of the SimpleTy index into Nth 2bit set from the 32-bit
1059 /// value and the upper 27 bits index into the second dimension of the array
1060 /// to select what 32-bit value to use.
1061 uint32_t Shift = 2 * (VT.SimpleTy & 0xF);
1062 CondCodeActions[CC][VT.SimpleTy >> 4] &= ~((uint32_t)0x3 << Shift);
1063 CondCodeActions[CC][VT.SimpleTy >> 4] |= (uint32_t)Action << Shift;
1066 /// If Opc/OrigVT is specified as being promoted, the promotion code defaults
1067 /// to trying a larger integer/fp until it can find one that works. If that
1068 /// default is insufficient, this method can be used by the target to override
1070 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1071 PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
1074 /// Targets should invoke this method for each target independent node that
1075 /// they want to provide a custom DAG combiner for by implementing the
1076 /// PerformDAGCombine virtual method.
1077 void setTargetDAGCombine(ISD::NodeType NT) {
1078 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1079 TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
1082 /// Set the target's required jmp_buf buffer size (in bytes); default is 200
1083 void setJumpBufSize(unsigned Size) {
1087 /// Set the target's required jmp_buf buffer alignment (in bytes); default is
1089 void setJumpBufAlignment(unsigned Align) {
1090 JumpBufAlignment = Align;
1093 /// Set the target's minimum function alignment (in log2(bytes))
1094 void setMinFunctionAlignment(unsigned Align) {
1095 MinFunctionAlignment = Align;
1098 /// Set the target's preferred function alignment. This should be set if
1099 /// there is a performance benefit to higher-than-minimum alignment (in
1101 void setPrefFunctionAlignment(unsigned Align) {
1102 PrefFunctionAlignment = Align;
1105 /// Set the target's preferred loop alignment. Default alignment is zero, it
1106 /// means the target does not care about loop alignment. The alignment is
1107 /// specified in log2(bytes).
1108 void setPrefLoopAlignment(unsigned Align) {
1109 PrefLoopAlignment = Align;
1112 /// Set the minimum stack alignment of an argument (in log2(bytes)).
1113 void setMinStackArgumentAlignment(unsigned Align) {
1114 MinStackArgumentAlignment = Align;
1117 /// Set if the DAG builder should automatically insert fences and reduce the
1118 /// order of atomic memory operations to Monotonic.
1119 void setInsertFencesForAtomic(bool fence) {
1120 InsertFencesForAtomic = fence;
1124 //===--------------------------------------------------------------------===//
1125 // Addressing mode description hooks (used by LSR etc).
1128 /// CodeGenPrepare sinks address calculations into the same BB as Load/Store
1129 /// instructions reading the address. This allows as much computation as
1130 /// possible to be done in the address mode for that operand. This hook lets
1131 /// targets also pass back when this should be done on intrinsics which
1133 virtual bool GetAddrModeArguments(IntrinsicInst * /*I*/,
1134 SmallVectorImpl<Value*> &/*Ops*/,
1135 Type *&/*AccessTy*/) const {
1139 /// This represents an addressing mode of:
1140 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
1141 /// If BaseGV is null, there is no BaseGV.
1142 /// If BaseOffs is zero, there is no base offset.
1143 /// If HasBaseReg is false, there is no base register.
1144 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
1147 GlobalValue *BaseGV;
1151 AddrMode() : BaseGV(0), BaseOffs(0), HasBaseReg(false), Scale(0) {}
1154 /// Return true if the addressing mode represented by AM is legal for this
1155 /// target, for a load/store of the specified type.
1157 /// The type may be VoidTy, in which case only return true if the addressing
1158 /// mode is legal for a load/store of any legal type. TODO: Handle
1159 /// pre/postinc as well.
1160 virtual bool isLegalAddressingMode(const AddrMode &AM, Type *Ty) const;
1162 /// \brief Return the cost of the scaling factor used in the addressing mode
1163 /// represented by AM for this target, for a load/store of the specified type.
1165 /// If the AM is supported, the return value must be >= 0.
1166 /// If the AM is not supported, it returns a negative value.
1167 /// TODO: Handle pre/postinc as well.
1168 virtual int getScalingFactorCost(const AddrMode &AM, Type *Ty) const {
1169 // Default: assume that any scaling factor used in a legal AM is free.
1170 if (isLegalAddressingMode(AM, Ty)) return 0;
1174 /// Return true if the specified immediate is legal icmp immediate, that is
1175 /// the target has icmp instructions which can compare a register against the
1176 /// immediate without having to materialize the immediate into a register.
1177 virtual bool isLegalICmpImmediate(int64_t) const {
1181 /// Return true if the specified immediate is legal add immediate, that is the
1182 /// target has add instructions which can add a register with the immediate
1183 /// without having to materialize the immediate into a register.
1184 virtual bool isLegalAddImmediate(int64_t) const {
1188 /// Return true if it's free to truncate a value of type Ty1 to type
1189 /// Ty2. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
1190 /// by referencing its sub-register AX.
1191 virtual bool isTruncateFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1195 /// Return true if a truncation from Ty1 to Ty2 is permitted when deciding
1196 /// whether a call is in tail position. Typically this means that both results
1197 /// would be assigned to the same register or stack slot, but it could mean
1198 /// the target performs adequate checks of its own before proceeding with the
1200 virtual bool allowTruncateForTailCall(Type * /*Ty1*/, Type * /*Ty2*/) const {
1204 virtual bool isTruncateFree(EVT /*VT1*/, EVT /*VT2*/) const {
1208 /// Return true if any actual instruction that defines a value of type Ty1
1209 /// implicitly zero-extends the value to Ty2 in the result register.
1211 /// This does not necessarily include registers defined in unknown ways, such
1212 /// as incoming arguments, or copies from unknown virtual registers. Also, if
1213 /// isTruncateFree(Ty2, Ty1) is true, this does not necessarily apply to
1214 /// truncate instructions. e.g. on x86-64, all instructions that define 32-bit
1215 /// values implicit zero-extend the result out to 64 bits.
1216 virtual bool isZExtFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1220 virtual bool isZExtFree(EVT /*VT1*/, EVT /*VT2*/) const {
1224 /// Return true if the target supplies and combines to a paired load
1225 /// two loaded values of type LoadedType next to each other in memory.
1226 /// RequiredAlignment gives the minimal alignment constraints that must be met
1227 /// to be able to select this paired load.
1229 /// This information is *not* used to generate actual paired loads, but it is
1230 /// used to generate a sequence of loads that is easier to combine into a
1232 /// For instance, something like this:
1233 /// a = load i64* addr
1234 /// b = trunc i64 a to i32
1235 /// c = lshr i64 a, 32
1236 /// d = trunc i64 c to i32
1237 /// will be optimized into:
1238 /// b = load i32* addr1
1239 /// d = load i32* addr2
1240 /// Where addr1 = addr2 +/- sizeof(i32).
1242 /// In other words, unless the target performs a post-isel load combining,
1243 /// this information should not be provided because it will generate more
1245 virtual bool hasPairedLoad(Type * /*LoadedType*/,
1246 unsigned & /*RequiredAligment*/) const {
1250 virtual bool hasPairedLoad(EVT /*LoadedType*/,
1251 unsigned & /*RequiredAligment*/) const {
1255 /// Return true if zero-extending the specific node Val to type VT2 is free
1256 /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
1257 /// because it's folded such as X86 zero-extending loads).
1258 virtual bool isZExtFree(SDValue Val, EVT VT2) const {
1259 return isZExtFree(Val.getValueType(), VT2);
1262 /// Return true if an fneg operation is free to the point where it is never
1263 /// worthwhile to replace it with a bitwise operation.
1264 virtual bool isFNegFree(EVT VT) const {
1265 assert(VT.isFloatingPoint());
1269 /// Return true if an fabs operation is free to the point where it is never
1270 /// worthwhile to replace it with a bitwise operation.
1271 virtual bool isFAbsFree(EVT VT) const {
1272 assert(VT.isFloatingPoint());
1276 /// Return true if an FMA operation is faster than a pair of fmul and fadd
1277 /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
1278 /// returns true, otherwise fmuladd is expanded to fmul + fadd.
1280 /// NOTE: This may be called before legalization on types for which FMAs are
1281 /// not legal, but should return true if those types will eventually legalize
1282 /// to types that support FMAs. After legalization, it will only be called on
1283 /// types that support FMAs (via Legal or Custom actions)
1284 virtual bool isFMAFasterThanFMulAndFAdd(EVT) const {
1288 /// Return true if it's profitable to narrow operations of type VT1 to
1289 /// VT2. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
1291 virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
1295 /// \brief Return true if it is beneficial to convert a load of a constant to
1296 /// just the constant itself.
1297 /// On some targets it might be more efficient to use a combination of
1298 /// arithmetic instructions to materialize the constant instead of loading it
1299 /// from a constant pool.
1300 virtual bool shouldConvertConstantLoadToIntImm(const APInt &Imm,
1304 //===--------------------------------------------------------------------===//
1305 // Runtime Library hooks
1308 /// Rename the default libcall routine name for the specified libcall.
1309 void setLibcallName(RTLIB::Libcall Call, const char *Name) {
1310 LibcallRoutineNames[Call] = Name;
1313 /// Get the libcall routine name for the specified libcall.
1314 const char *getLibcallName(RTLIB::Libcall Call) const {
1315 return LibcallRoutineNames[Call];
1318 /// Override the default CondCode to be used to test the result of the
1319 /// comparison libcall against zero.
1320 void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
1321 CmpLibcallCCs[Call] = CC;
1324 /// Get the CondCode that's to be used to test the result of the comparison
1325 /// libcall against zero.
1326 ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
1327 return CmpLibcallCCs[Call];
1330 /// Set the CallingConv that should be used for the specified libcall.
1331 void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
1332 LibcallCallingConvs[Call] = CC;
1335 /// Get the CallingConv that should be used for the specified libcall.
1336 CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
1337 return LibcallCallingConvs[Call];
1340 void getNameWithPrefix(SmallVectorImpl<char> &Name, const GlobalValue *GV,
1341 Mangler &Mang, bool MayAlwaysUsePrivate = false) const;
1342 MCSymbol *getSymbol(const GlobalValue *GV, Mangler &Mang) const;
1345 const TargetMachine &TM;
1346 const DataLayout *DL;
1347 const TargetLoweringObjectFile &TLOF;
1349 /// True if this is a little endian target.
1350 bool IsLittleEndian;
1352 /// Tells the code generator not to expand operations into sequences that use
1353 /// the select operations if possible.
1354 bool SelectIsExpensive;
1356 /// Tells the code generator that the target has multiple (allocatable)
1357 /// condition registers that can be used to store the results of comparisons
1358 /// for use by selects and conditional branches. With multiple condition
1359 /// registers, the code generator will not aggressively sink comparisons into
1360 /// the blocks of their users.
1361 bool HasMultipleConditionRegisters;
1363 /// Tells the code generator not to expand integer divides by constants into a
1364 /// sequence of muls, adds, and shifts. This is a hack until a real cost
1365 /// model is in place. If we ever optimize for size, this will be set to true
1366 /// unconditionally.
1369 /// Tells the code generator to bypass slow divide or remainder
1370 /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
1371 /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
1372 /// div/rem when the operands are positive and less than 256.
1373 DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
1375 /// Tells the code generator that it shouldn't generate srl/add/sra for a
1376 /// signed divide by power of two, and let the target handle it.
1377 bool Pow2DivIsCheap;
1379 /// Tells the code generator that it shouldn't generate extra flow control
1380 /// instructions and should attempt to combine flow control instructions via
1382 bool JumpIsExpensive;
1384 /// This target prefers to use _setjmp to implement llvm.setjmp.
1386 /// Defaults to false.
1387 bool UseUnderscoreSetJmp;
1389 /// This target prefers to use _longjmp to implement llvm.longjmp.
1391 /// Defaults to false.
1392 bool UseUnderscoreLongJmp;
1394 /// Whether the target can generate code for jumptables. If it's not true,
1395 /// then each jumptable must be lowered into if-then-else's.
1396 bool SupportJumpTables;
1398 /// Number of blocks threshold to use jump tables.
1399 int MinimumJumpTableEntries;
1401 /// Information about the contents of the high-bits in boolean values held in
1402 /// a type wider than i1. See getBooleanContents.
1403 BooleanContent BooleanContents;
1405 /// Information about the contents of the high-bits in boolean vector values
1406 /// when the element type is wider than i1. See getBooleanContents.
1407 BooleanContent BooleanVectorContents;
1409 /// The target scheduling preference: shortest possible total cycles or lowest
1411 Sched::Preference SchedPreferenceInfo;
1413 /// The size, in bytes, of the target's jmp_buf buffers
1414 unsigned JumpBufSize;
1416 /// The alignment, in bytes, of the target's jmp_buf buffers
1417 unsigned JumpBufAlignment;
1419 /// The minimum alignment that any argument on the stack needs to have.
1420 unsigned MinStackArgumentAlignment;
1422 /// The minimum function alignment (used when optimizing for size, and to
1423 /// prevent explicitly provided alignment from leading to incorrect code).
1424 unsigned MinFunctionAlignment;
1426 /// The preferred function alignment (used when alignment unspecified and
1427 /// optimizing for speed).
1428 unsigned PrefFunctionAlignment;
1430 /// The preferred loop alignment.
1431 unsigned PrefLoopAlignment;
1433 /// Whether the DAG builder should automatically insert fences and reduce
1434 /// ordering for atomics. (This will be set for for most architectures with
1435 /// weak memory ordering.)
1436 bool InsertFencesForAtomic;
1438 /// If set to a physical register, this specifies the register that
1439 /// llvm.savestack/llvm.restorestack should save and restore.
1440 unsigned StackPointerRegisterToSaveRestore;
1442 /// If set to a physical register, this specifies the register that receives
1443 /// the exception address on entry to a landing pad.
1444 unsigned ExceptionPointerRegister;
1446 /// If set to a physical register, this specifies the register that receives
1447 /// the exception typeid on entry to a landing pad.
1448 unsigned ExceptionSelectorRegister;
1450 /// This indicates the default register class to use for each ValueType the
1451 /// target supports natively.
1452 const TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
1453 unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
1454 MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
1456 /// This indicates the "representative" register class to use for each
1457 /// ValueType the target supports natively. This information is used by the
1458 /// scheduler to track register pressure. By default, the representative
1459 /// register class is the largest legal super-reg register class of the
1460 /// register class of the specified type. e.g. On x86, i8, i16, and i32's
1461 /// representative class would be GR32.
1462 const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
1464 /// This indicates the "cost" of the "representative" register class for each
1465 /// ValueType. The cost is used by the scheduler to approximate register
1467 uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
1469 /// For any value types we are promoting or expanding, this contains the value
1470 /// type that we are changing to. For Expanded types, this contains one step
1471 /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
1472 /// (e.g. i64 -> i16). For types natively supported by the system, this holds
1473 /// the same type (e.g. i32 -> i32).
1474 MVT TransformToType[MVT::LAST_VALUETYPE];
1476 /// For each operation and each value type, keep a LegalizeAction that
1477 /// indicates how instruction selection should deal with the operation. Most
1478 /// operations are Legal (aka, supported natively by the target), but
1479 /// operations that are not should be described. Note that operations on
1480 /// non-legal value types are not described here.
1481 uint8_t OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END];
1483 /// For each load extension type and each value type, keep a LegalizeAction
1484 /// that indicates how instruction selection should deal with a load of a
1485 /// specific value type and extension type.
1486 uint8_t LoadExtActions[MVT::LAST_VALUETYPE][ISD::LAST_LOADEXT_TYPE];
1488 /// For each value type pair keep a LegalizeAction that indicates whether a
1489 /// truncating store of a specific value type and truncating type is legal.
1490 uint8_t TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
1492 /// For each indexed mode and each value type, keep a pair of LegalizeAction
1493 /// that indicates how instruction selection should deal with the load /
1496 /// The first dimension is the value_type for the reference. The second
1497 /// dimension represents the various modes for load store.
1498 uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
1500 /// For each condition code (ISD::CondCode) keep a LegalizeAction that
1501 /// indicates how instruction selection should deal with the condition code.
1503 /// Because each CC action takes up 2 bits, we need to have the array size be
1504 /// large enough to fit all of the value types. This can be done by rounding
1505 /// up the MVT::LAST_VALUETYPE value to the next multiple of 16.
1506 uint32_t CondCodeActions[ISD::SETCC_INVALID][(MVT::LAST_VALUETYPE + 15) / 16];
1508 ValueTypeActionImpl ValueTypeActions;
1512 getTypeConversion(LLVMContext &Context, EVT VT) const {
1513 // If this is a simple type, use the ComputeRegisterProp mechanism.
1514 if (VT.isSimple()) {
1515 MVT SVT = VT.getSimpleVT();
1516 assert((unsigned)SVT.SimpleTy < array_lengthof(TransformToType));
1517 MVT NVT = TransformToType[SVT.SimpleTy];
1518 LegalizeTypeAction LA = ValueTypeActions.getTypeAction(SVT);
1522 ValueTypeActions.getTypeAction(NVT) != TypePromoteInteger)
1523 && "Promote may not follow Expand or Promote");
1525 if (LA == TypeSplitVector)
1526 return LegalizeKind(LA, EVT::getVectorVT(Context,
1527 SVT.getVectorElementType(),
1528 SVT.getVectorNumElements()/2));
1529 if (LA == TypeScalarizeVector)
1530 return LegalizeKind(LA, SVT.getVectorElementType());
1531 return LegalizeKind(LA, NVT);
1534 // Handle Extended Scalar Types.
1535 if (!VT.isVector()) {
1536 assert(VT.isInteger() && "Float types must be simple");
1537 unsigned BitSize = VT.getSizeInBits();
1538 // First promote to a power-of-two size, then expand if necessary.
1539 if (BitSize < 8 || !isPowerOf2_32(BitSize)) {
1540 EVT NVT = VT.getRoundIntegerType(Context);
1541 assert(NVT != VT && "Unable to round integer VT");
1542 LegalizeKind NextStep = getTypeConversion(Context, NVT);
1543 // Avoid multi-step promotion.
1544 if (NextStep.first == TypePromoteInteger) return NextStep;
1545 // Return rounded integer type.
1546 return LegalizeKind(TypePromoteInteger, NVT);
1549 return LegalizeKind(TypeExpandInteger,
1550 EVT::getIntegerVT(Context, VT.getSizeInBits()/2));
1553 // Handle vector types.
1554 unsigned NumElts = VT.getVectorNumElements();
1555 EVT EltVT = VT.getVectorElementType();
1557 // Vectors with only one element are always scalarized.
1559 return LegalizeKind(TypeScalarizeVector, EltVT);
1561 // Try to widen vector elements until the element type is a power of two and
1562 // promote it to a legal type later on, for example:
1563 // <3 x i8> -> <4 x i8> -> <4 x i32>
1564 if (EltVT.isInteger()) {
1565 // Vectors with a number of elements that is not a power of two are always
1566 // widened, for example <3 x i8> -> <4 x i8>.
1567 if (!VT.isPow2VectorType()) {
1568 NumElts = (unsigned)NextPowerOf2(NumElts);
1569 EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts);
1570 return LegalizeKind(TypeWidenVector, NVT);
1573 // Examine the element type.
1574 LegalizeKind LK = getTypeConversion(Context, EltVT);
1576 // If type is to be expanded, split the vector.
1577 // <4 x i140> -> <2 x i140>
1578 if (LK.first == TypeExpandInteger)
1579 return LegalizeKind(TypeSplitVector,
1580 EVT::getVectorVT(Context, EltVT, NumElts / 2));
1582 // Promote the integer element types until a legal vector type is found
1583 // or until the element integer type is too big. If a legal type was not
1584 // found, fallback to the usual mechanism of widening/splitting the
1586 EVT OldEltVT = EltVT;
1588 // Increase the bitwidth of the element to the next pow-of-two
1589 // (which is greater than 8 bits).
1590 EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits()
1591 ).getRoundIntegerType(Context);
1593 // Stop trying when getting a non-simple element type.
1594 // Note that vector elements may be greater than legal vector element
1595 // types. Example: X86 XMM registers hold 64bit element on 32bit
1597 if (!EltVT.isSimple()) break;
1599 // Build a new vector type and check if it is legal.
1600 MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1601 // Found a legal promoted vector type.
1602 if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal)
1603 return LegalizeKind(TypePromoteInteger,
1604 EVT::getVectorVT(Context, EltVT, NumElts));
1607 // Reset the type to the unexpanded type if we did not find a legal vector
1608 // type with a promoted vector element type.
1612 // Try to widen the vector until a legal type is found.
1613 // If there is no wider legal type, split the vector.
1615 // Round up to the next power of 2.
1616 NumElts = (unsigned)NextPowerOf2(NumElts);
1618 // If there is no simple vector type with this many elements then there
1619 // cannot be a larger legal vector type. Note that this assumes that
1620 // there are no skipped intermediate vector types in the simple types.
1621 if (!EltVT.isSimple()) break;
1622 MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1623 if (LargerVector == MVT()) break;
1625 // If this type is legal then widen the vector.
1626 if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal)
1627 return LegalizeKind(TypeWidenVector, LargerVector);
1630 // Widen odd vectors to next power of two.
1631 if (!VT.isPow2VectorType()) {
1632 EVT NVT = VT.getPow2VectorType(Context);
1633 return LegalizeKind(TypeWidenVector, NVT);
1636 // Vectors with illegal element types are expanded.
1637 EVT NVT = EVT::getVectorVT(Context, EltVT, VT.getVectorNumElements() / 2);
1638 return LegalizeKind(TypeSplitVector, NVT);
1642 std::vector<std::pair<MVT, const TargetRegisterClass*> > AvailableRegClasses;
1644 /// Targets can specify ISD nodes that they would like PerformDAGCombine
1645 /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
1648 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
1650 /// For operations that must be promoted to a specific type, this holds the
1651 /// destination type. This map should be sparse, so don't hold it as an
1654 /// Targets add entries to this map with AddPromotedToType(..), clients access
1655 /// this with getTypeToPromoteTo(..).
1656 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
1659 /// Stores the name each libcall.
1660 const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
1662 /// The ISD::CondCode that should be used to test the result of each of the
1663 /// comparison libcall against zero.
1664 ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
1666 /// Stores the CallingConv that should be used for each libcall.
1667 CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
1670 /// \brief Specify maximum number of store instructions per memset call.
1672 /// When lowering \@llvm.memset this field specifies the maximum number of
1673 /// store operations that may be substituted for the call to memset. Targets
1674 /// must set this value based on the cost threshold for that target. Targets
1675 /// should assume that the memset will be done using as many of the largest
1676 /// store operations first, followed by smaller ones, if necessary, per
1677 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
1678 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
1679 /// store. This only applies to setting a constant array of a constant size.
1680 unsigned MaxStoresPerMemset;
1682 /// Maximum number of stores operations that may be substituted for the call
1683 /// to memset, used for functions with OptSize attribute.
1684 unsigned MaxStoresPerMemsetOptSize;
1686 /// \brief Specify maximum bytes of store instructions per memcpy call.
1688 /// When lowering \@llvm.memcpy this field specifies the maximum number of
1689 /// store operations that may be substituted for a call to memcpy. Targets
1690 /// must set this value based on the cost threshold for that target. Targets
1691 /// should assume that the memcpy will be done using as many of the largest
1692 /// store operations first, followed by smaller ones, if necessary, per
1693 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
1694 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
1695 /// and one 1-byte store. This only applies to copying a constant array of
1697 unsigned MaxStoresPerMemcpy;
1699 /// Maximum number of store operations that may be substituted for a call to
1700 /// memcpy, used for functions with OptSize attribute.
1701 unsigned MaxStoresPerMemcpyOptSize;
1703 /// \brief Specify maximum bytes of store instructions per memmove call.
1705 /// When lowering \@llvm.memmove this field specifies the maximum number of
1706 /// store instructions that may be substituted for a call to memmove. Targets
1707 /// must set this value based on the cost threshold for that target. Targets
1708 /// should assume that the memmove will be done using as many of the largest
1709 /// store operations first, followed by smaller ones, if necessary, per
1710 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
1711 /// with 8-bit alignment would result in nine 1-byte stores. This only
1712 /// applies to copying a constant array of constant size.
1713 unsigned MaxStoresPerMemmove;
1715 /// Maximum number of store instructions that may be substituted for a call to
1716 /// memmove, used for functions with OpSize attribute.
1717 unsigned MaxStoresPerMemmoveOptSize;
1719 /// Tells the code generator that select is more expensive than a branch if
1720 /// the branch is usually predicted right.
1721 bool PredictableSelectIsExpensive;
1724 /// Return true if the value types that can be represented by the specified
1725 /// register class are all legal.
1726 bool isLegalRC(const TargetRegisterClass *RC) const;
1728 /// Replace/modify any TargetFrameIndex operands with a targte-dependent
1729 /// sequence of memory operands that is recognized by PrologEpilogInserter.
1730 MachineBasicBlock *emitPatchPoint(MachineInstr *MI, MachineBasicBlock *MBB) const;
1733 /// This class defines information used to lower LLVM code to legal SelectionDAG
1734 /// operators that the target instruction selector can accept natively.
1736 /// This class also defines callbacks that targets must implement to lower
1737 /// target-specific constructs to SelectionDAG operators.
1738 class TargetLowering : public TargetLoweringBase {
1739 TargetLowering(const TargetLowering&) LLVM_DELETED_FUNCTION;
1740 void operator=(const TargetLowering&) LLVM_DELETED_FUNCTION;
1743 /// NOTE: The constructor takes ownership of TLOF.
1744 explicit TargetLowering(const TargetMachine &TM,
1745 const TargetLoweringObjectFile *TLOF);
1747 /// Returns true by value, base pointer and offset pointer and addressing mode
1748 /// by reference if the node's address can be legally represented as
1749 /// pre-indexed load / store address.
1750 virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
1751 SDValue &/*Offset*/,
1752 ISD::MemIndexedMode &/*AM*/,
1753 SelectionDAG &/*DAG*/) const {
1757 /// Returns true by value, base pointer and offset pointer and addressing mode
1758 /// by reference if this node can be combined with a load / store to form a
1759 /// post-indexed load / store.
1760 virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
1762 SDValue &/*Offset*/,
1763 ISD::MemIndexedMode &/*AM*/,
1764 SelectionDAG &/*DAG*/) const {
1768 /// Return the entry encoding for a jump table in the current function. The
1769 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
1770 virtual unsigned getJumpTableEncoding() const;
1772 virtual const MCExpr *
1773 LowerCustomJumpTableEntry(const MachineJumpTableInfo * /*MJTI*/,
1774 const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
1775 MCContext &/*Ctx*/) const {
1776 llvm_unreachable("Need to implement this hook if target has custom JTIs");
1779 /// Returns relocation base for the given PIC jumptable.
1780 virtual SDValue getPICJumpTableRelocBase(SDValue Table,
1781 SelectionDAG &DAG) const;
1783 /// This returns the relocation base for the given PIC jumptable, the same as
1784 /// getPICJumpTableRelocBase, but as an MCExpr.
1785 virtual const MCExpr *
1786 getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
1787 unsigned JTI, MCContext &Ctx) const;
1789 /// Return true if folding a constant offset with the given GlobalAddress is
1790 /// legal. It is frequently not legal in PIC relocation models.
1791 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
1793 bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
1794 SDValue &Chain) const;
1796 void softenSetCCOperands(SelectionDAG &DAG, EVT VT,
1797 SDValue &NewLHS, SDValue &NewRHS,
1798 ISD::CondCode &CCCode, SDLoc DL) const;
1800 /// Returns a pair of (return value, chain).
1801 std::pair<SDValue, SDValue> makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC,
1802 EVT RetVT, const SDValue *Ops,
1803 unsigned NumOps, bool isSigned,
1804 SDLoc dl, bool doesNotReturn = false,
1805 bool isReturnValueUsed = true) const;
1807 //===--------------------------------------------------------------------===//
1808 // TargetLowering Optimization Methods
1811 /// A convenience struct that encapsulates a DAG, and two SDValues for
1812 /// returning information from TargetLowering to its clients that want to
1814 struct TargetLoweringOpt {
1821 explicit TargetLoweringOpt(SelectionDAG &InDAG,
1823 DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
1825 bool LegalTypes() const { return LegalTys; }
1826 bool LegalOperations() const { return LegalOps; }
1828 bool CombineTo(SDValue O, SDValue N) {
1834 /// Check to see if the specified operand of the specified instruction is a
1835 /// constant integer. If so, check to see if there are any bits set in the
1836 /// constant that are not demanded. If so, shrink the constant and return
1838 bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded);
1840 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. This
1841 /// uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
1842 /// generalized for targets with other types of implicit widening casts.
1843 bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
1847 /// Look at Op. At this point, we know that only the DemandedMask bits of the
1848 /// result of Op are ever used downstream. If we can use this information to
1849 /// simplify Op, create a new simplified DAG node and return true, returning
1850 /// the original and new nodes in Old and New. Otherwise, analyze the
1851 /// expression and return a mask of KnownOne and KnownZero bits for the
1852 /// expression (used to simplify the caller). The KnownZero/One bits may only
1853 /// be accurate for those bits in the DemandedMask.
1854 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
1855 APInt &KnownZero, APInt &KnownOne,
1856 TargetLoweringOpt &TLO, unsigned Depth = 0) const;
1858 /// Determine which of the bits specified in Mask are known to be either zero
1859 /// or one and return them in the KnownZero/KnownOne bitsets.
1860 virtual void computeMaskedBitsForTargetNode(const SDValue Op,
1863 const SelectionDAG &DAG,
1864 unsigned Depth = 0) const;
1866 /// This method can be implemented by targets that want to expose additional
1867 /// information about sign bits to the DAG Combiner.
1868 virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
1869 unsigned Depth = 0) const;
1871 struct DAGCombinerInfo {
1872 void *DC; // The DAG Combiner object.
1874 bool CalledByLegalizer;
1878 DAGCombinerInfo(SelectionDAG &dag, CombineLevel level, bool cl, void *dc)
1879 : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
1881 bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
1882 bool isBeforeLegalizeOps() const { return Level < AfterLegalizeVectorOps; }
1883 bool isAfterLegalizeVectorOps() const {
1884 return Level == AfterLegalizeDAG;
1886 CombineLevel getDAGCombineLevel() { return Level; }
1887 bool isCalledByLegalizer() const { return CalledByLegalizer; }
1889 void AddToWorklist(SDNode *N);
1890 void RemoveFromWorklist(SDNode *N);
1891 SDValue CombineTo(SDNode *N, const std::vector<SDValue> &To,
1893 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
1894 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
1896 void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
1899 /// Try to simplify a setcc built with the specified operands and cc. If it is
1900 /// unable to simplify it, return a null SDValue.
1901 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
1902 ISD::CondCode Cond, bool foldBooleans,
1903 DAGCombinerInfo &DCI, SDLoc dl) const;
1905 /// Returns true (and the GlobalValue and the offset) if the node is a
1906 /// GlobalAddress + offset.
1908 isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
1910 /// This method will be invoked for all target nodes and for any
1911 /// target-independent nodes that the target has registered with invoke it
1914 /// The semantics are as follows:
1916 /// SDValue.Val == 0 - No change was made
1917 /// SDValue.Val == N - N was replaced, is dead, and is already handled.
1918 /// otherwise - N should be replaced by the returned Operand.
1920 /// In addition, methods provided by DAGCombinerInfo may be used to perform
1921 /// more complex transformations.
1923 virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
1925 /// Return true if the target has native support for the specified value type
1926 /// and it is 'desirable' to use the type for the given node type. e.g. On x86
1927 /// i16 is legal, but undesirable since i16 instruction encodings are longer
1928 /// and some i16 instructions are slow.
1929 virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
1930 // By default, assume all legal types are desirable.
1931 return isTypeLegal(VT);
1934 /// Return true if it is profitable for dag combiner to transform a floating
1935 /// point op of specified opcode to a equivalent op of an integer
1936 /// type. e.g. f32 load -> i32 load can be profitable on ARM.
1937 virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
1942 /// This method query the target whether it is beneficial for dag combiner to
1943 /// promote the specified node. If true, it should return the desired
1944 /// promotion type by reference.
1945 virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
1949 //===--------------------------------------------------------------------===//
1950 // Lowering methods - These methods must be implemented by targets so that
1951 // the SelectionDAGBuilder code knows how to lower these.
1954 /// This hook must be implemented to lower the incoming (formal) arguments,
1955 /// described by the Ins array, into the specified DAG. The implementation
1956 /// should fill in the InVals array with legal-type argument values, and
1957 /// return the resulting token chain value.
1960 LowerFormalArguments(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
1962 const SmallVectorImpl<ISD::InputArg> &/*Ins*/,
1963 SDLoc /*dl*/, SelectionDAG &/*DAG*/,
1964 SmallVectorImpl<SDValue> &/*InVals*/) const {
1965 llvm_unreachable("Not Implemented");
1968 struct ArgListEntry {
1977 bool isInAlloca : 1;
1978 bool isReturned : 1;
1981 ArgListEntry() : isSExt(false), isZExt(false), isInReg(false),
1982 isSRet(false), isNest(false), isByVal(false), isInAlloca(false),
1983 isReturned(false), Alignment(0) { }
1985 void setAttributes(ImmutableCallSite *CS, unsigned AttrIdx);
1987 typedef std::vector<ArgListEntry> ArgListTy;
1989 /// This structure contains all information that is necessary for lowering
1990 /// calls. It is passed to TLI::LowerCallTo when the SelectionDAG builder
1991 /// needs to lower a call, and targets will see this struct in their LowerCall
1993 struct CallLoweringInfo {
2000 bool DoesNotReturn : 1;
2001 bool IsReturnValueUsed : 1;
2003 // IsTailCall should be modified by implementations of
2004 // TargetLowering::LowerCall that perform tail call conversions.
2007 unsigned NumFixedArgs;
2008 CallingConv::ID CallConv;
2013 ImmutableCallSite *CS;
2014 SmallVector<ISD::OutputArg, 32> Outs;
2015 SmallVector<SDValue, 32> OutVals;
2016 SmallVector<ISD::InputArg, 32> Ins;
2019 /// Constructs a call lowering context based on the ImmutableCallSite \p cs.
2020 CallLoweringInfo(SDValue chain, Type *retTy,
2021 FunctionType *FTy, bool isTailCall, SDValue callee,
2022 ArgListTy &args, SelectionDAG &dag, SDLoc dl,
2023 ImmutableCallSite &cs)
2024 : Chain(chain), RetTy(retTy), RetSExt(cs.paramHasAttr(0, Attribute::SExt)),
2025 RetZExt(cs.paramHasAttr(0, Attribute::ZExt)), IsVarArg(FTy->isVarArg()),
2026 IsInReg(cs.paramHasAttr(0, Attribute::InReg)),
2027 DoesNotReturn(cs.doesNotReturn()),
2028 IsReturnValueUsed(!cs.getInstruction()->use_empty()),
2029 IsTailCall(isTailCall), NumFixedArgs(FTy->getNumParams()),
2030 CallConv(cs.getCallingConv()), Callee(callee), Args(args), DAG(dag),
2033 /// Constructs a call lowering context based on the provided call
2035 CallLoweringInfo(SDValue chain, Type *retTy, bool retSExt, bool retZExt,
2036 bool isVarArg, bool isInReg, unsigned numFixedArgs,
2037 CallingConv::ID callConv, bool isTailCall,
2038 bool doesNotReturn, bool isReturnValueUsed, SDValue callee,
2039 ArgListTy &args, SelectionDAG &dag, SDLoc dl)
2040 : Chain(chain), RetTy(retTy), RetSExt(retSExt), RetZExt(retZExt),
2041 IsVarArg(isVarArg), IsInReg(isInReg), DoesNotReturn(doesNotReturn),
2042 IsReturnValueUsed(isReturnValueUsed), IsTailCall(isTailCall),
2043 NumFixedArgs(numFixedArgs), CallConv(callConv), Callee(callee),
2044 Args(args), DAG(dag), DL(dl), CS(NULL) {}
2047 /// This function lowers an abstract call to a function into an actual call.
2048 /// This returns a pair of operands. The first element is the return value
2049 /// for the function (if RetTy is not VoidTy). The second element is the
2050 /// outgoing token chain. It calls LowerCall to do the actual lowering.
2051 std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
2053 /// This hook must be implemented to lower calls into the the specified
2054 /// DAG. The outgoing arguments to the call are described by the Outs array,
2055 /// and the values to be returned by the call are described by the Ins
2056 /// array. The implementation should fill in the InVals array with legal-type
2057 /// return values from the call, and return the resulting token chain value.
2059 LowerCall(CallLoweringInfo &/*CLI*/,
2060 SmallVectorImpl<SDValue> &/*InVals*/) const {
2061 llvm_unreachable("Not Implemented");
2064 /// Target-specific cleanup for formal ByVal parameters.
2065 virtual void HandleByVal(CCState *, unsigned &, unsigned) const {}
2067 /// This hook should be implemented to check whether the return values
2068 /// described by the Outs array can fit into the return registers. If false
2069 /// is returned, an sret-demotion is performed.
2070 virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
2071 MachineFunction &/*MF*/, bool /*isVarArg*/,
2072 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
2073 LLVMContext &/*Context*/) const
2075 // Return true by default to get preexisting behavior.
2079 /// This hook must be implemented to lower outgoing return values, described
2080 /// by the Outs array, into the specified DAG. The implementation should
2081 /// return the resulting token chain value.
2083 LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
2085 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
2086 const SmallVectorImpl<SDValue> &/*OutVals*/,
2087 SDLoc /*dl*/, SelectionDAG &/*DAG*/) const {
2088 llvm_unreachable("Not Implemented");
2091 /// Return true if result of the specified node is used by a return node
2092 /// only. It also compute and return the input chain for the tail call.
2094 /// This is used to determine whether it is possible to codegen a libcall as
2095 /// tail call at legalization time.
2096 virtual bool isUsedByReturnOnly(SDNode *, SDValue &/*Chain*/) const {
2100 /// Return true if the target may be able emit the call instruction as a tail
2101 /// call. This is used by optimization passes to determine if it's profitable
2102 /// to duplicate return instructions to enable tailcall optimization.
2103 virtual bool mayBeEmittedAsTailCall(CallInst *) const {
2107 /// Return the type that should be used to zero or sign extend a
2108 /// zeroext/signext integer argument or return value. FIXME: Most C calling
2109 /// convention requires the return type to be promoted, but this is not true
2110 /// all the time, e.g. i1 on x86-64. It is also not necessary for non-C
2111 /// calling conventions. The frontend should handle this and include all of
2112 /// the necessary information.
2113 virtual MVT getTypeForExtArgOrReturn(MVT VT,
2114 ISD::NodeType /*ExtendKind*/) const {
2115 MVT MinVT = getRegisterType(MVT::i32);
2116 return VT.bitsLT(MinVT) ? MinVT : VT;
2119 /// Returns a 0 terminated array of registers that can be safely used as
2120 /// scratch registers.
2121 virtual const uint16_t *getScratchRegisters(CallingConv::ID CC) const {
2125 /// This callback is used to prepare for a volatile or atomic load.
2126 /// It takes a chain node as input and returns the chain for the load itself.
2128 /// Having a callback like this is necessary for targets like SystemZ,
2129 /// which allows a CPU to reuse the result of a previous load indefinitely,
2130 /// even if a cache-coherent store is performed by another CPU. The default
2131 /// implementation does nothing.
2132 virtual SDValue prepareVolatileOrAtomicLoad(SDValue Chain, SDLoc DL,
2133 SelectionDAG &DAG) const {
2137 /// This callback is invoked by the type legalizer to legalize nodes with an
2138 /// illegal operand type but legal result types. It replaces the
2139 /// LowerOperation callback in the type Legalizer. The reason we can not do
2140 /// away with LowerOperation entirely is that LegalizeDAG isn't yet ready to
2141 /// use this callback.
2143 /// TODO: Consider merging with ReplaceNodeResults.
2145 /// The target places new result values for the node in Results (their number
2146 /// and types must exactly match those of the original return values of
2147 /// the node), or leaves Results empty, which indicates that the node is not
2148 /// to be custom lowered after all.
2149 /// The default implementation calls LowerOperation.
2150 virtual void LowerOperationWrapper(SDNode *N,
2151 SmallVectorImpl<SDValue> &Results,
2152 SelectionDAG &DAG) const;
2154 /// This callback is invoked for operations that are unsupported by the
2155 /// target, which are registered to use 'custom' lowering, and whose defined
2156 /// values are all legal. If the target has no operations that require custom
2157 /// lowering, it need not implement this. The default implementation of this
2159 virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
2161 /// This callback is invoked when a node result type is illegal for the
2162 /// target, and the operation was registered to use 'custom' lowering for that
2163 /// result type. The target places new result values for the node in Results
2164 /// (their number and types must exactly match those of the original return
2165 /// values of the node), or leaves Results empty, which indicates that the
2166 /// node is not to be custom lowered after all.
2168 /// If the target has no operations that require custom lowering, it need not
2169 /// implement this. The default implementation aborts.
2170 virtual void ReplaceNodeResults(SDNode * /*N*/,
2171 SmallVectorImpl<SDValue> &/*Results*/,
2172 SelectionDAG &/*DAG*/) const {
2173 llvm_unreachable("ReplaceNodeResults not implemented for this target!");
2176 /// This method returns the name of a target specific DAG node.
2177 virtual const char *getTargetNodeName(unsigned Opcode) const;
2179 /// This method returns a target specific FastISel object, or null if the
2180 /// target does not support "fast" ISel.
2181 virtual FastISel *createFastISel(FunctionLoweringInfo &,
2182 const TargetLibraryInfo *) const {
2187 bool verifyReturnAddressArgumentIsConstant(SDValue Op,
2188 SelectionDAG &DAG) const;
2190 //===--------------------------------------------------------------------===//
2191 // Inline Asm Support hooks
2194 /// This hook allows the target to expand an inline asm call to be explicit
2195 /// llvm code if it wants to. This is useful for turning simple inline asms
2196 /// into LLVM intrinsics, which gives the compiler more information about the
2197 /// behavior of the code.
2198 virtual bool ExpandInlineAsm(CallInst *) const {
2202 enum ConstraintType {
2203 C_Register, // Constraint represents specific register(s).
2204 C_RegisterClass, // Constraint represents any of register(s) in class.
2205 C_Memory, // Memory constraint.
2206 C_Other, // Something else.
2207 C_Unknown // Unsupported constraint.
2210 enum ConstraintWeight {
2212 CW_Invalid = -1, // No match.
2213 CW_Okay = 0, // Acceptable.
2214 CW_Good = 1, // Good weight.
2215 CW_Better = 2, // Better weight.
2216 CW_Best = 3, // Best weight.
2218 // Well-known weights.
2219 CW_SpecificReg = CW_Okay, // Specific register operands.
2220 CW_Register = CW_Good, // Register operands.
2221 CW_Memory = CW_Better, // Memory operands.
2222 CW_Constant = CW_Best, // Constant operand.
2223 CW_Default = CW_Okay // Default or don't know type.
2226 /// This contains information for each constraint that we are lowering.
2227 struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
2228 /// This contains the actual string for the code, like "m". TargetLowering
2229 /// picks the 'best' code from ConstraintInfo::Codes that most closely
2230 /// matches the operand.
2231 std::string ConstraintCode;
2233 /// Information about the constraint code, e.g. Register, RegisterClass,
2234 /// Memory, Other, Unknown.
2235 TargetLowering::ConstraintType ConstraintType;
2237 /// If this is the result output operand or a clobber, this is null,
2238 /// otherwise it is the incoming operand to the CallInst. This gets
2239 /// modified as the asm is processed.
2240 Value *CallOperandVal;
2242 /// The ValueType for the operand value.
2245 /// Return true of this is an input operand that is a matching constraint
2247 bool isMatchingInputConstraint() const;
2249 /// If this is an input matching constraint, this method returns the output
2250 /// operand it matches.
2251 unsigned getMatchedOperand() const;
2253 /// Copy constructor for copying from an AsmOperandInfo.
2254 AsmOperandInfo(const AsmOperandInfo &info)
2255 : InlineAsm::ConstraintInfo(info),
2256 ConstraintCode(info.ConstraintCode),
2257 ConstraintType(info.ConstraintType),
2258 CallOperandVal(info.CallOperandVal),
2259 ConstraintVT(info.ConstraintVT) {
2262 /// Copy constructor for copying from a ConstraintInfo.
2263 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
2264 : InlineAsm::ConstraintInfo(info),
2265 ConstraintType(TargetLowering::C_Unknown),
2266 CallOperandVal(0), ConstraintVT(MVT::Other) {
2270 typedef std::vector<AsmOperandInfo> AsmOperandInfoVector;
2272 /// Split up the constraint string from the inline assembly value into the
2273 /// specific constraints and their prefixes, and also tie in the associated
2274 /// operand values. If this returns an empty vector, and if the constraint
2275 /// string itself isn't empty, there was an error parsing.
2276 virtual AsmOperandInfoVector ParseConstraints(ImmutableCallSite CS) const;
2278 /// Examine constraint type and operand type and determine a weight value.
2279 /// The operand object must already have been set up with the operand type.
2280 virtual ConstraintWeight getMultipleConstraintMatchWeight(
2281 AsmOperandInfo &info, int maIndex) const;
2283 /// Examine constraint string and operand type and determine a weight value.
2284 /// The operand object must already have been set up with the operand type.
2285 virtual ConstraintWeight getSingleConstraintMatchWeight(
2286 AsmOperandInfo &info, const char *constraint) const;
2288 /// Determines the constraint code and constraint type to use for the specific
2289 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
2290 /// If the actual operand being passed in is available, it can be passed in as
2291 /// Op, otherwise an empty SDValue can be passed.
2292 virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
2294 SelectionDAG *DAG = 0) const;
2296 /// Given a constraint, return the type of constraint it is for this target.
2297 virtual ConstraintType getConstraintType(const std::string &Constraint) const;
2299 /// Given a physical register constraint (e.g. {edx}), return the register
2300 /// number and the register class for the register.
2302 /// Given a register class constraint, like 'r', if this corresponds directly
2303 /// to an LLVM register class, return a register of 0 and the register class
2306 /// This should only be used for C_Register constraints. On error, this
2307 /// returns a register number of 0 and a null register class pointer..
2308 virtual std::pair<unsigned, const TargetRegisterClass*>
2309 getRegForInlineAsmConstraint(const std::string &Constraint,
2312 /// Try to replace an X constraint, which matches anything, with another that
2313 /// has more specific requirements based on the type of the corresponding
2314 /// operand. This returns null if there is no replacement to make.
2315 virtual const char *LowerXConstraint(EVT ConstraintVT) const;
2317 /// Lower the specified operand into the Ops vector. If it is invalid, don't
2318 /// add anything to Ops.
2319 virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
2320 std::vector<SDValue> &Ops,
2321 SelectionDAG &DAG) const;
2323 //===--------------------------------------------------------------------===//
2324 // Div utility functions
2326 SDValue BuildExactSDIV(SDValue Op1, SDValue Op2, SDLoc dl,
2327 SelectionDAG &DAG) const;
2328 SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
2329 std::vector<SDNode*> *Created) const;
2330 SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
2331 std::vector<SDNode*> *Created) const;
2333 //===--------------------------------------------------------------------===//
2334 // Instruction Emitting Hooks
2337 /// This method should be implemented by targets that mark instructions with
2338 /// the 'usesCustomInserter' flag. These instructions are special in various
2339 /// ways, which require special support to insert. The specified MachineInstr
2340 /// is created but not inserted into any basic blocks, and this method is
2341 /// called to expand it into a sequence of instructions, potentially also
2342 /// creating new basic blocks and control flow.
2343 virtual MachineBasicBlock *
2344 EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const;
2346 /// This method should be implemented by targets that mark instructions with
2347 /// the 'hasPostISelHook' flag. These instructions must be adjusted after
2348 /// instruction selection by target hooks. e.g. To fill in optional defs for
2349 /// ARM 's' setting instructions.
2351 AdjustInstrPostInstrSelection(MachineInstr *MI, SDNode *Node) const;
2354 /// Given an LLVM IR type and return type attributes, compute the return value
2355 /// EVTs and flags, and optionally also the offsets, if the return value is
2356 /// being lowered to memory.
2357 void GetReturnInfo(Type* ReturnType, AttributeSet attr,
2358 SmallVectorImpl<ISD::OutputArg> &Outs,
2359 const TargetLowering &TLI);
2361 } // end llvm namespace