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 //===----------------------------------------------------------------------===//
10 // This file describes how to lower LLVM code to machine code. This has two
13 // 1. Which ValueTypes are natively supported by the target.
14 // 2. Which operations are supported for supported ValueTypes.
15 // 3. Cost thresholds for alternative implementations of certain operations.
17 // In addition it has a few other components, like information about FP
20 //===----------------------------------------------------------------------===//
22 #ifndef LLVM_TARGET_TARGETLOWERING_H
23 #define LLVM_TARGET_TARGETLOWERING_H
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/AddressingMode.h"
27 #include "llvm/Attributes.h"
28 #include "llvm/CallingConv.h"
29 #include "llvm/CodeGen/RuntimeLibcalls.h"
30 #include "llvm/CodeGen/SelectionDAGNodes.h"
31 #include "llvm/InlineAsm.h"
32 #include "llvm/Support/CallSite.h"
33 #include "llvm/Support/DebugLoc.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;
53 template<typename T> class SmallVectorImpl;
55 class TargetRegisterClass;
56 class TargetLibraryInfo;
57 class TargetLoweringObjectFile;
62 None, // No preference
63 Source, // Follow source order.
64 RegPressure, // Scheduling for lowest register pressure.
65 Hybrid, // Scheduling for both latency and register pressure.
66 ILP, // Scheduling for ILP in low register pressure mode.
67 VLIW // Scheduling for VLIW targets.
72 //===----------------------------------------------------------------------===//
73 /// TargetLowering - This class defines information used to lower LLVM code to
74 /// legal SelectionDAG operators that the target instruction selector can accept
77 /// This class also defines callbacks that targets must implement to lower
78 /// target-specific constructs to SelectionDAG operators.
80 class TargetLowering {
81 TargetLowering(const TargetLowering&) LLVM_DELETED_FUNCTION;
82 void operator=(const TargetLowering&) LLVM_DELETED_FUNCTION;
84 /// LegalizeAction - This enum indicates whether operations are valid for a
85 /// target, and if not, what action should be used to make them valid.
87 Legal, // The target natively supports this operation.
88 Promote, // This operation should be executed in a larger type.
89 Expand, // Try to expand this to other ops, otherwise use a libcall.
90 Custom // Use the LowerOperation hook to implement custom lowering.
93 /// LegalizeTypeAction - This enum indicates whether a types are legal for a
94 /// target, and if not, what action should be used to make them valid.
95 enum LegalizeTypeAction {
96 TypeLegal, // The target natively supports this type.
97 TypePromoteInteger, // Replace this integer with a larger one.
98 TypeExpandInteger, // Split this integer into two of half the size.
99 TypeSoftenFloat, // Convert this float to a same size integer type.
100 TypeExpandFloat, // Split this float into two of half the size.
101 TypeScalarizeVector, // Replace this one-element vector with its element.
102 TypeSplitVector, // Split this vector into two of half the size.
103 TypeWidenVector // This vector should be widened into a larger vector.
106 /// LegalizeKind holds the legalization kind that needs to happen to EVT
107 /// in order to type-legalize it.
108 typedef std::pair<LegalizeTypeAction, EVT> LegalizeKind;
110 enum BooleanContent { // How the target represents true/false values.
111 UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
112 ZeroOrOneBooleanContent, // All bits zero except for bit 0.
113 ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
116 enum SelectSupportKind {
117 ScalarValSelect, // The target supports scalar selects (ex: cmov).
118 ScalarCondVectorVal, // The target supports selects with a scalar condition
119 // and vector values (ex: cmov).
120 VectorMaskSelect // The target supports vector selects with a vector
121 // mask (ex: x86 blends).
124 static ISD::NodeType getExtendForContent(BooleanContent Content) {
126 case UndefinedBooleanContent:
127 // Extend by adding rubbish bits.
128 return ISD::ANY_EXTEND;
129 case ZeroOrOneBooleanContent:
130 // Extend by adding zero bits.
131 return ISD::ZERO_EXTEND;
132 case ZeroOrNegativeOneBooleanContent:
133 // Extend by copying the sign bit.
134 return ISD::SIGN_EXTEND;
136 llvm_unreachable("Invalid content kind");
139 /// NOTE: The constructor takes ownership of TLOF.
140 explicit TargetLowering(const TargetMachine &TM,
141 const TargetLoweringObjectFile *TLOF);
142 virtual ~TargetLowering();
144 const TargetMachine &getTargetMachine() const { return TM; }
145 const DataLayout *getDataLayout() const { return TD; }
146 const TargetLoweringObjectFile &getObjFileLowering() const { return TLOF; }
148 bool isBigEndian() const { return !IsLittleEndian; }
149 bool isLittleEndian() const { return IsLittleEndian; }
150 // Return the pointer type for the given address space, defaults to
151 // the pointer type from the data layout.
152 // FIXME: The default needs to be removed once all the code is updated.
153 virtual MVT getPointerTy(uint32_t AS = 0) const { return PointerTy; }
154 virtual MVT getShiftAmountTy(EVT LHSTy) const;
156 /// isSelectExpensive - Return true if the select operation is expensive for
158 bool isSelectExpensive() const { return SelectIsExpensive; }
160 virtual bool isSelectSupported(SelectSupportKind kind) const { return true; }
162 /// shouldSplitVectorElementType - Return true if a vector of the given type
163 /// should be split (TypeSplitVector) instead of promoted
164 /// (TypePromoteInteger) during type legalization.
165 virtual bool shouldSplitVectorElementType(EVT VT) const { return false; }
167 /// isIntDivCheap() - Return true if integer divide is usually cheaper than
168 /// a sequence of several shifts, adds, and multiplies for this target.
169 bool isIntDivCheap() const { return IntDivIsCheap; }
171 /// isSlowDivBypassed - Returns true if target has indicated at least one
172 /// type should be bypassed.
173 bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
175 /// getBypassSlowDivTypes - Returns map of slow types for division or
176 /// remainder with corresponding fast types
177 const DenseMap<unsigned int, unsigned int> &getBypassSlowDivWidths() const {
178 return BypassSlowDivWidths;
181 /// isPow2DivCheap() - Return true if pow2 div is cheaper than a chain of
183 bool isPow2DivCheap() const { return Pow2DivIsCheap; }
185 /// isJumpExpensive() - Return true if Flow Control is an expensive operation
186 /// that should be avoided.
187 bool isJumpExpensive() const { return JumpIsExpensive; }
189 /// isPredictableSelectExpensive - Return true if selects are only cheaper
190 /// than branches if the branch is unlikely to be predicted right.
191 bool isPredictableSelectExpensive() const {
192 return predictableSelectIsExpensive;
195 /// getSetCCResultType - Return the ValueType of the result of SETCC
196 /// operations. Also used to obtain the target's preferred type for
197 /// the condition operand of SELECT and BRCOND nodes. In the case of
198 /// BRCOND the argument passed is MVT::Other since there are no other
199 /// operands to get a type hint from.
200 virtual EVT getSetCCResultType(EVT VT) const;
202 /// getCmpLibcallReturnType - Return the ValueType for comparison
203 /// libcalls. Comparions libcalls include floating point comparion calls,
204 /// and Ordered/Unordered check calls on floating point numbers.
206 MVT::SimpleValueType getCmpLibcallReturnType() const;
208 /// getBooleanContents - For targets without i1 registers, this gives the
209 /// nature of the high-bits of boolean values held in types wider than i1.
210 /// "Boolean values" are special true/false values produced by nodes like
211 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
212 /// Not to be confused with general values promoted from i1.
213 /// Some cpus distinguish between vectors of boolean and scalars; the isVec
214 /// parameter selects between the two kinds. For example on X86 a scalar
215 /// boolean should be zero extended from i1, while the elements of a vector
216 /// of booleans should be sign extended from i1.
217 BooleanContent getBooleanContents(bool isVec) const {
218 return isVec ? BooleanVectorContents : BooleanContents;
221 /// getSchedulingPreference - Return target scheduling preference.
222 Sched::Preference getSchedulingPreference() const {
223 return SchedPreferenceInfo;
226 /// getSchedulingPreference - Some scheduler, e.g. hybrid, can switch to
227 /// different scheduling heuristics for different nodes. This function returns
228 /// the preference (or none) for the given node.
229 virtual Sched::Preference getSchedulingPreference(SDNode *) const {
233 /// getRegClassFor - Return the register class that should be used for the
234 /// specified value type.
235 virtual const TargetRegisterClass *getRegClassFor(EVT VT) const {
236 assert(VT.isSimple() && "getRegClassFor called on illegal type!");
237 const TargetRegisterClass *RC = RegClassForVT[VT.getSimpleVT().SimpleTy];
238 assert(RC && "This value type is not natively supported!");
242 /// getRepRegClassFor - Return the 'representative' register class for the
243 /// specified value type. The 'representative' register class is the largest
244 /// legal super-reg register class for the register class of the value type.
245 /// For example, on i386 the rep register class for i8, i16, and i32 are GR32;
246 /// while the rep register class is GR64 on x86_64.
247 virtual const TargetRegisterClass *getRepRegClassFor(EVT VT) const {
248 assert(VT.isSimple() && "getRepRegClassFor called on illegal type!");
249 const TargetRegisterClass *RC = RepRegClassForVT[VT.getSimpleVT().SimpleTy];
253 /// getRepRegClassCostFor - Return the cost of the 'representative' register
254 /// class for the specified value type.
255 virtual uint8_t getRepRegClassCostFor(EVT VT) const {
256 assert(VT.isSimple() && "getRepRegClassCostFor called on illegal type!");
257 return RepRegClassCostForVT[VT.getSimpleVT().SimpleTy];
260 /// isTypeLegal - Return true if the target has native support for the
261 /// specified value type. This means that it has a register that directly
262 /// holds it without promotions or expansions.
263 bool isTypeLegal(EVT VT) const {
264 assert(!VT.isSimple() ||
265 (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
266 return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != 0;
269 class ValueTypeActionImpl {
270 /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
271 /// that indicates how instruction selection should deal with the type.
272 uint8_t ValueTypeActions[MVT::LAST_VALUETYPE];
275 ValueTypeActionImpl() {
276 std::fill(ValueTypeActions, array_endof(ValueTypeActions), 0);
279 LegalizeTypeAction getTypeAction(MVT VT) const {
280 return (LegalizeTypeAction)ValueTypeActions[VT.SimpleTy];
283 void setTypeAction(EVT VT, LegalizeTypeAction Action) {
284 unsigned I = VT.getSimpleVT().SimpleTy;
285 ValueTypeActions[I] = Action;
289 const ValueTypeActionImpl &getValueTypeActions() const {
290 return ValueTypeActions;
293 /// getTypeAction - Return how we should legalize values of this type, either
294 /// it is already legal (return 'Legal') or we need to promote it to a larger
295 /// type (return 'Promote'), or we need to expand it into multiple registers
296 /// of smaller integer type (return 'Expand'). 'Custom' is not an option.
297 LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const {
298 return getTypeConversion(Context, VT).first;
300 LegalizeTypeAction getTypeAction(MVT VT) const {
301 return ValueTypeActions.getTypeAction(VT);
304 /// getTypeToTransformTo - For types supported by the target, this is an
305 /// identity function. For types that must be promoted to larger types, this
306 /// returns the larger type to promote to. For integer types that are larger
307 /// than the largest integer register, this contains one step in the expansion
308 /// to get to the smaller register. For illegal floating point types, this
309 /// returns the integer type to transform to.
310 EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
311 return getTypeConversion(Context, VT).second;
314 /// getTypeToExpandTo - For types supported by the target, this is an
315 /// identity function. For types that must be expanded (i.e. integer types
316 /// that are larger than the largest integer register or illegal floating
317 /// point types), this returns the largest legal type it will be expanded to.
318 EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
319 assert(!VT.isVector());
321 switch (getTypeAction(Context, VT)) {
324 case TypeExpandInteger:
325 VT = getTypeToTransformTo(Context, VT);
328 llvm_unreachable("Type is not legal nor is it to be expanded!");
333 /// getVectorTypeBreakdown - Vector types are broken down into some number of
334 /// legal first class types. For example, EVT::v8f32 maps to 2 EVT::v4f32
335 /// with Altivec or SSE1, or 8 promoted EVT::f64 values with the X86 FP stack.
336 /// Similarly, EVT::v2i64 turns into 4 EVT::i32 values with both PPC and X86.
338 /// This method returns the number of registers needed, and the VT for each
339 /// register. It also returns the VT and quantity of the intermediate values
340 /// before they are promoted/expanded.
342 unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
344 unsigned &NumIntermediates,
345 EVT &RegisterVT) const;
347 /// getTgtMemIntrinsic: Given an intrinsic, checks if on the target the
348 /// intrinsic will need to map to a MemIntrinsicNode (touches memory). If
349 /// this is the case, it returns true and store the intrinsic
350 /// information into the IntrinsicInfo that was passed to the function.
351 struct IntrinsicInfo {
352 unsigned opc; // target opcode
353 EVT memVT; // memory VT
354 const Value* ptrVal; // value representing memory location
355 int offset; // offset off of ptrVal
356 unsigned align; // alignment
357 bool vol; // is volatile?
358 bool readMem; // reads memory?
359 bool writeMem; // writes memory?
362 virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
363 unsigned /*Intrinsic*/) const {
367 /// isFPImmLegal - Returns true if the target can instruction select the
368 /// specified FP immediate natively. If false, the legalizer will materialize
369 /// the FP immediate as a load from a constant pool.
370 virtual bool isFPImmLegal(const APFloat &/*Imm*/, EVT /*VT*/) const {
374 /// isShuffleMaskLegal - Targets can use this to indicate that they only
375 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
376 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
377 /// are assumed to be legal.
378 virtual bool isShuffleMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
383 /// canOpTrap - Returns true if the operation can trap for the value type.
384 /// VT must be a legal type. By default, we optimistically assume most
385 /// operations don't trap except for divide and remainder.
386 virtual bool canOpTrap(unsigned Op, EVT VT) const;
388 /// isVectorClearMaskLegal - Similar to isShuffleMaskLegal. This is
389 /// used by Targets can use this to indicate if there is a suitable
390 /// VECTOR_SHUFFLE that can be used to replace a VAND with a constant
392 virtual bool isVectorClearMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
397 /// getOperationAction - Return how this operation should be treated: either
398 /// it is legal, needs to be promoted to a larger size, needs to be
399 /// expanded to some other code sequence, or the target has a custom expander
401 LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
402 if (VT.isExtended()) return Expand;
403 // If a target-specific SDNode requires legalization, require the target
404 // to provide custom legalization for it.
405 if (Op > array_lengthof(OpActions[0])) return Custom;
406 unsigned I = (unsigned) VT.getSimpleVT().SimpleTy;
407 return (LegalizeAction)OpActions[I][Op];
410 /// isOperationLegalOrCustom - Return true if the specified operation is
411 /// legal on this target or can be made legal with custom lowering. This
412 /// is used to help guide high-level lowering decisions.
413 bool isOperationLegalOrCustom(unsigned Op, EVT VT) const {
414 return (VT == MVT::Other || isTypeLegal(VT)) &&
415 (getOperationAction(Op, VT) == Legal ||
416 getOperationAction(Op, VT) == Custom);
419 /// isOperationExpand - Return true if the specified operation is illegal on
420 /// this target or unlikely to be made legal with custom lowering. This is
421 /// used to help guide high-level lowering decisions.
422 bool isOperationExpand(unsigned Op, EVT VT) const {
423 return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
426 /// isOperationLegal - Return true if the specified operation is legal on this
428 bool isOperationLegal(unsigned Op, EVT VT) const {
429 return (VT == MVT::Other || isTypeLegal(VT)) &&
430 getOperationAction(Op, VT) == Legal;
433 /// getLoadExtAction - Return how this load with extension should be treated:
434 /// either it is legal, needs to be promoted to a larger size, needs to be
435 /// expanded to some other code sequence, or the target has a custom expander
437 LegalizeAction getLoadExtAction(unsigned ExtType, EVT VT) const {
438 assert(ExtType < ISD::LAST_LOADEXT_TYPE &&
439 VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
440 "Table isn't big enough!");
441 return (LegalizeAction)LoadExtActions[VT.getSimpleVT().SimpleTy][ExtType];
444 /// isLoadExtLegal - Return true if the specified load with extension is legal
446 bool isLoadExtLegal(unsigned ExtType, EVT VT) const {
447 return VT.isSimple() && getLoadExtAction(ExtType, VT) == Legal;
450 /// getTruncStoreAction - Return how this store with truncation should be
451 /// treated: either it is legal, needs to be promoted to a larger size, needs
452 /// to be expanded to some other code sequence, or the target has a custom
454 LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT) const {
455 assert(ValVT.getSimpleVT() < MVT::LAST_VALUETYPE &&
456 MemVT.getSimpleVT() < MVT::LAST_VALUETYPE &&
457 "Table isn't big enough!");
458 return (LegalizeAction)TruncStoreActions[ValVT.getSimpleVT().SimpleTy]
459 [MemVT.getSimpleVT().SimpleTy];
462 /// isTruncStoreLegal - Return true if the specified store with truncation is
463 /// legal on this target.
464 bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
465 return isTypeLegal(ValVT) && MemVT.isSimple() &&
466 getTruncStoreAction(ValVT, MemVT) == Legal;
469 /// getIndexedLoadAction - Return how the indexed load should be treated:
470 /// either it is legal, needs to be promoted to a larger size, needs to be
471 /// expanded to some other code sequence, or the target has a custom expander
474 getIndexedLoadAction(unsigned IdxMode, EVT VT) const {
475 assert(IdxMode < ISD::LAST_INDEXED_MODE &&
476 VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
477 "Table isn't big enough!");
478 unsigned Ty = (unsigned)VT.getSimpleVT().SimpleTy;
479 return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] & 0xf0) >> 4);
482 /// isIndexedLoadLegal - Return true if the specified indexed load is legal
484 bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
485 return VT.isSimple() &&
486 (getIndexedLoadAction(IdxMode, VT) == Legal ||
487 getIndexedLoadAction(IdxMode, VT) == Custom);
490 /// getIndexedStoreAction - Return how the indexed store should be treated:
491 /// either it is legal, needs to be promoted to a larger size, needs to be
492 /// expanded to some other code sequence, or the target has a custom expander
495 getIndexedStoreAction(unsigned IdxMode, EVT VT) const {
496 assert(IdxMode < ISD::LAST_INDEXED_MODE &&
497 VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
498 "Table isn't big enough!");
499 unsigned Ty = (unsigned)VT.getSimpleVT().SimpleTy;
500 return (LegalizeAction)(IndexedModeActions[Ty][IdxMode] & 0x0f);
503 /// isIndexedStoreLegal - Return true if the specified indexed load is legal
505 bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
506 return VT.isSimple() &&
507 (getIndexedStoreAction(IdxMode, VT) == Legal ||
508 getIndexedStoreAction(IdxMode, VT) == Custom);
511 /// getCondCodeAction - Return how the condition code should be treated:
512 /// either it is legal, needs to be expanded to some other code sequence,
513 /// or the target has a custom expander for it.
515 getCondCodeAction(ISD::CondCode CC, EVT VT) const {
516 assert((unsigned)CC < array_lengthof(CondCodeActions) &&
517 (unsigned)VT.getSimpleVT().SimpleTy < sizeof(CondCodeActions[0])*4 &&
518 "Table isn't big enough!");
519 /// The lower 5 bits of the SimpleTy index into Nth 2bit set from the 64bit
520 /// value and the upper 27 bits index into the second dimension of the
521 /// array to select what 64bit value to use.
522 LegalizeAction Action = (LegalizeAction)
523 ((CondCodeActions[CC][VT.getSimpleVT().SimpleTy >> 5]
524 >> (2*(VT.getSimpleVT().SimpleTy & 0x1F))) & 3);
525 assert(Action != Promote && "Can't promote condition code!");
529 /// isCondCodeLegal - Return true if the specified condition code is legal
531 bool isCondCodeLegal(ISD::CondCode CC, EVT VT) const {
532 return getCondCodeAction(CC, VT) == Legal ||
533 getCondCodeAction(CC, VT) == Custom;
537 /// getTypeToPromoteTo - If the action for this operation is to promote, this
538 /// method returns the ValueType to promote to.
539 EVT getTypeToPromoteTo(unsigned Op, EVT VT) const {
540 assert(getOperationAction(Op, VT) == Promote &&
541 "This operation isn't promoted!");
543 // See if this has an explicit type specified.
544 std::map<std::pair<unsigned, MVT::SimpleValueType>,
545 MVT::SimpleValueType>::const_iterator PTTI =
546 PromoteToType.find(std::make_pair(Op, VT.getSimpleVT().SimpleTy));
547 if (PTTI != PromoteToType.end()) return PTTI->second;
549 assert((VT.isInteger() || VT.isFloatingPoint()) &&
550 "Cannot autopromote this type, add it with AddPromotedToType.");
554 NVT = (MVT::SimpleValueType)(NVT.getSimpleVT().SimpleTy+1);
555 assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
556 "Didn't find type to promote to!");
557 } while (!isTypeLegal(NVT) ||
558 getOperationAction(Op, NVT) == Promote);
562 /// getValueType - Return the EVT corresponding to this LLVM type.
563 /// This is fixed by the LLVM operations except for the pointer size. If
564 /// AllowUnknown is true, this will return MVT::Other for types with no EVT
565 /// counterpart (e.g. structs), otherwise it will assert.
566 EVT getValueType(Type *Ty, bool AllowUnknown = false) const {
567 // Lower scalar pointers to native pointer types.
568 if (Ty->isPointerTy()) return PointerTy;
570 if (Ty->isVectorTy()) {
571 VectorType *VTy = cast<VectorType>(Ty);
572 Type *Elm = VTy->getElementType();
573 // Lower vectors of pointers to native pointer types.
574 if (Elm->isPointerTy())
575 Elm = EVT(PointerTy).getTypeForEVT(Ty->getContext());
576 return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
577 VTy->getNumElements());
579 return EVT::getEVT(Ty, AllowUnknown);
583 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
584 /// function arguments in the caller parameter area. This is the actual
585 /// alignment, not its logarithm.
586 virtual unsigned getByValTypeAlignment(Type *Ty) const;
588 /// getRegisterType - Return the type of registers that this ValueType will
589 /// eventually require.
590 EVT getRegisterType(MVT VT) const {
591 assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
592 return RegisterTypeForVT[VT.SimpleTy];
595 /// getRegisterType - Return the type of registers that this ValueType will
596 /// eventually require.
597 EVT getRegisterType(LLVMContext &Context, EVT VT) const {
599 assert((unsigned)VT.getSimpleVT().SimpleTy <
600 array_lengthof(RegisterTypeForVT));
601 return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
605 unsigned NumIntermediates;
606 (void)getVectorTypeBreakdown(Context, VT, VT1,
607 NumIntermediates, RegisterVT);
610 if (VT.isInteger()) {
611 return getRegisterType(Context, getTypeToTransformTo(Context, VT));
613 llvm_unreachable("Unsupported extended type!");
616 /// getNumRegisters - Return the number of registers that this ValueType will
617 /// eventually require. This is one for any types promoted to live in larger
618 /// registers, but may be more than one for types (like i64) that are split
619 /// into pieces. For types like i140, which are first promoted then expanded,
620 /// it is the number of registers needed to hold all the bits of the original
621 /// type. For an i140 on a 32 bit machine this means 5 registers.
622 unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
624 assert((unsigned)VT.getSimpleVT().SimpleTy <
625 array_lengthof(NumRegistersForVT));
626 return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
630 unsigned NumIntermediates;
631 return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
633 if (VT.isInteger()) {
634 unsigned BitWidth = VT.getSizeInBits();
635 unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
636 return (BitWidth + RegWidth - 1) / RegWidth;
638 llvm_unreachable("Unsupported extended type!");
641 /// ShouldShrinkFPConstant - If true, then instruction selection should
642 /// seek to shrink the FP constant of the specified type to a smaller type
643 /// in order to save space and / or reduce runtime.
644 virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
646 /// hasTargetDAGCombine - If true, the target has custom DAG combine
647 /// transformations that it can perform for the specified node.
648 bool hasTargetDAGCombine(ISD::NodeType NT) const {
649 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
650 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
653 /// This function returns the maximum number of store operations permitted
654 /// to replace a call to llvm.memset. The value is set by the target at the
655 /// performance threshold for such a replacement. If OptSize is true,
656 /// return the limit for functions that have OptSize attribute.
657 /// @brief Get maximum # of store operations permitted for llvm.memset
658 unsigned getMaxStoresPerMemset(bool OptSize) const {
659 return OptSize ? maxStoresPerMemsetOptSize : maxStoresPerMemset;
662 /// This function returns the maximum number of store operations permitted
663 /// to replace a call to llvm.memcpy. The value is set by the target at the
664 /// performance threshold for such a replacement. If OptSize is true,
665 /// return the limit for functions that have OptSize attribute.
666 /// @brief Get maximum # of store operations permitted for llvm.memcpy
667 unsigned getMaxStoresPerMemcpy(bool OptSize) const {
668 return OptSize ? maxStoresPerMemcpyOptSize : maxStoresPerMemcpy;
671 /// This function returns the maximum number of store operations permitted
672 /// to replace a call to llvm.memmove. The value is set by the target at the
673 /// performance threshold for such a replacement. If OptSize is true,
674 /// return the limit for functions that have OptSize attribute.
675 /// @brief Get maximum # of store operations permitted for llvm.memmove
676 unsigned getMaxStoresPerMemmove(bool OptSize) const {
677 return OptSize ? maxStoresPerMemmoveOptSize : maxStoresPerMemmove;
680 /// This function returns true if the target allows unaligned memory accesses.
681 /// of the specified type. This is used, for example, in situations where an
682 /// array copy/move/set is converted to a sequence of store operations. It's
683 /// use helps to ensure that such replacements don't generate code that causes
684 /// an alignment error (trap) on the target machine.
685 /// @brief Determine if the target supports unaligned memory accesses.
686 virtual bool allowsUnalignedMemoryAccesses(EVT) const {
690 /// This function returns true if the target would benefit from code placement
692 /// @brief Determine if the target should perform code placement optimization.
693 bool shouldOptimizeCodePlacement() const {
694 return benefitFromCodePlacementOpt;
697 /// getOptimalMemOpType - Returns the target specific optimal type for load
698 /// and store operations as a result of memset, memcpy, and memmove
699 /// lowering. If DstAlign is zero that means it's safe to destination
700 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
701 /// means there isn't a need to check it against alignment requirement,
702 /// probably because the source does not need to be loaded. If
703 /// 'IsZeroVal' is true, that means it's safe to return a
704 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
705 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
706 /// constant so it does not need to be loaded.
707 /// It returns EVT::Other if the type should be determined using generic
708 /// target-independent logic.
709 virtual EVT getOptimalMemOpType(uint64_t /*Size*/,
710 unsigned /*DstAlign*/, unsigned /*SrcAlign*/,
712 bool /*MemcpyStrSrc*/,
713 MachineFunction &/*MF*/) const {
717 /// usesUnderscoreSetJmp - Determine if we should use _setjmp or setjmp
718 /// to implement llvm.setjmp.
719 bool usesUnderscoreSetJmp() const {
720 return UseUnderscoreSetJmp;
723 /// usesUnderscoreLongJmp - Determine if we should use _longjmp or longjmp
724 /// to implement llvm.longjmp.
725 bool usesUnderscoreLongJmp() const {
726 return UseUnderscoreLongJmp;
729 /// supportJumpTables - return whether the target can generate code for
731 bool supportJumpTables() const {
732 return SupportJumpTables;
735 /// getMinimumJumpTableEntries - return integer threshold on number of
736 /// blocks to use jump tables rather than if sequence.
737 int getMinimumJumpTableEntries() const {
738 return MinimumJumpTableEntries;
741 /// getStackPointerRegisterToSaveRestore - If a physical register, this
742 /// specifies the register that llvm.savestack/llvm.restorestack should save
744 unsigned getStackPointerRegisterToSaveRestore() const {
745 return StackPointerRegisterToSaveRestore;
748 /// getExceptionPointerRegister - If a physical register, this returns
749 /// the register that receives the exception address on entry to a landing
751 unsigned getExceptionPointerRegister() const {
752 return ExceptionPointerRegister;
755 /// getExceptionSelectorRegister - If a physical register, this returns
756 /// the register that receives the exception typeid on entry to a landing
758 unsigned getExceptionSelectorRegister() const {
759 return ExceptionSelectorRegister;
762 /// getJumpBufSize - returns the target's jmp_buf size in bytes (if never
763 /// set, the default is 200)
764 unsigned getJumpBufSize() const {
768 /// getJumpBufAlignment - returns the target's jmp_buf alignment in bytes
769 /// (if never set, the default is 0)
770 unsigned getJumpBufAlignment() const {
771 return JumpBufAlignment;
774 /// getMinStackArgumentAlignment - return the minimum stack alignment of an
776 unsigned getMinStackArgumentAlignment() const {
777 return MinStackArgumentAlignment;
780 /// getMinFunctionAlignment - return the minimum function alignment.
782 unsigned getMinFunctionAlignment() const {
783 return MinFunctionAlignment;
786 /// getPrefFunctionAlignment - return the preferred function alignment.
788 unsigned getPrefFunctionAlignment() const {
789 return PrefFunctionAlignment;
792 /// getPrefLoopAlignment - return the preferred loop alignment.
794 unsigned getPrefLoopAlignment() const {
795 return PrefLoopAlignment;
798 /// getShouldFoldAtomicFences - return whether the combiner should fold
799 /// fence MEMBARRIER instructions into the atomic intrinsic instructions.
801 bool getShouldFoldAtomicFences() const {
802 return ShouldFoldAtomicFences;
805 /// getInsertFencesFor - return whether the DAG builder should automatically
806 /// insert fences and reduce ordering for atomics.
808 bool getInsertFencesForAtomic() const {
809 return InsertFencesForAtomic;
812 /// getPreIndexedAddressParts - returns true by value, base pointer and
813 /// offset pointer and addressing mode by reference if the node's address
814 /// can be legally represented as pre-indexed load / store address.
815 virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
817 ISD::MemIndexedMode &/*AM*/,
818 SelectionDAG &/*DAG*/) const {
822 /// getPostIndexedAddressParts - returns true by value, base pointer and
823 /// offset pointer and addressing mode by reference if this node can be
824 /// combined with a load / store to form a post-indexed load / store.
825 virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
826 SDValue &/*Base*/, SDValue &/*Offset*/,
827 ISD::MemIndexedMode &/*AM*/,
828 SelectionDAG &/*DAG*/) const {
832 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
833 /// current function. The returned value is a member of the
834 /// MachineJumpTableInfo::JTEntryKind enum.
835 virtual unsigned getJumpTableEncoding() const;
837 virtual const MCExpr *
838 LowerCustomJumpTableEntry(const MachineJumpTableInfo * /*MJTI*/,
839 const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
840 MCContext &/*Ctx*/) const {
841 llvm_unreachable("Need to implement this hook if target has custom JTIs");
844 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
846 virtual SDValue getPICJumpTableRelocBase(SDValue Table,
847 SelectionDAG &DAG) const;
849 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
850 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
852 virtual const MCExpr *
853 getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
854 unsigned JTI, MCContext &Ctx) const;
856 /// isOffsetFoldingLegal - Return true if folding a constant offset
857 /// with the given GlobalAddress is legal. It is frequently not legal in
858 /// PIC relocation models.
859 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
861 /// getStackCookieLocation - Return true if the target stores stack
862 /// protector cookies at a fixed offset in some non-standard address
863 /// space, and populates the address space and offset as
865 virtual bool getStackCookieLocation(unsigned &/*AddressSpace*/,
866 unsigned &/*Offset*/) const {
870 /// getMaximalGlobalOffset - Returns the maximal possible offset which can be
871 /// used for loads / stores from the global.
872 virtual unsigned getMaximalGlobalOffset() const {
876 //===--------------------------------------------------------------------===//
877 // TargetLowering Optimization Methods
880 /// TargetLoweringOpt - A convenience struct that encapsulates a DAG, and two
881 /// SDValues for returning information from TargetLowering to its clients
882 /// that want to combine
883 struct TargetLoweringOpt {
890 explicit TargetLoweringOpt(SelectionDAG &InDAG,
892 DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
894 bool LegalTypes() const { return LegalTys; }
895 bool LegalOperations() const { return LegalOps; }
897 bool CombineTo(SDValue O, SDValue N) {
903 /// ShrinkDemandedConstant - Check to see if the specified operand of the
904 /// specified instruction is a constant integer. If so, check to see if
905 /// there are any bits set in the constant that are not demanded. If so,
906 /// shrink the constant and return true.
907 bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded);
909 /// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the
910 /// casts are free. This uses isZExtFree and ZERO_EXTEND for the widening
911 /// cast, but it could be generalized for targets with other types of
912 /// implicit widening casts.
913 bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
917 /// SimplifyDemandedBits - Look at Op. At this point, we know that only the
918 /// DemandedMask bits of the result of Op are ever used downstream. If we can
919 /// use this information to simplify Op, create a new simplified DAG node and
920 /// return true, returning the original and new nodes in Old and New.
921 /// Otherwise, analyze the expression and return a mask of KnownOne and
922 /// KnownZero bits for the expression (used to simplify the caller).
923 /// The KnownZero/One bits may only be accurate for those bits in the
925 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
926 APInt &KnownZero, APInt &KnownOne,
927 TargetLoweringOpt &TLO, unsigned Depth = 0) const;
929 /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
930 /// Mask are known to be either zero or one and return them in the
931 /// KnownZero/KnownOne bitsets.
932 virtual void computeMaskedBitsForTargetNode(const SDValue Op,
935 const SelectionDAG &DAG,
936 unsigned Depth = 0) const;
938 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
939 /// targets that want to expose additional information about sign bits to the
941 virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
942 unsigned Depth = 0) const;
944 struct DAGCombinerInfo {
945 void *DC; // The DAG Combiner object.
947 bool BeforeLegalizeOps;
948 bool CalledByLegalizer;
952 DAGCombinerInfo(SelectionDAG &dag, bool bl, bool blo, bool cl, void *dc)
953 : DC(dc), BeforeLegalize(bl), BeforeLegalizeOps(blo),
954 CalledByLegalizer(cl), DAG(dag) {}
956 bool isBeforeLegalize() const { return BeforeLegalize; }
957 bool isBeforeLegalizeOps() const { return BeforeLegalizeOps; }
958 bool isCalledByLegalizer() const { return CalledByLegalizer; }
960 void AddToWorklist(SDNode *N);
961 void RemoveFromWorklist(SDNode *N);
962 SDValue CombineTo(SDNode *N, const std::vector<SDValue> &To,
964 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
965 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
967 void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
970 /// SimplifySetCC - Try to simplify a setcc built with the specified operands
971 /// and cc. If it is unable to simplify it, return a null SDValue.
972 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
973 ISD::CondCode Cond, bool foldBooleans,
974 DAGCombinerInfo &DCI, DebugLoc dl) const;
976 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
977 /// node is a GlobalAddress + offset.
979 isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
981 /// PerformDAGCombine - This method will be invoked for all target nodes and
982 /// for any target-independent nodes that the target has registered with
985 /// The semantics are as follows:
987 /// SDValue.Val == 0 - No change was made
988 /// SDValue.Val == N - N was replaced, is dead, and is already handled.
989 /// otherwise - N should be replaced by the returned Operand.
991 /// In addition, methods provided by DAGCombinerInfo may be used to perform
992 /// more complex transformations.
994 virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
996 /// isTypeDesirableForOp - Return true if the target has native support for
997 /// the specified value type and it is 'desirable' to use the type for the
998 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
999 /// instruction encodings are longer and some i16 instructions are slow.
1000 virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
1001 // By default, assume all legal types are desirable.
1002 return isTypeLegal(VT);
1005 /// isDesirableToPromoteOp - Return true if it is profitable for dag combiner
1006 /// to transform a floating point op of specified opcode to a equivalent op of
1007 /// an integer type. e.g. f32 load -> i32 load can be profitable on ARM.
1008 virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
1013 /// IsDesirableToPromoteOp - This method query the target whether it is
1014 /// beneficial for dag combiner to promote the specified node. If true, it
1015 /// should return the desired promotion type by reference.
1016 virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
1020 //===--------------------------------------------------------------------===//
1021 // TargetLowering Configuration Methods - These methods should be invoked by
1022 // the derived class constructor to configure this object for the target.
1026 /// setBooleanContents - Specify how the target extends the result of a
1027 /// boolean value from i1 to a wider type. See getBooleanContents.
1028 void setBooleanContents(BooleanContent Ty) { BooleanContents = Ty; }
1029 /// setBooleanVectorContents - Specify how the target extends the result
1030 /// of a vector boolean value from a vector of i1 to a wider type. See
1031 /// getBooleanContents.
1032 void setBooleanVectorContents(BooleanContent Ty) {
1033 BooleanVectorContents = Ty;
1036 /// setSchedulingPreference - Specify the target scheduling preference.
1037 void setSchedulingPreference(Sched::Preference Pref) {
1038 SchedPreferenceInfo = Pref;
1041 /// setUseUnderscoreSetJmp - Indicate whether this target prefers to
1042 /// use _setjmp to implement llvm.setjmp or the non _ version.
1043 /// Defaults to false.
1044 void setUseUnderscoreSetJmp(bool Val) {
1045 UseUnderscoreSetJmp = Val;
1048 /// setUseUnderscoreLongJmp - Indicate whether this target prefers to
1049 /// use _longjmp to implement llvm.longjmp or the non _ version.
1050 /// Defaults to false.
1051 void setUseUnderscoreLongJmp(bool Val) {
1052 UseUnderscoreLongJmp = Val;
1055 /// setSupportJumpTables - Indicate whether the target can generate code for
1057 void setSupportJumpTables(bool Val) {
1058 SupportJumpTables = Val;
1061 /// setMinimumJumpTableEntries - Indicate the number of blocks to generate
1062 /// jump tables rather than if sequence.
1063 void setMinimumJumpTableEntries(int Val) {
1064 MinimumJumpTableEntries = Val;
1067 /// setStackPointerRegisterToSaveRestore - If set to a physical register, this
1068 /// specifies the register that llvm.savestack/llvm.restorestack should save
1070 void setStackPointerRegisterToSaveRestore(unsigned R) {
1071 StackPointerRegisterToSaveRestore = R;
1074 /// setExceptionPointerRegister - If set to a physical register, this sets
1075 /// the register that receives the exception address on entry to a landing
1077 void setExceptionPointerRegister(unsigned R) {
1078 ExceptionPointerRegister = R;
1081 /// setExceptionSelectorRegister - If set to a physical register, this sets
1082 /// the register that receives the exception typeid on entry to a landing
1084 void setExceptionSelectorRegister(unsigned R) {
1085 ExceptionSelectorRegister = R;
1088 /// SelectIsExpensive - Tells the code generator not to expand operations
1089 /// into sequences that use the select operations if possible.
1090 void setSelectIsExpensive(bool isExpensive = true) {
1091 SelectIsExpensive = isExpensive;
1094 /// JumpIsExpensive - Tells the code generator not to expand sequence of
1095 /// operations into a separate sequences that increases the amount of
1097 void setJumpIsExpensive(bool isExpensive = true) {
1098 JumpIsExpensive = isExpensive;
1101 /// setIntDivIsCheap - Tells the code generator that integer divide is
1102 /// expensive, and if possible, should be replaced by an alternate sequence
1103 /// of instructions not containing an integer divide.
1104 void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
1106 /// addBypassSlowDiv - Tells the code generator which bitwidths to bypass.
1107 void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
1108 BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
1111 /// setPow2DivIsCheap - Tells the code generator that it shouldn't generate
1112 /// srl/add/sra for a signed divide by power of two, and let the target handle
1114 void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
1116 /// addRegisterClass - Add the specified register class as an available
1117 /// regclass for the specified value type. This indicates the selector can
1118 /// handle values of that class natively.
1119 void addRegisterClass(EVT VT, const TargetRegisterClass *RC) {
1120 assert((unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
1121 AvailableRegClasses.push_back(std::make_pair(VT, RC));
1122 RegClassForVT[VT.getSimpleVT().SimpleTy] = RC;
1125 /// findRepresentativeClass - Return the largest legal super-reg register class
1126 /// of the register class for the specified type and its associated "cost".
1127 virtual std::pair<const TargetRegisterClass*, uint8_t>
1128 findRepresentativeClass(EVT VT) const;
1130 /// computeRegisterProperties - Once all of the register classes are added,
1131 /// this allows us to compute derived properties we expose.
1132 void computeRegisterProperties();
1134 /// setOperationAction - Indicate that the specified operation does not work
1135 /// with the specified type and indicate what to do about it.
1136 void setOperationAction(unsigned Op, MVT VT,
1137 LegalizeAction Action) {
1138 assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
1139 OpActions[(unsigned)VT.SimpleTy][Op] = (uint8_t)Action;
1142 /// setLoadExtAction - Indicate that the specified load with extension does
1143 /// not work with the specified type and indicate what to do about it.
1144 void setLoadExtAction(unsigned ExtType, MVT VT,
1145 LegalizeAction Action) {
1146 assert(ExtType < ISD::LAST_LOADEXT_TYPE && VT < MVT::LAST_VALUETYPE &&
1147 "Table isn't big enough!");
1148 LoadExtActions[VT.SimpleTy][ExtType] = (uint8_t)Action;
1151 /// setTruncStoreAction - Indicate that the specified truncating store does
1152 /// not work with the specified type and indicate what to do about it.
1153 void setTruncStoreAction(MVT ValVT, MVT MemVT,
1154 LegalizeAction Action) {
1155 assert(ValVT < MVT::LAST_VALUETYPE && MemVT < MVT::LAST_VALUETYPE &&
1156 "Table isn't big enough!");
1157 TruncStoreActions[ValVT.SimpleTy][MemVT.SimpleTy] = (uint8_t)Action;
1160 /// setIndexedLoadAction - Indicate that the specified indexed load does or
1161 /// does not work with the specified type and indicate what to do abort
1162 /// it. NOTE: All indexed mode loads are initialized to Expand in
1163 /// TargetLowering.cpp
1164 void setIndexedLoadAction(unsigned IdxMode, MVT VT,
1165 LegalizeAction Action) {
1166 assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
1167 (unsigned)Action < 0xf && "Table isn't big enough!");
1168 // Load action are kept in the upper half.
1169 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0xf0;
1170 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action) <<4;
1173 /// setIndexedStoreAction - Indicate that the specified indexed store does or
1174 /// does not work with the specified type and indicate what to do about
1175 /// it. NOTE: All indexed mode stores are initialized to Expand in
1176 /// TargetLowering.cpp
1177 void setIndexedStoreAction(unsigned IdxMode, MVT VT,
1178 LegalizeAction Action) {
1179 assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
1180 (unsigned)Action < 0xf && "Table isn't big enough!");
1181 // Store action are kept in the lower half.
1182 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0x0f;
1183 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action);
1186 /// setCondCodeAction - Indicate that the specified condition code is or isn't
1187 /// supported on the target and indicate what to do about it.
1188 void setCondCodeAction(ISD::CondCode CC, MVT VT,
1189 LegalizeAction Action) {
1190 assert(VT < MVT::LAST_VALUETYPE &&
1191 (unsigned)CC < array_lengthof(CondCodeActions) &&
1192 "Table isn't big enough!");
1193 /// The lower 5 bits of the SimpleTy index into Nth 2bit set from the 64bit
1194 /// value and the upper 27 bits index into the second dimension of the
1195 /// array to select what 64bit value to use.
1196 CondCodeActions[(unsigned)CC][VT.SimpleTy >> 5]
1197 &= ~(uint64_t(3UL) << (VT.SimpleTy & 0x1F)*2);
1198 CondCodeActions[(unsigned)CC][VT.SimpleTy >> 5]
1199 |= (uint64_t)Action << (VT.SimpleTy & 0x1F)*2;
1202 /// AddPromotedToType - If Opc/OrigVT is specified as being promoted, the
1203 /// promotion code defaults to trying a larger integer/fp until it can find
1204 /// one that works. If that default is insufficient, this method can be used
1205 /// by the target to override the default.
1206 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1207 PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
1210 /// setTargetDAGCombine - Targets should invoke this method for each target
1211 /// independent node that they want to provide a custom DAG combiner for by
1212 /// implementing the PerformDAGCombine virtual method.
1213 void setTargetDAGCombine(ISD::NodeType NT) {
1214 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1215 TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
1218 /// setJumpBufSize - Set the target's required jmp_buf buffer size (in
1219 /// bytes); default is 200
1220 void setJumpBufSize(unsigned Size) {
1224 /// setJumpBufAlignment - Set the target's required jmp_buf buffer
1225 /// alignment (in bytes); default is 0
1226 void setJumpBufAlignment(unsigned Align) {
1227 JumpBufAlignment = Align;
1230 /// setMinFunctionAlignment - Set the target's minimum function alignment (in
1232 void setMinFunctionAlignment(unsigned Align) {
1233 MinFunctionAlignment = Align;
1236 /// setPrefFunctionAlignment - Set the target's preferred function alignment.
1237 /// This should be set if there is a performance benefit to
1238 /// higher-than-minimum alignment (in log2(bytes))
1239 void setPrefFunctionAlignment(unsigned Align) {
1240 PrefFunctionAlignment = Align;
1243 /// setPrefLoopAlignment - Set the target's preferred loop alignment. Default
1244 /// alignment is zero, it means the target does not care about loop alignment.
1245 /// The alignment is specified in log2(bytes).
1246 void setPrefLoopAlignment(unsigned Align) {
1247 PrefLoopAlignment = Align;
1250 /// setMinStackArgumentAlignment - Set the minimum stack alignment of an
1251 /// argument (in log2(bytes)).
1252 void setMinStackArgumentAlignment(unsigned Align) {
1253 MinStackArgumentAlignment = Align;
1256 /// setShouldFoldAtomicFences - Set if the target's implementation of the
1257 /// atomic operation intrinsics includes locking. Default is false.
1258 void setShouldFoldAtomicFences(bool fold) {
1259 ShouldFoldAtomicFences = fold;
1262 /// setInsertFencesForAtomic - Set if the DAG builder should
1263 /// automatically insert fences and reduce the order of atomic memory
1264 /// operations to Monotonic.
1265 void setInsertFencesForAtomic(bool fence) {
1266 InsertFencesForAtomic = fence;
1270 //===--------------------------------------------------------------------===//
1271 // Lowering methods - These methods must be implemented by targets so that
1272 // the SelectionDAGBuilder code knows how to lower these.
1275 /// LowerFormalArguments - This hook must be implemented to lower the
1276 /// incoming (formal) arguments, described by the Ins array, into the
1277 /// specified DAG. The implementation should fill in the InVals array
1278 /// with legal-type argument values, and return the resulting token
1282 LowerFormalArguments(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
1284 const SmallVectorImpl<ISD::InputArg> &/*Ins*/,
1285 DebugLoc /*dl*/, SelectionDAG &/*DAG*/,
1286 SmallVectorImpl<SDValue> &/*InVals*/) const {
1287 llvm_unreachable("Not Implemented");
1290 struct ArgListEntry {
1301 ArgListEntry() : isSExt(false), isZExt(false), isInReg(false),
1302 isSRet(false), isNest(false), isByVal(false), Alignment(0) { }
1304 typedef std::vector<ArgListEntry> ArgListTy;
1306 /// CallLoweringInfo - This structure contains all information that is
1307 /// necessary for lowering calls. It is passed to TLI::LowerCallTo when the
1308 /// SelectionDAG builder needs to lower a call, and targets will see this
1309 /// struct in their LowerCall implementation.
1310 struct CallLoweringInfo {
1317 bool DoesNotReturn : 1;
1318 bool IsReturnValueUsed : 1;
1320 // IsTailCall should be modified by implementations of
1321 // TargetLowering::LowerCall that perform tail call conversions.
1324 unsigned NumFixedArgs;
1325 CallingConv::ID CallConv;
1330 ImmutableCallSite *CS;
1331 SmallVector<ISD::OutputArg, 32> Outs;
1332 SmallVector<SDValue, 32> OutVals;
1333 SmallVector<ISD::InputArg, 32> Ins;
1336 /// CallLoweringInfo - Constructs a call lowering context based on the
1337 /// ImmutableCallSite \p cs.
1338 CallLoweringInfo(SDValue chain, Type *retTy,
1339 FunctionType *FTy, bool isTailCall, SDValue callee,
1340 ArgListTy &args, SelectionDAG &dag, DebugLoc dl,
1341 ImmutableCallSite &cs)
1342 : Chain(chain), RetTy(retTy), RetSExt(cs.paramHasAttr(0, Attributes::SExt)),
1343 RetZExt(cs.paramHasAttr(0, Attributes::ZExt)), IsVarArg(FTy->isVarArg()),
1344 IsInReg(cs.paramHasAttr(0, Attributes::InReg)),
1345 DoesNotReturn(cs.doesNotReturn()),
1346 IsReturnValueUsed(!cs.getInstruction()->use_empty()),
1347 IsTailCall(isTailCall), NumFixedArgs(FTy->getNumParams()),
1348 CallConv(cs.getCallingConv()), Callee(callee), Args(args), DAG(dag),
1351 /// CallLoweringInfo - Constructs a call lowering context based on the
1352 /// provided call information.
1353 CallLoweringInfo(SDValue chain, Type *retTy, bool retSExt, bool retZExt,
1354 bool isVarArg, bool isInReg, unsigned numFixedArgs,
1355 CallingConv::ID callConv, bool isTailCall,
1356 bool doesNotReturn, bool isReturnValueUsed, SDValue callee,
1357 ArgListTy &args, SelectionDAG &dag, DebugLoc dl)
1358 : Chain(chain), RetTy(retTy), RetSExt(retSExt), RetZExt(retZExt),
1359 IsVarArg(isVarArg), IsInReg(isInReg), DoesNotReturn(doesNotReturn),
1360 IsReturnValueUsed(isReturnValueUsed), IsTailCall(isTailCall),
1361 NumFixedArgs(numFixedArgs), CallConv(callConv), Callee(callee),
1362 Args(args), DAG(dag), DL(dl), CS(NULL) {}
1365 /// LowerCallTo - This function lowers an abstract call to a function into an
1366 /// actual call. This returns a pair of operands. The first element is the
1367 /// return value for the function (if RetTy is not VoidTy). The second
1368 /// element is the outgoing token chain. It calls LowerCall to do the actual
1370 std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
1372 /// LowerCall - This hook must be implemented to lower calls into the
1373 /// the specified DAG. The outgoing arguments to the call are described
1374 /// by the Outs array, and the values to be returned by the call are
1375 /// described by the Ins array. The implementation should fill in the
1376 /// InVals array with legal-type return values from the call, and return
1377 /// the resulting token chain value.
1379 LowerCall(CallLoweringInfo &/*CLI*/,
1380 SmallVectorImpl<SDValue> &/*InVals*/) const {
1381 llvm_unreachable("Not Implemented");
1384 /// HandleByVal - Target-specific cleanup for formal ByVal parameters.
1385 virtual void HandleByVal(CCState *, unsigned &, unsigned) const {}
1387 /// CanLowerReturn - This hook should be implemented to check whether the
1388 /// return values described by the Outs array can fit into the return
1389 /// registers. If false is returned, an sret-demotion is performed.
1391 virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
1392 MachineFunction &/*MF*/, bool /*isVarArg*/,
1393 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
1394 LLVMContext &/*Context*/) const
1396 // Return true by default to get preexisting behavior.
1400 /// LowerReturn - This hook must be implemented to lower outgoing
1401 /// return values, described by the Outs array, into the specified
1402 /// DAG. The implementation should return the resulting token chain
1406 LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
1408 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
1409 const SmallVectorImpl<SDValue> &/*OutVals*/,
1410 DebugLoc /*dl*/, SelectionDAG &/*DAG*/) const {
1411 llvm_unreachable("Not Implemented");
1414 /// isUsedByReturnOnly - Return true if result of the specified node is used
1415 /// by a return node only. It also compute and return the input chain for the
1417 /// This is used to determine whether it is possible
1418 /// to codegen a libcall as tail call at legalization time.
1419 virtual bool isUsedByReturnOnly(SDNode *, SDValue &Chain) const {
1423 /// mayBeEmittedAsTailCall - Return true if the target may be able emit the
1424 /// call instruction as a tail call. This is used by optimization passes to
1425 /// determine if it's profitable to duplicate return instructions to enable
1426 /// tailcall optimization.
1427 virtual bool mayBeEmittedAsTailCall(CallInst *) const {
1431 /// getTypeForExtArgOrReturn - Return the type that should be used to zero or
1432 /// sign extend a zeroext/signext integer argument or return value.
1433 /// FIXME: Most C calling convention requires the return type to be promoted,
1434 /// but this is not true all the time, e.g. i1 on x86-64. It is also not
1435 /// necessary for non-C calling conventions. The frontend should handle this
1436 /// and include all of the necessary information.
1437 virtual EVT getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1438 ISD::NodeType /*ExtendKind*/) const {
1439 EVT MinVT = getRegisterType(Context, MVT::i32);
1440 return VT.bitsLT(MinVT) ? MinVT : VT;
1443 /// LowerOperationWrapper - This callback is invoked by the type legalizer
1444 /// to legalize nodes with an illegal operand type but legal result types.
1445 /// It replaces the LowerOperation callback in the type Legalizer.
1446 /// The reason we can not do away with LowerOperation entirely is that
1447 /// LegalizeDAG isn't yet ready to use this callback.
1448 /// TODO: Consider merging with ReplaceNodeResults.
1450 /// The target places new result values for the node in Results (their number
1451 /// and types must exactly match those of the original return values of
1452 /// the node), or leaves Results empty, which indicates that the node is not
1453 /// to be custom lowered after all.
1454 /// The default implementation calls LowerOperation.
1455 virtual void LowerOperationWrapper(SDNode *N,
1456 SmallVectorImpl<SDValue> &Results,
1457 SelectionDAG &DAG) const;
1459 /// LowerOperation - This callback is invoked for operations that are
1460 /// unsupported by the target, which are registered to use 'custom' lowering,
1461 /// and whose defined values are all legal.
1462 /// If the target has no operations that require custom lowering, it need not
1463 /// implement this. The default implementation of this aborts.
1464 virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
1466 /// ReplaceNodeResults - This callback is invoked when a node result type is
1467 /// illegal for the target, and the operation was registered to use 'custom'
1468 /// lowering for that result type. The target places new result values for
1469 /// the node in Results (their number and types must exactly match those of
1470 /// the original return values of the node), or leaves Results empty, which
1471 /// indicates that the node is not to be custom lowered after all.
1473 /// If the target has no operations that require custom lowering, it need not
1474 /// implement this. The default implementation aborts.
1475 virtual void ReplaceNodeResults(SDNode * /*N*/,
1476 SmallVectorImpl<SDValue> &/*Results*/,
1477 SelectionDAG &/*DAG*/) const {
1478 llvm_unreachable("ReplaceNodeResults not implemented for this target!");
1481 /// getTargetNodeName() - This method returns the name of a target specific
1483 virtual const char *getTargetNodeName(unsigned Opcode) const;
1485 /// createFastISel - This method returns a target specific FastISel object,
1486 /// or null if the target does not support "fast" ISel.
1487 virtual FastISel *createFastISel(FunctionLoweringInfo &,
1488 const TargetLibraryInfo *) const {
1492 //===--------------------------------------------------------------------===//
1493 // Inline Asm Support hooks
1496 /// ExpandInlineAsm - This hook allows the target to expand an inline asm
1497 /// call to be explicit llvm code if it wants to. This is useful for
1498 /// turning simple inline asms into LLVM intrinsics, which gives the
1499 /// compiler more information about the behavior of the code.
1500 virtual bool ExpandInlineAsm(CallInst *) const {
1504 enum ConstraintType {
1505 C_Register, // Constraint represents specific register(s).
1506 C_RegisterClass, // Constraint represents any of register(s) in class.
1507 C_Memory, // Memory constraint.
1508 C_Other, // Something else.
1509 C_Unknown // Unsupported constraint.
1512 enum ConstraintWeight {
1514 CW_Invalid = -1, // No match.
1515 CW_Okay = 0, // Acceptable.
1516 CW_Good = 1, // Good weight.
1517 CW_Better = 2, // Better weight.
1518 CW_Best = 3, // Best weight.
1520 // Well-known weights.
1521 CW_SpecificReg = CW_Okay, // Specific register operands.
1522 CW_Register = CW_Good, // Register operands.
1523 CW_Memory = CW_Better, // Memory operands.
1524 CW_Constant = CW_Best, // Constant operand.
1525 CW_Default = CW_Okay // Default or don't know type.
1528 /// AsmOperandInfo - This contains information for each constraint that we are
1530 struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
1531 /// ConstraintCode - This contains the actual string for the code, like "m".
1532 /// TargetLowering picks the 'best' code from ConstraintInfo::Codes that
1533 /// most closely matches the operand.
1534 std::string ConstraintCode;
1536 /// ConstraintType - Information about the constraint code, e.g. Register,
1537 /// RegisterClass, Memory, Other, Unknown.
1538 TargetLowering::ConstraintType ConstraintType;
1540 /// CallOperandval - If this is the result output operand or a
1541 /// clobber, this is null, otherwise it is the incoming operand to the
1542 /// CallInst. This gets modified as the asm is processed.
1543 Value *CallOperandVal;
1545 /// ConstraintVT - The ValueType for the operand value.
1548 /// isMatchingInputConstraint - Return true of this is an input operand that
1549 /// is a matching constraint like "4".
1550 bool isMatchingInputConstraint() const;
1552 /// getMatchedOperand - If this is an input matching constraint, this method
1553 /// returns the output operand it matches.
1554 unsigned getMatchedOperand() const;
1556 /// Copy constructor for copying from an AsmOperandInfo.
1557 AsmOperandInfo(const AsmOperandInfo &info)
1558 : InlineAsm::ConstraintInfo(info),
1559 ConstraintCode(info.ConstraintCode),
1560 ConstraintType(info.ConstraintType),
1561 CallOperandVal(info.CallOperandVal),
1562 ConstraintVT(info.ConstraintVT) {
1565 /// Copy constructor for copying from a ConstraintInfo.
1566 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
1567 : InlineAsm::ConstraintInfo(info),
1568 ConstraintType(TargetLowering::C_Unknown),
1569 CallOperandVal(0), ConstraintVT(MVT::Other) {
1573 typedef std::vector<AsmOperandInfo> AsmOperandInfoVector;
1575 /// ParseConstraints - Split up the constraint string from the inline
1576 /// assembly value into the specific constraints and their prefixes,
1577 /// and also tie in the associated operand values.
1578 /// If this returns an empty vector, and if the constraint string itself
1579 /// isn't empty, there was an error parsing.
1580 virtual AsmOperandInfoVector ParseConstraints(ImmutableCallSite CS) const;
1582 /// Examine constraint type and operand type and determine a weight value.
1583 /// The operand object must already have been set up with the operand type.
1584 virtual ConstraintWeight getMultipleConstraintMatchWeight(
1585 AsmOperandInfo &info, int maIndex) const;
1587 /// Examine constraint string and operand type and determine a weight value.
1588 /// The operand object must already have been set up with the operand type.
1589 virtual ConstraintWeight getSingleConstraintMatchWeight(
1590 AsmOperandInfo &info, const char *constraint) const;
1592 /// ComputeConstraintToUse - Determines the constraint code and constraint
1593 /// type to use for the specific AsmOperandInfo, setting
1594 /// OpInfo.ConstraintCode and OpInfo.ConstraintType. If the actual operand
1595 /// being passed in is available, it can be passed in as Op, otherwise an
1596 /// empty SDValue can be passed.
1597 virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
1599 SelectionDAG *DAG = 0) const;
1601 /// getConstraintType - Given a constraint, return the type of constraint it
1602 /// is for this target.
1603 virtual ConstraintType getConstraintType(const std::string &Constraint) const;
1605 /// getRegForInlineAsmConstraint - Given a physical register constraint (e.g.
1606 /// {edx}), return the register number and the register class for the
1609 /// Given a register class constraint, like 'r', if this corresponds directly
1610 /// to an LLVM register class, return a register of 0 and the register class
1613 /// This should only be used for C_Register constraints. On error,
1614 /// this returns a register number of 0 and a null register class pointer..
1615 virtual std::pair<unsigned, const TargetRegisterClass*>
1616 getRegForInlineAsmConstraint(const std::string &Constraint,
1619 /// LowerXConstraint - try to replace an X constraint, which matches anything,
1620 /// with another that has more specific requirements based on the type of the
1621 /// corresponding operand. This returns null if there is no replacement to
1623 virtual const char *LowerXConstraint(EVT ConstraintVT) const;
1625 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
1626 /// vector. If it is invalid, don't add anything to Ops.
1627 virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
1628 std::vector<SDValue> &Ops,
1629 SelectionDAG &DAG) const;
1631 //===--------------------------------------------------------------------===//
1632 // Instruction Emitting Hooks
1635 // EmitInstrWithCustomInserter - This method should be implemented by targets
1636 // that mark instructions with the 'usesCustomInserter' flag. These
1637 // instructions are special in various ways, which require special support to
1638 // insert. The specified MachineInstr is created but not inserted into any
1639 // basic blocks, and this method is called to expand it into a sequence of
1640 // instructions, potentially also creating new basic blocks and control flow.
1641 virtual MachineBasicBlock *
1642 EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const;
1644 /// AdjustInstrPostInstrSelection - This method should be implemented by
1645 /// targets that mark instructions with the 'hasPostISelHook' flag. These
1646 /// instructions must be adjusted after instruction selection by target hooks.
1647 /// e.g. To fill in optional defs for ARM 's' setting instructions.
1649 AdjustInstrPostInstrSelection(MachineInstr *MI, SDNode *Node) const;
1651 //===--------------------------------------------------------------------===//
1652 // Addressing mode description hooks (used by LSR etc).
1655 /// GetAddrModeArguments - CodeGenPrepare sinks address calculations into the
1656 /// same BB as Load/Store instructions reading the address. This allows as
1657 /// much computation as possible to be done in the address mode for that
1658 /// operand. This hook lets targets also pass back when this should be done
1659 /// on intrinsics which load/store.
1660 virtual bool GetAddrModeArguments(IntrinsicInst *I,
1661 SmallVectorImpl<Value*> &Ops,
1662 Type *&AccessTy) const {
1666 /// isLegalAddressingMode - Return true if the addressing mode represented by
1667 /// AM is legal for this target, for a load/store of the specified type.
1668 /// The type may be VoidTy, in which case only return true if the addressing
1669 /// mode is legal for a load/store of any legal type.
1670 /// TODO: Handle pre/postinc as well.
1671 virtual bool isLegalAddressingMode(const AddrMode &AM, Type *Ty) const;
1673 /// isLegalICmpImmediate - Return true if the specified immediate is legal
1674 /// icmp immediate, that is the target has icmp instructions which can compare
1675 /// a register against the immediate without having to materialize the
1676 /// immediate into a register.
1677 virtual bool isLegalICmpImmediate(int64_t) const {
1681 /// isLegalAddImmediate - Return true if the specified immediate is legal
1682 /// add immediate, that is the target has add instructions which can add
1683 /// a register with the immediate without having to materialize the
1684 /// immediate into a register.
1685 virtual bool isLegalAddImmediate(int64_t) const {
1689 /// isTruncateFree - Return true if it's free to truncate a value of
1690 /// type Ty1 to type Ty2. e.g. On x86 it's free to truncate a i32 value in
1691 /// register EAX to i16 by referencing its sub-register AX.
1692 virtual bool isTruncateFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1696 virtual bool isTruncateFree(EVT /*VT1*/, EVT /*VT2*/) const {
1700 /// isZExtFree - Return true if any actual instruction that defines a
1701 /// value of type Ty1 implicitly zero-extends the value to Ty2 in the result
1702 /// register. This does not necessarily include registers defined in
1703 /// unknown ways, such as incoming arguments, or copies from unknown
1704 /// virtual registers. Also, if isTruncateFree(Ty2, Ty1) is true, this
1705 /// does not necessarily apply to truncate instructions. e.g. on x86-64,
1706 /// all instructions that define 32-bit values implicit zero-extend the
1707 /// result out to 64 bits.
1708 virtual bool isZExtFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1712 virtual bool isZExtFree(EVT /*VT1*/, EVT /*VT2*/) const {
1716 /// isFNegFree - Return true if an fneg operation is free to the point where
1717 /// it is never worthwhile to replace it with a bitwise operation.
1718 virtual bool isFNegFree(EVT) const {
1722 /// isFAbsFree - Return true if an fneg operation is free to the point where
1723 /// it is never worthwhile to replace it with a bitwise operation.
1724 virtual bool isFAbsFree(EVT) const {
1728 /// isFMAFasterThanMulAndAdd - Return true if an FMA operation is faster than
1729 /// a pair of mul and add instructions. fmuladd intrinsics will be expanded to
1730 /// FMAs when this method returns true (and FMAs are legal), otherwise fmuladd
1731 /// is expanded to mul + add.
1732 virtual bool isFMAFasterThanMulAndAdd(EVT) const {
1736 /// isNarrowingProfitable - Return true if it's profitable to narrow
1737 /// operations of type VT1 to VT2. e.g. on x86, it's profitable to narrow
1738 /// from i32 to i8 but not from i32 to i16.
1739 virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
1743 //===--------------------------------------------------------------------===//
1744 // Div utility functions
1746 SDValue BuildExactSDIV(SDValue Op1, SDValue Op2, DebugLoc dl,
1747 SelectionDAG &DAG) const;
1748 SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
1749 std::vector<SDNode*>* Created) const;
1750 SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
1751 std::vector<SDNode*>* Created) const;
1754 //===--------------------------------------------------------------------===//
1755 // Runtime Library hooks
1758 /// setLibcallName - Rename the default libcall routine name for the specified
1760 void setLibcallName(RTLIB::Libcall Call, const char *Name) {
1761 LibcallRoutineNames[Call] = Name;
1764 /// getLibcallName - Get the libcall routine name for the specified libcall.
1766 const char *getLibcallName(RTLIB::Libcall Call) const {
1767 return LibcallRoutineNames[Call];
1770 /// setCmpLibcallCC - Override the default CondCode to be used to test the
1771 /// result of the comparison libcall against zero.
1772 void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
1773 CmpLibcallCCs[Call] = CC;
1776 /// getCmpLibcallCC - Get the CondCode that's to be used to test the result of
1777 /// the comparison libcall against zero.
1778 ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
1779 return CmpLibcallCCs[Call];
1782 /// setLibcallCallingConv - Set the CallingConv that should be used for the
1783 /// specified libcall.
1784 void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
1785 LibcallCallingConvs[Call] = CC;
1788 /// getLibcallCallingConv - Get the CallingConv that should be used for the
1789 /// specified libcall.
1790 CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
1791 return LibcallCallingConvs[Call];
1795 const TargetMachine &TM;
1796 const DataLayout *TD;
1797 const TargetLoweringObjectFile &TLOF;
1799 /// PointerTy - The type to use for pointers for the default address space,
1800 /// usually i32 or i64.
1804 /// IsLittleEndian - True if this is a little endian target.
1806 bool IsLittleEndian;
1808 /// SelectIsExpensive - Tells the code generator not to expand operations
1809 /// into sequences that use the select operations if possible.
1810 bool SelectIsExpensive;
1812 /// IntDivIsCheap - Tells the code generator not to expand integer divides by
1813 /// constants into a sequence of muls, adds, and shifts. This is a hack until
1814 /// a real cost model is in place. If we ever optimize for size, this will be
1815 /// set to true unconditionally.
1818 /// BypassSlowDivMap - Tells the code generator to bypass slow divide or
1819 /// remainder instructions. For example, BypassSlowDivWidths[32,8] tells the
1820 /// code generator to bypass 32-bit integer div/rem with an 8-bit unsigned
1821 /// integer div/rem when the operands are positive and less than 256.
1822 DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
1824 /// Pow2DivIsCheap - Tells the code generator that it shouldn't generate
1825 /// srl/add/sra for a signed divide by power of two, and let the target handle
1827 bool Pow2DivIsCheap;
1829 /// JumpIsExpensive - Tells the code generator that it shouldn't generate
1830 /// extra flow control instructions and should attempt to combine flow
1831 /// control instructions via predication.
1832 bool JumpIsExpensive;
1834 /// UseUnderscoreSetJmp - This target prefers to use _setjmp to implement
1835 /// llvm.setjmp. Defaults to false.
1836 bool UseUnderscoreSetJmp;
1838 /// UseUnderscoreLongJmp - This target prefers to use _longjmp to implement
1839 /// llvm.longjmp. Defaults to false.
1840 bool UseUnderscoreLongJmp;
1842 /// SupportJumpTables - Whether the target can generate code for jumptables.
1843 /// If it's not true, then each jumptable must be lowered into if-then-else's.
1844 bool SupportJumpTables;
1846 /// MinimumJumpTableEntries - Number of blocks threshold to use jump tables.
1847 int MinimumJumpTableEntries;
1849 /// BooleanContents - Information about the contents of the high-bits in
1850 /// boolean values held in a type wider than i1. See getBooleanContents.
1851 BooleanContent BooleanContents;
1852 /// BooleanVectorContents - Information about the contents of the high-bits
1853 /// in boolean vector values when the element type is wider than i1. See
1854 /// getBooleanContents.
1855 BooleanContent BooleanVectorContents;
1857 /// SchedPreferenceInfo - The target scheduling preference: shortest possible
1858 /// total cycles or lowest register usage.
1859 Sched::Preference SchedPreferenceInfo;
1861 /// JumpBufSize - The size, in bytes, of the target's jmp_buf buffers
1862 unsigned JumpBufSize;
1864 /// JumpBufAlignment - The alignment, in bytes, of the target's jmp_buf
1866 unsigned JumpBufAlignment;
1868 /// MinStackArgumentAlignment - The minimum alignment that any argument
1869 /// on the stack needs to have.
1871 unsigned MinStackArgumentAlignment;
1873 /// MinFunctionAlignment - The minimum function alignment (used when
1874 /// optimizing for size, and to prevent explicitly provided alignment
1875 /// from leading to incorrect code).
1877 unsigned MinFunctionAlignment;
1879 /// PrefFunctionAlignment - The preferred function alignment (used when
1880 /// alignment unspecified and optimizing for speed).
1882 unsigned PrefFunctionAlignment;
1884 /// PrefLoopAlignment - The preferred loop alignment.
1886 unsigned PrefLoopAlignment;
1888 /// ShouldFoldAtomicFences - Whether fencing MEMBARRIER instructions should
1889 /// be folded into the enclosed atomic intrinsic instruction by the
1891 bool ShouldFoldAtomicFences;
1893 /// InsertFencesForAtomic - Whether the DAG builder should automatically
1894 /// insert fences and reduce ordering for atomics. (This will be set for
1895 /// for most architectures with weak memory ordering.)
1896 bool InsertFencesForAtomic;
1898 /// StackPointerRegisterToSaveRestore - If set to a physical register, this
1899 /// specifies the register that llvm.savestack/llvm.restorestack should save
1901 unsigned StackPointerRegisterToSaveRestore;
1903 /// ExceptionPointerRegister - If set to a physical register, this specifies
1904 /// the register that receives the exception address on entry to a landing
1906 unsigned ExceptionPointerRegister;
1908 /// ExceptionSelectorRegister - If set to a physical register, this specifies
1909 /// the register that receives the exception typeid on entry to a landing
1911 unsigned ExceptionSelectorRegister;
1913 /// RegClassForVT - This indicates the default register class to use for
1914 /// each ValueType the target supports natively.
1915 const TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
1916 unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
1917 EVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
1919 /// RepRegClassForVT - This indicates the "representative" register class to
1920 /// use for each ValueType the target supports natively. This information is
1921 /// used by the scheduler to track register pressure. By default, the
1922 /// representative register class is the largest legal super-reg register
1923 /// class of the register class of the specified type. e.g. On x86, i8, i16,
1924 /// and i32's representative class would be GR32.
1925 const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
1927 /// RepRegClassCostForVT - This indicates the "cost" of the "representative"
1928 /// register class for each ValueType. The cost is used by the scheduler to
1929 /// approximate register pressure.
1930 uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
1932 /// TransformToType - For any value types we are promoting or expanding, this
1933 /// contains the value type that we are changing to. For Expanded types, this
1934 /// contains one step of the expand (e.g. i64 -> i32), even if there are
1935 /// multiple steps required (e.g. i64 -> i16). For types natively supported
1936 /// by the system, this holds the same type (e.g. i32 -> i32).
1937 EVT TransformToType[MVT::LAST_VALUETYPE];
1939 /// OpActions - For each operation and each value type, keep a LegalizeAction
1940 /// that indicates how instruction selection should deal with the operation.
1941 /// Most operations are Legal (aka, supported natively by the target), but
1942 /// operations that are not should be described. Note that operations on
1943 /// non-legal value types are not described here.
1944 uint8_t OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END];
1946 /// LoadExtActions - For each load extension type and each value type,
1947 /// keep a LegalizeAction that indicates how instruction selection should deal
1948 /// with a load of a specific value type and extension type.
1949 uint8_t LoadExtActions[MVT::LAST_VALUETYPE][ISD::LAST_LOADEXT_TYPE];
1951 /// TruncStoreActions - For each value type pair keep a LegalizeAction that
1952 /// indicates whether a truncating store of a specific value type and
1953 /// truncating type is legal.
1954 uint8_t TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
1956 /// IndexedModeActions - For each indexed mode and each value type,
1957 /// keep a pair of LegalizeAction that indicates how instruction
1958 /// selection should deal with the load / store. The first dimension is the
1959 /// value_type for the reference. The second dimension represents the various
1960 /// modes for load store.
1961 uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
1963 /// CondCodeActions - For each condition code (ISD::CondCode) keep a
1964 /// LegalizeAction that indicates how instruction selection should
1965 /// deal with the condition code.
1966 /// Because each CC action takes up 2 bits, we need to have the array size
1967 /// be large enough to fit all of the value types. This can be done by
1968 /// dividing the MVT::LAST_VALUETYPE by 32 and adding one.
1969 uint64_t CondCodeActions[ISD::SETCC_INVALID][(MVT::LAST_VALUETYPE / 32) + 1];
1971 ValueTypeActionImpl ValueTypeActions;
1975 getTypeConversion(LLVMContext &Context, EVT VT) const {
1976 // If this is a simple type, use the ComputeRegisterProp mechanism.
1977 if (VT.isSimple()) {
1978 assert((unsigned)VT.getSimpleVT().SimpleTy <
1979 array_lengthof(TransformToType));
1980 EVT NVT = TransformToType[VT.getSimpleVT().SimpleTy];
1981 LegalizeTypeAction LA = ValueTypeActions.getTypeAction(VT.getSimpleVT());
1984 (!(NVT.isSimple() && LA != TypeLegal) ||
1985 ValueTypeActions.getTypeAction(NVT.getSimpleVT()) != TypePromoteInteger)
1986 && "Promote may not follow Expand or Promote");
1988 if (LA == TypeSplitVector)
1989 NVT = EVT::getVectorVT(Context, VT.getVectorElementType(),
1990 VT.getVectorNumElements() / 2);
1991 return LegalizeKind(LA, NVT);
1994 // Handle Extended Scalar Types.
1995 if (!VT.isVector()) {
1996 assert(VT.isInteger() && "Float types must be simple");
1997 unsigned BitSize = VT.getSizeInBits();
1998 // First promote to a power-of-two size, then expand if necessary.
1999 if (BitSize < 8 || !isPowerOf2_32(BitSize)) {
2000 EVT NVT = VT.getRoundIntegerType(Context);
2001 assert(NVT != VT && "Unable to round integer VT");
2002 LegalizeKind NextStep = getTypeConversion(Context, NVT);
2003 // Avoid multi-step promotion.
2004 if (NextStep.first == TypePromoteInteger) return NextStep;
2005 // Return rounded integer type.
2006 return LegalizeKind(TypePromoteInteger, NVT);
2009 return LegalizeKind(TypeExpandInteger,
2010 EVT::getIntegerVT(Context, VT.getSizeInBits()/2));
2013 // Handle vector types.
2014 unsigned NumElts = VT.getVectorNumElements();
2015 EVT EltVT = VT.getVectorElementType();
2017 // Vectors with only one element are always scalarized.
2019 return LegalizeKind(TypeScalarizeVector, EltVT);
2021 // Try to widen vector elements until a legal type is found.
2022 if (EltVT.isInteger()) {
2023 // Vectors with a number of elements that is not a power of two are always
2024 // widened, for example <3 x float> -> <4 x float>.
2025 if (!VT.isPow2VectorType()) {
2026 NumElts = (unsigned)NextPowerOf2(NumElts);
2027 EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts);
2028 return LegalizeKind(TypeWidenVector, NVT);
2031 // Examine the element type.
2032 LegalizeKind LK = getTypeConversion(Context, EltVT);
2034 // If type is to be expanded, split the vector.
2035 // <4 x i140> -> <2 x i140>
2036 if (LK.first == TypeExpandInteger)
2037 return LegalizeKind(TypeSplitVector,
2038 EVT::getVectorVT(Context, EltVT, NumElts / 2));
2040 // Promote the integer element types until a legal vector type is found
2041 // or until the element integer type is too big. If a legal type was not
2042 // found, fallback to the usual mechanism of widening/splitting the
2045 // Increase the bitwidth of the element to the next pow-of-two
2046 // (which is greater than 8 bits).
2047 EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits()
2048 ).getRoundIntegerType(Context);
2050 // Stop trying when getting a non-simple element type.
2051 // Note that vector elements may be greater than legal vector element
2052 // types. Example: X86 XMM registers hold 64bit element on 32bit systems.
2053 if (!EltVT.isSimple()) break;
2055 // Build a new vector type and check if it is legal.
2056 MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
2057 // Found a legal promoted vector type.
2058 if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal)
2059 return LegalizeKind(TypePromoteInteger,
2060 EVT::getVectorVT(Context, EltVT, NumElts));
2064 // Try to widen the vector until a legal type is found.
2065 // If there is no wider legal type, split the vector.
2067 // Round up to the next power of 2.
2068 NumElts = (unsigned)NextPowerOf2(NumElts);
2070 // If there is no simple vector type with this many elements then there
2071 // cannot be a larger legal vector type. Note that this assumes that
2072 // there are no skipped intermediate vector types in the simple types.
2073 if (!EltVT.isSimple()) break;
2074 MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
2075 if (LargerVector == MVT()) break;
2077 // If this type is legal then widen the vector.
2078 if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal)
2079 return LegalizeKind(TypeWidenVector, LargerVector);
2082 // Widen odd vectors to next power of two.
2083 if (!VT.isPow2VectorType()) {
2084 EVT NVT = VT.getPow2VectorType(Context);
2085 return LegalizeKind(TypeWidenVector, NVT);
2088 // Vectors with illegal element types are expanded.
2089 EVT NVT = EVT::getVectorVT(Context, EltVT, VT.getVectorNumElements() / 2);
2090 return LegalizeKind(TypeSplitVector, NVT);
2094 std::vector<std::pair<EVT, const TargetRegisterClass*> > AvailableRegClasses;
2096 /// TargetDAGCombineArray - Targets can specify ISD nodes that they would
2097 /// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(),
2098 /// which sets a bit in this array.
2100 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
2102 /// PromoteToType - For operations that must be promoted to a specific type,
2103 /// this holds the destination type. This map should be sparse, so don't hold
2106 /// Targets add entries to this map with AddPromotedToType(..), clients access
2107 /// this with getTypeToPromoteTo(..).
2108 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
2111 /// LibcallRoutineNames - Stores the name each libcall.
2113 const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
2115 /// CmpLibcallCCs - The ISD::CondCode that should be used to test the result
2116 /// of each of the comparison libcall against zero.
2117 ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
2119 /// LibcallCallingConvs - Stores the CallingConv that should be used for each
2121 CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
2124 /// When lowering \@llvm.memset this field specifies the maximum number of
2125 /// store operations that may be substituted for the call to memset. Targets
2126 /// must set this value based on the cost threshold for that target. Targets
2127 /// should assume that the memset will be done using as many of the largest
2128 /// store operations first, followed by smaller ones, if necessary, per
2129 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
2130 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
2131 /// store. This only applies to setting a constant array of a constant size.
2132 /// @brief Specify maximum number of store instructions per memset call.
2133 unsigned maxStoresPerMemset;
2135 /// Maximum number of stores operations that may be substituted for the call
2136 /// to memset, used for functions with OptSize attribute.
2137 unsigned maxStoresPerMemsetOptSize;
2139 /// When lowering \@llvm.memcpy this field specifies the maximum number of
2140 /// store operations that may be substituted for a call to memcpy. Targets
2141 /// must set this value based on the cost threshold for that target. Targets
2142 /// should assume that the memcpy will be done using as many of the largest
2143 /// store operations first, followed by smaller ones, if necessary, per
2144 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
2145 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
2146 /// and one 1-byte store. This only applies to copying a constant array of
2148 /// @brief Specify maximum bytes of store instructions per memcpy call.
2149 unsigned maxStoresPerMemcpy;
2151 /// Maximum number of store operations that may be substituted for a call
2152 /// to memcpy, used for functions with OptSize attribute.
2153 unsigned maxStoresPerMemcpyOptSize;
2155 /// When lowering \@llvm.memmove this field specifies the maximum number of
2156 /// store instructions that may be substituted for a call to memmove. Targets
2157 /// must set this value based on the cost threshold for that target. Targets
2158 /// should assume that the memmove will be done using as many of the largest
2159 /// store operations first, followed by smaller ones, if necessary, per
2160 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
2161 /// with 8-bit alignment would result in nine 1-byte stores. This only
2162 /// applies to copying a constant array of constant size.
2163 /// @brief Specify maximum bytes of store instructions per memmove call.
2164 unsigned maxStoresPerMemmove;
2166 /// Maximum number of store instructions that may be substituted for a call
2167 /// to memmove, used for functions with OpSize attribute.
2168 unsigned maxStoresPerMemmoveOptSize;
2170 /// This field specifies whether the target can benefit from code placement
2172 bool benefitFromCodePlacementOpt;
2174 /// predictableSelectIsExpensive - Tells the code generator that select is
2175 /// more expensive than a branch if the branch is usually predicted right.
2176 bool predictableSelectIsExpensive;
2179 /// isLegalRC - Return true if the value types that can be represented by the
2180 /// specified register class are all legal.
2181 bool isLegalRC(const TargetRegisterClass *RC) const;
2184 /// GetReturnInfo - Given an LLVM IR type and return type attributes,
2185 /// compute the return value EVTs and flags, and optionally also
2186 /// the offsets, if the return value is being lowered to memory.
2187 void GetReturnInfo(Type* ReturnType, Attributes attr,
2188 SmallVectorImpl<ISD::OutputArg> &Outs,
2189 const TargetLowering &TLI);
2191 } // end llvm namespace