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/CodeGen/DAGCombine.h"
27 #include "llvm/CodeGen/RuntimeLibcalls.h"
28 #include "llvm/CodeGen/SelectionDAGNodes.h"
29 #include "llvm/IR/Attributes.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/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.
71 /// TargetLoweringBase - This base class for TargetLowering contains the
72 /// SelectionDAG-independent parts that can be used from the rest of CodeGen.
73 class TargetLoweringBase {
74 TargetLoweringBase(const TargetLoweringBase&) LLVM_DELETED_FUNCTION;
75 void operator=(const TargetLoweringBase&) LLVM_DELETED_FUNCTION;
78 /// LegalizeAction - This enum indicates whether operations are valid for a
79 /// target, and if not, what action should be used to make them valid.
81 Legal, // The target natively supports this operation.
82 Promote, // This operation should be executed in a larger type.
83 Expand, // Try to expand this to other ops, otherwise use a libcall.
84 Custom // Use the LowerOperation hook to implement custom lowering.
87 /// LegalizeTypeAction - This enum indicates whether a types are legal for a
88 /// target, and if not, what action should be used to make them valid.
89 enum LegalizeTypeAction {
90 TypeLegal, // The target natively supports this type.
91 TypePromoteInteger, // Replace this integer with a larger one.
92 TypeExpandInteger, // Split this integer into two of half the size.
93 TypeSoftenFloat, // Convert this float to a same size integer type.
94 TypeExpandFloat, // Split this float into two of half the size.
95 TypeScalarizeVector, // Replace this one-element vector with its element.
96 TypeSplitVector, // Split this vector into two of half the size.
97 TypeWidenVector // This vector should be widened into a larger vector.
100 /// LegalizeKind holds the legalization kind that needs to happen to EVT
101 /// in order to type-legalize it.
102 typedef std::pair<LegalizeTypeAction, EVT> LegalizeKind;
104 enum BooleanContent { // How the target represents true/false values.
105 UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
106 ZeroOrOneBooleanContent, // All bits zero except for bit 0.
107 ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
110 enum SelectSupportKind {
111 ScalarValSelect, // The target supports scalar selects (ex: cmov).
112 ScalarCondVectorVal, // The target supports selects with a scalar condition
113 // and vector values (ex: cmov).
114 VectorMaskSelect // The target supports vector selects with a vector
115 // mask (ex: x86 blends).
118 static ISD::NodeType getExtendForContent(BooleanContent Content) {
120 case UndefinedBooleanContent:
121 // Extend by adding rubbish bits.
122 return ISD::ANY_EXTEND;
123 case ZeroOrOneBooleanContent:
124 // Extend by adding zero bits.
125 return ISD::ZERO_EXTEND;
126 case ZeroOrNegativeOneBooleanContent:
127 // Extend by copying the sign bit.
128 return ISD::SIGN_EXTEND;
130 llvm_unreachable("Invalid content kind");
133 /// NOTE: The constructor takes ownership of TLOF.
134 explicit TargetLoweringBase(const TargetMachine &TM,
135 const TargetLoweringObjectFile *TLOF);
136 virtual ~TargetLoweringBase();
138 const TargetMachine &getTargetMachine() const { return TM; }
139 const DataLayout *getDataLayout() const { return TD; }
140 const TargetLoweringObjectFile &getObjFileLowering() const { return TLOF; }
142 bool isBigEndian() const { return !IsLittleEndian; }
143 bool isLittleEndian() const { return IsLittleEndian; }
144 // Return the pointer type for the given address space, defaults to
145 // the pointer type from the data layout.
146 // FIXME: The default needs to be removed once all the code is updated.
147 virtual MVT getPointerTy(uint32_t AS = 0) const { return PointerTy; }
148 virtual MVT getShiftAmountTy(EVT LHSTy) const;
150 /// isSelectExpensive - Return true if the select operation is expensive for
152 bool isSelectExpensive() const { return SelectIsExpensive; }
154 virtual bool isSelectSupported(SelectSupportKind kind) const { return true; }
156 /// shouldSplitVectorElementType - Return true if a vector of the given type
157 /// should be split (TypeSplitVector) instead of promoted
158 /// (TypePromoteInteger) during type legalization.
159 virtual bool shouldSplitVectorElementType(EVT VT) const { return false; }
161 /// isIntDivCheap() - Return true if integer divide is usually cheaper than
162 /// a sequence of several shifts, adds, and multiplies for this target.
163 bool isIntDivCheap() const { return IntDivIsCheap; }
165 /// isSlowDivBypassed - Returns true if target has indicated at least one
166 /// type should be bypassed.
167 bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
169 /// getBypassSlowDivTypes - Returns map of slow types for division or
170 /// remainder with corresponding fast types
171 const DenseMap<unsigned int, unsigned int> &getBypassSlowDivWidths() const {
172 return BypassSlowDivWidths;
175 /// isPow2DivCheap() - Return true if pow2 div is cheaper than a chain of
177 bool isPow2DivCheap() const { return Pow2DivIsCheap; }
179 /// isJumpExpensive() - Return true if Flow Control is an expensive operation
180 /// that should be avoided.
181 bool isJumpExpensive() const { return JumpIsExpensive; }
183 /// isPredictableSelectExpensive - Return true if selects are only cheaper
184 /// than branches if the branch is unlikely to be predicted right.
185 bool isPredictableSelectExpensive() const {
186 return PredictableSelectIsExpensive;
189 /// getSetCCResultType - Return the ValueType of the result of SETCC
190 /// operations. Also used to obtain the target's preferred type for
191 /// the condition operand of SELECT and BRCOND nodes. In the case of
192 /// BRCOND the argument passed is MVT::Other since there are no other
193 /// operands to get a type hint from.
194 virtual EVT getSetCCResultType(EVT VT) const;
196 /// getCmpLibcallReturnType - Return the ValueType for comparison
197 /// libcalls. Comparions libcalls include floating point comparion calls,
198 /// and Ordered/Unordered check calls on floating point numbers.
200 MVT::SimpleValueType getCmpLibcallReturnType() const;
202 /// getBooleanContents - For targets without i1 registers, this gives the
203 /// nature of the high-bits of boolean values held in types wider than i1.
204 /// "Boolean values" are special true/false values produced by nodes like
205 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
206 /// Not to be confused with general values promoted from i1.
207 /// Some cpus distinguish between vectors of boolean and scalars; the isVec
208 /// parameter selects between the two kinds. For example on X86 a scalar
209 /// boolean should be zero extended from i1, while the elements of a vector
210 /// of booleans should be sign extended from i1.
211 BooleanContent getBooleanContents(bool isVec) const {
212 return isVec ? BooleanVectorContents : BooleanContents;
215 /// getSchedulingPreference - Return target scheduling preference.
216 Sched::Preference getSchedulingPreference() const {
217 return SchedPreferenceInfo;
220 /// getSchedulingPreference - Some scheduler, e.g. hybrid, can switch to
221 /// different scheduling heuristics for different nodes. This function returns
222 /// the preference (or none) for the given node.
223 virtual Sched::Preference getSchedulingPreference(SDNode *) const {
227 /// getRegClassFor - Return the register class that should be used for the
228 /// specified value type.
229 virtual const TargetRegisterClass *getRegClassFor(MVT VT) const {
230 const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
231 assert(RC && "This value type is not natively supported!");
235 /// getRepRegClassFor - Return the 'representative' register class for the
236 /// specified value type. The 'representative' register class is the largest
237 /// legal super-reg register class for the register class of the value type.
238 /// For example, on i386 the rep register class for i8, i16, and i32 are GR32;
239 /// while the rep register class is GR64 on x86_64.
240 virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
241 const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
245 /// getRepRegClassCostFor - Return the cost of the 'representative' register
246 /// class for the specified value type.
247 virtual uint8_t getRepRegClassCostFor(MVT VT) const {
248 return RepRegClassCostForVT[VT.SimpleTy];
251 /// isTypeLegal - Return true if the target has native support for the
252 /// specified value type. This means that it has a register that directly
253 /// holds it without promotions or expansions.
254 bool isTypeLegal(EVT VT) const {
255 assert(!VT.isSimple() ||
256 (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
257 return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != 0;
260 class ValueTypeActionImpl {
261 /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
262 /// that indicates how instruction selection should deal with the type.
263 uint8_t ValueTypeActions[MVT::LAST_VALUETYPE];
266 ValueTypeActionImpl() {
267 std::fill(ValueTypeActions, array_endof(ValueTypeActions), 0);
270 LegalizeTypeAction getTypeAction(MVT VT) const {
271 return (LegalizeTypeAction)ValueTypeActions[VT.SimpleTy];
274 void setTypeAction(MVT VT, LegalizeTypeAction Action) {
275 unsigned I = VT.SimpleTy;
276 ValueTypeActions[I] = Action;
280 const ValueTypeActionImpl &getValueTypeActions() const {
281 return ValueTypeActions;
284 /// getTypeAction - Return how we should legalize values of this type, either
285 /// it is already legal (return 'Legal') or we need to promote it to a larger
286 /// type (return 'Promote'), or we need to expand it into multiple registers
287 /// of smaller integer type (return 'Expand'). 'Custom' is not an option.
288 LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const {
289 return getTypeConversion(Context, VT).first;
291 LegalizeTypeAction getTypeAction(MVT VT) const {
292 return ValueTypeActions.getTypeAction(VT);
295 /// getTypeToTransformTo - For types supported by the target, this is an
296 /// identity function. For types that must be promoted to larger types, this
297 /// returns the larger type to promote to. For integer types that are larger
298 /// than the largest integer register, this contains one step in the expansion
299 /// to get to the smaller register. For illegal floating point types, this
300 /// returns the integer type to transform to.
301 EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
302 return getTypeConversion(Context, VT).second;
305 /// getTypeToExpandTo - For types supported by the target, this is an
306 /// identity function. For types that must be expanded (i.e. integer types
307 /// that are larger than the largest integer register or illegal floating
308 /// point types), this returns the largest legal type it will be expanded to.
309 EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
310 assert(!VT.isVector());
312 switch (getTypeAction(Context, VT)) {
315 case TypeExpandInteger:
316 VT = getTypeToTransformTo(Context, VT);
319 llvm_unreachable("Type is not legal nor is it to be expanded!");
324 /// getVectorTypeBreakdown - Vector types are broken down into some number of
325 /// legal first class types. For example, EVT::v8f32 maps to 2 EVT::v4f32
326 /// with Altivec or SSE1, or 8 promoted EVT::f64 values with the X86 FP stack.
327 /// Similarly, EVT::v2i64 turns into 4 EVT::i32 values with both PPC and X86.
329 /// This method returns the number of registers needed, and the VT for each
330 /// register. It also returns the VT and quantity of the intermediate values
331 /// before they are promoted/expanded.
333 unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
335 unsigned &NumIntermediates,
336 MVT &RegisterVT) const;
338 /// getTgtMemIntrinsic: Given an intrinsic, checks if on the target the
339 /// intrinsic will need to map to a MemIntrinsicNode (touches memory). If
340 /// this is the case, it returns true and store the intrinsic
341 /// information into the IntrinsicInfo that was passed to the function.
342 struct IntrinsicInfo {
343 unsigned opc; // target opcode
344 EVT memVT; // memory VT
345 const Value* ptrVal; // value representing memory location
346 int offset; // offset off of ptrVal
347 unsigned align; // alignment
348 bool vol; // is volatile?
349 bool readMem; // reads memory?
350 bool writeMem; // writes memory?
353 virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
354 unsigned /*Intrinsic*/) const {
358 /// isFPImmLegal - Returns true if the target can instruction select the
359 /// specified FP immediate natively. If false, the legalizer will materialize
360 /// the FP immediate as a load from a constant pool.
361 virtual bool isFPImmLegal(const APFloat &/*Imm*/, EVT /*VT*/) const {
365 /// isShuffleMaskLegal - Targets can use this to indicate that they only
366 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
367 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
368 /// are assumed to be legal.
369 virtual bool isShuffleMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
374 /// canOpTrap - Returns true if the operation can trap for the value type.
375 /// VT must be a legal type. By default, we optimistically assume most
376 /// operations don't trap except for divide and remainder.
377 virtual bool canOpTrap(unsigned Op, EVT VT) const;
379 /// isVectorClearMaskLegal - Similar to isShuffleMaskLegal. This is
380 /// used by Targets can use this to indicate if there is a suitable
381 /// VECTOR_SHUFFLE that can be used to replace a VAND with a constant
383 virtual bool isVectorClearMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
388 /// getOperationAction - Return how this operation should be treated: either
389 /// it is legal, needs to be promoted to a larger size, needs to be
390 /// expanded to some other code sequence, or the target has a custom expander
392 LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
393 if (VT.isExtended()) return Expand;
394 // If a target-specific SDNode requires legalization, require the target
395 // to provide custom legalization for it.
396 if (Op > array_lengthof(OpActions[0])) return Custom;
397 unsigned I = (unsigned) VT.getSimpleVT().SimpleTy;
398 return (LegalizeAction)OpActions[I][Op];
401 /// isOperationLegalOrCustom - Return true if the specified operation is
402 /// legal on this target or can be made legal with custom lowering. This
403 /// is used to help guide high-level lowering decisions.
404 bool isOperationLegalOrCustom(unsigned Op, EVT VT) const {
405 return (VT == MVT::Other || isTypeLegal(VT)) &&
406 (getOperationAction(Op, VT) == Legal ||
407 getOperationAction(Op, VT) == Custom);
410 /// isOperationLegalOrPromote - Return true if the specified operation is
411 /// legal on this target or can be made legal using promotion. This
412 /// is used to help guide high-level lowering decisions.
413 bool isOperationLegalOrPromote(unsigned Op, EVT VT) const {
414 return (VT == MVT::Other || isTypeLegal(VT)) &&
415 (getOperationAction(Op, VT) == Legal ||
416 getOperationAction(Op, VT) == Promote);
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, MVT VT) const {
438 assert(ExtType < ISD::LAST_LOADEXT_TYPE && VT < MVT::LAST_VALUETYPE &&
439 "Table isn't big enough!");
440 return (LegalizeAction)LoadExtActions[VT.SimpleTy][ExtType];
443 /// isLoadExtLegal - Return true if the specified load with extension is legal
445 bool isLoadExtLegal(unsigned ExtType, EVT VT) const {
446 return VT.isSimple() &&
447 getLoadExtAction(ExtType, VT.getSimpleVT()) == 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(MVT ValVT, MVT MemVT) const {
455 assert(ValVT < MVT::LAST_VALUETYPE && MemVT < MVT::LAST_VALUETYPE &&
456 "Table isn't big enough!");
457 return (LegalizeAction)TruncStoreActions[ValVT.SimpleTy]
461 /// isTruncStoreLegal - Return true if the specified store with truncation is
462 /// legal on this target.
463 bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
464 return isTypeLegal(ValVT) && MemVT.isSimple() &&
465 getTruncStoreAction(ValVT.getSimpleVT(), MemVT.getSimpleVT()) == Legal;
468 /// getIndexedLoadAction - Return how the indexed load should be treated:
469 /// either it is legal, needs to be promoted to a larger size, needs to be
470 /// expanded to some other code sequence, or the target has a custom expander
473 getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
474 assert(IdxMode < ISD::LAST_INDEXED_MODE && VT < MVT::LAST_VALUETYPE &&
475 "Table isn't big enough!");
476 unsigned Ty = (unsigned)VT.SimpleTy;
477 return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] & 0xf0) >> 4);
480 /// isIndexedLoadLegal - Return true if the specified indexed load is legal
482 bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
483 return VT.isSimple() &&
484 (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
485 getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
488 /// getIndexedStoreAction - Return how the indexed store should be treated:
489 /// either it is legal, needs to be promoted to a larger size, needs to be
490 /// expanded to some other code sequence, or the target has a custom expander
493 getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
494 assert(IdxMode < ISD::LAST_INDEXED_MODE && VT < MVT::LAST_VALUETYPE &&
495 "Table isn't big enough!");
496 unsigned Ty = (unsigned)VT.SimpleTy;
497 return (LegalizeAction)(IndexedModeActions[Ty][IdxMode] & 0x0f);
500 /// isIndexedStoreLegal - Return true if the specified indexed load is legal
502 bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
503 return VT.isSimple() &&
504 (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
505 getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
508 /// getCondCodeAction - Return how the condition code should be treated:
509 /// either it is legal, needs to be expanded to some other code sequence,
510 /// or the target has a custom expander for it.
512 getCondCodeAction(ISD::CondCode CC, MVT VT) const {
513 assert((unsigned)CC < array_lengthof(CondCodeActions) &&
514 (unsigned)VT.SimpleTy < sizeof(CondCodeActions[0])*4 &&
515 "Table isn't big enough!");
516 /// The lower 5 bits of the SimpleTy index into Nth 2bit set from the 64bit
517 /// value and the upper 27 bits index into the second dimension of the
518 /// array to select what 64bit value to use.
519 LegalizeAction Action = (LegalizeAction)
520 ((CondCodeActions[CC][VT.SimpleTy >> 5] >> (2*(VT.SimpleTy & 0x1F))) & 3);
521 assert(Action != Promote && "Can't promote condition code!");
525 /// isCondCodeLegal - Return true if the specified condition code is legal
527 bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
529 getCondCodeAction(CC, VT) == Legal ||
530 getCondCodeAction(CC, VT) == Custom;
534 /// getTypeToPromoteTo - If the action for this operation is to promote, this
535 /// method returns the ValueType to promote to.
536 MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
537 assert(getOperationAction(Op, VT) == Promote &&
538 "This operation isn't promoted!");
540 // See if this has an explicit type specified.
541 std::map<std::pair<unsigned, MVT::SimpleValueType>,
542 MVT::SimpleValueType>::const_iterator PTTI =
543 PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
544 if (PTTI != PromoteToType.end()) return PTTI->second;
546 assert((VT.isInteger() || VT.isFloatingPoint()) &&
547 "Cannot autopromote this type, add it with AddPromotedToType.");
551 NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
552 assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
553 "Didn't find type to promote to!");
554 } while (!isTypeLegal(NVT) ||
555 getOperationAction(Op, NVT) == Promote);
559 /// getValueType - Return the EVT corresponding to this LLVM type.
560 /// This is fixed by the LLVM operations except for the pointer size. If
561 /// AllowUnknown is true, this will return MVT::Other for types with no EVT
562 /// counterpart (e.g. structs), otherwise it will assert.
563 EVT getValueType(Type *Ty, bool AllowUnknown = false) const {
564 // Lower scalar pointers to native pointer types.
565 if (Ty->isPointerTy()) return PointerTy;
567 if (Ty->isVectorTy()) {
568 VectorType *VTy = cast<VectorType>(Ty);
569 Type *Elm = VTy->getElementType();
570 // Lower vectors of pointers to native pointer types.
571 if (Elm->isPointerTy())
572 Elm = EVT(PointerTy).getTypeForEVT(Ty->getContext());
573 return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
574 VTy->getNumElements());
576 return EVT::getEVT(Ty, AllowUnknown);
579 /// Return the MVT corresponding to this LLVM type. See getValueType.
580 MVT getSimpleValueType(Type *Ty, bool AllowUnknown = false) const {
581 return getValueType(Ty, AllowUnknown).getSimpleVT();
584 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
585 /// function arguments in the caller parameter area. This is the actual
586 /// alignment, not its logarithm.
587 virtual unsigned getByValTypeAlignment(Type *Ty) const;
589 /// getRegisterType - Return the type of registers that this ValueType will
590 /// eventually require.
591 MVT getRegisterType(MVT VT) const {
592 assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
593 return RegisterTypeForVT[VT.SimpleTy];
596 /// getRegisterType - Return the type of registers that this ValueType will
597 /// eventually require.
598 MVT getRegisterType(LLVMContext &Context, EVT VT) const {
600 assert((unsigned)VT.getSimpleVT().SimpleTy <
601 array_lengthof(RegisterTypeForVT));
602 return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
607 unsigned NumIntermediates;
608 (void)getVectorTypeBreakdown(Context, VT, VT1,
609 NumIntermediates, RegisterVT);
612 if (VT.isInteger()) {
613 return getRegisterType(Context, getTypeToTransformTo(Context, VT));
615 llvm_unreachable("Unsupported extended type!");
618 /// getNumRegisters - Return the number of registers that this ValueType will
619 /// eventually require. This is one for any types promoted to live in larger
620 /// registers, but may be more than one for types (like i64) that are split
621 /// into pieces. For types like i140, which are first promoted then expanded,
622 /// it is the number of registers needed to hold all the bits of the original
623 /// type. For an i140 on a 32 bit machine this means 5 registers.
624 unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
626 assert((unsigned)VT.getSimpleVT().SimpleTy <
627 array_lengthof(NumRegistersForVT));
628 return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
633 unsigned NumIntermediates;
634 return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
636 if (VT.isInteger()) {
637 unsigned BitWidth = VT.getSizeInBits();
638 unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
639 return (BitWidth + RegWidth - 1) / RegWidth;
641 llvm_unreachable("Unsupported extended type!");
644 /// ShouldShrinkFPConstant - If true, then instruction selection should
645 /// seek to shrink the FP constant of the specified type to a smaller type
646 /// in order to save space and / or reduce runtime.
647 virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
649 /// hasTargetDAGCombine - If true, the target has custom DAG combine
650 /// transformations that it can perform for the specified node.
651 bool hasTargetDAGCombine(ISD::NodeType NT) const {
652 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
653 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
656 /// This function returns the maximum number of store operations permitted
657 /// to replace a call to llvm.memset. The value is set by the target at the
658 /// performance threshold for such a replacement. If OptSize is true,
659 /// return the limit for functions that have OptSize attribute.
660 /// @brief Get maximum # of store operations permitted for llvm.memset
661 unsigned getMaxStoresPerMemset(bool OptSize) const {
662 return OptSize ? MaxStoresPerMemsetOptSize : MaxStoresPerMemset;
665 /// This function returns the maximum number of store operations permitted
666 /// to replace a call to llvm.memcpy. The value is set by the target at the
667 /// performance threshold for such a replacement. If OptSize is true,
668 /// return the limit for functions that have OptSize attribute.
669 /// @brief Get maximum # of store operations permitted for llvm.memcpy
670 unsigned getMaxStoresPerMemcpy(bool OptSize) const {
671 return OptSize ? MaxStoresPerMemcpyOptSize : MaxStoresPerMemcpy;
674 /// This function returns the maximum number of store operations permitted
675 /// to replace a call to llvm.memmove. The value is set by the target at the
676 /// performance threshold for such a replacement. If OptSize is true,
677 /// return the limit for functions that have OptSize attribute.
678 /// @brief Get maximum # of store operations permitted for llvm.memmove
679 unsigned getMaxStoresPerMemmove(bool OptSize) const {
680 return OptSize ? MaxStoresPerMemmoveOptSize : MaxStoresPerMemmove;
683 /// This function returns true if the target allows unaligned memory accesses.
684 /// of the specified type. If true, it also returns whether the unaligned
685 /// memory access is "fast" in the second argument by reference. This is used,
686 /// for example, in situations where an array copy/move/set is converted to a
687 /// sequence of store operations. It's use helps to ensure that such
688 /// replacements don't generate code that causes an alignment error (trap) on
689 /// the target machine.
690 /// @brief Determine if the target supports unaligned memory accesses.
691 virtual bool allowsUnalignedMemoryAccesses(EVT, bool *Fast = 0) const {
695 /// This function returns true if the target would benefit from code placement
697 /// @brief Determine if the target should perform code placement optimization.
698 bool shouldOptimizeCodePlacement() const {
699 return BenefitFromCodePlacementOpt;
702 /// getOptimalMemOpType - Returns the target specific optimal type for load
703 /// and store operations as a result of memset, memcpy, and memmove
704 /// lowering. If DstAlign is zero that means it's safe to destination
705 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
706 /// means there isn't a need to check it against alignment requirement,
707 /// probably because the source does not need to be loaded. If 'IsMemset' is
708 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
709 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
710 /// source is constant so it does not need to be loaded.
711 /// It returns EVT::Other if the type should be determined using generic
712 /// target-independent logic.
713 virtual EVT getOptimalMemOpType(uint64_t /*Size*/,
714 unsigned /*DstAlign*/, unsigned /*SrcAlign*/,
717 bool /*MemcpyStrSrc*/,
718 MachineFunction &/*MF*/) const {
722 /// isSafeMemOpType - Returns true if it's safe to use load / store of the
723 /// specified type to expand memcpy / memset inline. This is mostly true
724 /// for all types except for some special cases. For example, on X86
725 /// targets without SSE2 f64 load / store are done with fldl / fstpl which
726 /// also does type conversion. Note the specified type doesn't have to be
727 /// legal as the hook is used before type legalization.
728 virtual bool isSafeMemOpType(MVT VT) const {
732 /// usesUnderscoreSetJmp - Determine if we should use _setjmp or setjmp
733 /// to implement llvm.setjmp.
734 bool usesUnderscoreSetJmp() const {
735 return UseUnderscoreSetJmp;
738 /// usesUnderscoreLongJmp - Determine if we should use _longjmp or longjmp
739 /// to implement llvm.longjmp.
740 bool usesUnderscoreLongJmp() const {
741 return UseUnderscoreLongJmp;
744 /// supportJumpTables - return whether the target can generate code for
746 bool supportJumpTables() const {
747 return SupportJumpTables;
750 /// getMinimumJumpTableEntries - return integer threshold on number of
751 /// blocks to use jump tables rather than if sequence.
752 int getMinimumJumpTableEntries() const {
753 return MinimumJumpTableEntries;
756 /// getStackPointerRegisterToSaveRestore - If a physical register, this
757 /// specifies the register that llvm.savestack/llvm.restorestack should save
759 unsigned getStackPointerRegisterToSaveRestore() const {
760 return StackPointerRegisterToSaveRestore;
763 /// getExceptionPointerRegister - If a physical register, this returns
764 /// the register that receives the exception address on entry to a landing
766 unsigned getExceptionPointerRegister() const {
767 return ExceptionPointerRegister;
770 /// getExceptionSelectorRegister - If a physical register, this returns
771 /// the register that receives the exception typeid on entry to a landing
773 unsigned getExceptionSelectorRegister() const {
774 return ExceptionSelectorRegister;
777 /// getJumpBufSize - returns the target's jmp_buf size in bytes (if never
778 /// set, the default is 200)
779 unsigned getJumpBufSize() const {
783 /// getJumpBufAlignment - returns the target's jmp_buf alignment in bytes
784 /// (if never set, the default is 0)
785 unsigned getJumpBufAlignment() const {
786 return JumpBufAlignment;
789 /// getMinStackArgumentAlignment - return the minimum stack alignment of an
791 unsigned getMinStackArgumentAlignment() const {
792 return MinStackArgumentAlignment;
795 /// getMinFunctionAlignment - return the minimum function alignment.
797 unsigned getMinFunctionAlignment() const {
798 return MinFunctionAlignment;
801 /// getPrefFunctionAlignment - return the preferred function alignment.
803 unsigned getPrefFunctionAlignment() const {
804 return PrefFunctionAlignment;
807 /// getPrefLoopAlignment - return the preferred loop alignment.
809 unsigned getPrefLoopAlignment() const {
810 return PrefLoopAlignment;
813 /// getShouldFoldAtomicFences - return whether the combiner should fold
814 /// fence MEMBARRIER instructions into the atomic intrinsic instructions.
816 bool getShouldFoldAtomicFences() const {
817 return ShouldFoldAtomicFences;
820 /// getInsertFencesFor - return whether the DAG builder should automatically
821 /// insert fences and reduce ordering for atomics.
823 bool getInsertFencesForAtomic() const {
824 return InsertFencesForAtomic;
827 /// getStackCookieLocation - Return true if the target stores stack
828 /// protector cookies at a fixed offset in some non-standard address
829 /// space, and populates the address space and offset as
831 virtual bool getStackCookieLocation(unsigned &/*AddressSpace*/,
832 unsigned &/*Offset*/) const {
836 /// getMaximalGlobalOffset - Returns the maximal possible offset which can be
837 /// used for loads / stores from the global.
838 virtual unsigned getMaximalGlobalOffset() const {
842 //===--------------------------------------------------------------------===//
843 /// \name Helpers for TargetTransformInfo implementations
846 /// Get the ISD node that corresponds to the Instruction class opcode.
847 int InstructionOpcodeToISD(unsigned Opcode) const;
849 /// Estimate the cost of type-legalization and the legalized type.
850 std::pair<unsigned, MVT> getTypeLegalizationCost(Type *Ty) const;
854 //===--------------------------------------------------------------------===//
855 // TargetLowering Configuration Methods - These methods should be invoked by
856 // the derived class constructor to configure this object for the target.
860 /// setBooleanContents - Specify how the target extends the result of a
861 /// boolean value from i1 to a wider type. See getBooleanContents.
862 void setBooleanContents(BooleanContent Ty) { BooleanContents = Ty; }
863 /// setBooleanVectorContents - Specify how the target extends the result
864 /// of a vector boolean value from a vector of i1 to a wider type. See
865 /// getBooleanContents.
866 void setBooleanVectorContents(BooleanContent Ty) {
867 BooleanVectorContents = Ty;
870 /// setSchedulingPreference - Specify the target scheduling preference.
871 void setSchedulingPreference(Sched::Preference Pref) {
872 SchedPreferenceInfo = Pref;
875 /// setUseUnderscoreSetJmp - Indicate whether this target prefers to
876 /// use _setjmp to implement llvm.setjmp or the non _ version.
877 /// Defaults to false.
878 void setUseUnderscoreSetJmp(bool Val) {
879 UseUnderscoreSetJmp = Val;
882 /// setUseUnderscoreLongJmp - Indicate whether this target prefers to
883 /// use _longjmp to implement llvm.longjmp or the non _ version.
884 /// Defaults to false.
885 void setUseUnderscoreLongJmp(bool Val) {
886 UseUnderscoreLongJmp = Val;
889 /// setSupportJumpTables - Indicate whether the target can generate code for
891 void setSupportJumpTables(bool Val) {
892 SupportJumpTables = Val;
895 /// setMinimumJumpTableEntries - Indicate the number of blocks to generate
896 /// jump tables rather than if sequence.
897 void setMinimumJumpTableEntries(int Val) {
898 MinimumJumpTableEntries = Val;
901 /// setStackPointerRegisterToSaveRestore - If set to a physical register, this
902 /// specifies the register that llvm.savestack/llvm.restorestack should save
904 void setStackPointerRegisterToSaveRestore(unsigned R) {
905 StackPointerRegisterToSaveRestore = R;
908 /// setExceptionPointerRegister - If set to a physical register, this sets
909 /// the register that receives the exception address on entry to a landing
911 void setExceptionPointerRegister(unsigned R) {
912 ExceptionPointerRegister = R;
915 /// setExceptionSelectorRegister - If set to a physical register, this sets
916 /// the register that receives the exception typeid on entry to a landing
918 void setExceptionSelectorRegister(unsigned R) {
919 ExceptionSelectorRegister = R;
922 /// SelectIsExpensive - Tells the code generator not to expand operations
923 /// into sequences that use the select operations if possible.
924 void setSelectIsExpensive(bool isExpensive = true) {
925 SelectIsExpensive = isExpensive;
928 /// JumpIsExpensive - Tells the code generator not to expand sequence of
929 /// operations into a separate sequences that increases the amount of
931 void setJumpIsExpensive(bool isExpensive = true) {
932 JumpIsExpensive = isExpensive;
935 /// setIntDivIsCheap - Tells the code generator that integer divide is
936 /// expensive, and if possible, should be replaced by an alternate sequence
937 /// of instructions not containing an integer divide.
938 void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
940 /// addBypassSlowDiv - Tells the code generator which bitwidths to bypass.
941 void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
942 BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
945 /// setPow2DivIsCheap - Tells the code generator that it shouldn't generate
946 /// srl/add/sra for a signed divide by power of two, and let the target handle
948 void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
950 /// addRegisterClass - Add the specified register class as an available
951 /// regclass for the specified value type. This indicates the selector can
952 /// handle values of that class natively.
953 void addRegisterClass(MVT VT, const TargetRegisterClass *RC) {
954 assert((unsigned)VT.SimpleTy < array_lengthof(RegClassForVT));
955 AvailableRegClasses.push_back(std::make_pair(VT, RC));
956 RegClassForVT[VT.SimpleTy] = RC;
959 /// findRepresentativeClass - Return the largest legal super-reg register class
960 /// of the register class for the specified type and its associated "cost".
961 virtual std::pair<const TargetRegisterClass*, uint8_t>
962 findRepresentativeClass(MVT VT) const;
964 /// computeRegisterProperties - Once all of the register classes are added,
965 /// this allows us to compute derived properties we expose.
966 void computeRegisterProperties();
968 /// setOperationAction - Indicate that the specified operation does not work
969 /// with the specified type and indicate what to do about it.
970 void setOperationAction(unsigned Op, MVT VT,
971 LegalizeAction Action) {
972 assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
973 OpActions[(unsigned)VT.SimpleTy][Op] = (uint8_t)Action;
976 /// setLoadExtAction - Indicate that the specified load with extension does
977 /// not work with the specified type and indicate what to do about it.
978 void setLoadExtAction(unsigned ExtType, MVT VT,
979 LegalizeAction Action) {
980 assert(ExtType < ISD::LAST_LOADEXT_TYPE && VT < MVT::LAST_VALUETYPE &&
981 "Table isn't big enough!");
982 LoadExtActions[VT.SimpleTy][ExtType] = (uint8_t)Action;
985 /// setTruncStoreAction - Indicate that the specified truncating store does
986 /// not work with the specified type and indicate what to do about it.
987 void setTruncStoreAction(MVT ValVT, MVT MemVT,
988 LegalizeAction Action) {
989 assert(ValVT < MVT::LAST_VALUETYPE && MemVT < MVT::LAST_VALUETYPE &&
990 "Table isn't big enough!");
991 TruncStoreActions[ValVT.SimpleTy][MemVT.SimpleTy] = (uint8_t)Action;
994 /// setIndexedLoadAction - Indicate that the specified indexed load does or
995 /// does not work with the specified type and indicate what to do abort
996 /// it. NOTE: All indexed mode loads are initialized to Expand in
997 /// TargetLowering.cpp
998 void setIndexedLoadAction(unsigned IdxMode, MVT VT,
999 LegalizeAction Action) {
1000 assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
1001 (unsigned)Action < 0xf && "Table isn't big enough!");
1002 // Load action are kept in the upper half.
1003 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0xf0;
1004 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action) <<4;
1007 /// setIndexedStoreAction - Indicate that the specified indexed store does or
1008 /// does not work with the specified type and indicate what to do about
1009 /// it. NOTE: All indexed mode stores are initialized to Expand in
1010 /// TargetLowering.cpp
1011 void setIndexedStoreAction(unsigned IdxMode, MVT VT,
1012 LegalizeAction Action) {
1013 assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
1014 (unsigned)Action < 0xf && "Table isn't big enough!");
1015 // Store action are kept in the lower half.
1016 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0x0f;
1017 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action);
1020 /// setCondCodeAction - Indicate that the specified condition code is or isn't
1021 /// supported on the target and indicate what to do about it.
1022 void setCondCodeAction(ISD::CondCode CC, MVT VT,
1023 LegalizeAction Action) {
1024 assert(VT < MVT::LAST_VALUETYPE &&
1025 (unsigned)CC < array_lengthof(CondCodeActions) &&
1026 "Table isn't big enough!");
1027 /// The lower 5 bits of the SimpleTy index into Nth 2bit set from the 64bit
1028 /// value and the upper 27 bits index into the second dimension of the
1029 /// array to select what 64bit value to use.
1030 CondCodeActions[(unsigned)CC][VT.SimpleTy >> 5]
1031 &= ~(uint64_t(3UL) << (VT.SimpleTy & 0x1F)*2);
1032 CondCodeActions[(unsigned)CC][VT.SimpleTy >> 5]
1033 |= (uint64_t)Action << (VT.SimpleTy & 0x1F)*2;
1036 /// AddPromotedToType - If Opc/OrigVT is specified as being promoted, the
1037 /// promotion code defaults to trying a larger integer/fp until it can find
1038 /// one that works. If that default is insufficient, this method can be used
1039 /// by the target to override the default.
1040 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1041 PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
1044 /// setTargetDAGCombine - Targets should invoke this method for each target
1045 /// independent node that they want to provide a custom DAG combiner for by
1046 /// implementing the PerformDAGCombine virtual method.
1047 void setTargetDAGCombine(ISD::NodeType NT) {
1048 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1049 TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
1052 /// setJumpBufSize - Set the target's required jmp_buf buffer size (in
1053 /// bytes); default is 200
1054 void setJumpBufSize(unsigned Size) {
1058 /// setJumpBufAlignment - Set the target's required jmp_buf buffer
1059 /// alignment (in bytes); default is 0
1060 void setJumpBufAlignment(unsigned Align) {
1061 JumpBufAlignment = Align;
1064 /// setMinFunctionAlignment - Set the target's minimum function alignment (in
1066 void setMinFunctionAlignment(unsigned Align) {
1067 MinFunctionAlignment = Align;
1070 /// setPrefFunctionAlignment - Set the target's preferred function alignment.
1071 /// This should be set if there is a performance benefit to
1072 /// higher-than-minimum alignment (in log2(bytes))
1073 void setPrefFunctionAlignment(unsigned Align) {
1074 PrefFunctionAlignment = Align;
1077 /// setPrefLoopAlignment - Set the target's preferred loop alignment. Default
1078 /// alignment is zero, it means the target does not care about loop alignment.
1079 /// The alignment is specified in log2(bytes).
1080 void setPrefLoopAlignment(unsigned Align) {
1081 PrefLoopAlignment = Align;
1084 /// setMinStackArgumentAlignment - Set the minimum stack alignment of an
1085 /// argument (in log2(bytes)).
1086 void setMinStackArgumentAlignment(unsigned Align) {
1087 MinStackArgumentAlignment = Align;
1090 /// setShouldFoldAtomicFences - Set if the target's implementation of the
1091 /// atomic operation intrinsics includes locking. Default is false.
1092 void setShouldFoldAtomicFences(bool fold) {
1093 ShouldFoldAtomicFences = fold;
1096 /// setInsertFencesForAtomic - Set if the DAG builder should
1097 /// automatically insert fences and reduce the order of atomic memory
1098 /// operations to Monotonic.
1099 void setInsertFencesForAtomic(bool fence) {
1100 InsertFencesForAtomic = fence;
1104 //===--------------------------------------------------------------------===//
1105 // Addressing mode description hooks (used by LSR etc).
1108 /// GetAddrModeArguments - CodeGenPrepare sinks address calculations into the
1109 /// same BB as Load/Store instructions reading the address. This allows as
1110 /// much computation as possible to be done in the address mode for that
1111 /// operand. This hook lets targets also pass back when this should be done
1112 /// on intrinsics which load/store.
1113 virtual bool GetAddrModeArguments(IntrinsicInst *I,
1114 SmallVectorImpl<Value*> &Ops,
1115 Type *&AccessTy) const {
1119 /// AddrMode - This represents an addressing mode of:
1120 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
1121 /// If BaseGV is null, there is no BaseGV.
1122 /// If BaseOffs is zero, there is no base offset.
1123 /// If HasBaseReg is false, there is no base register.
1124 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
1128 GlobalValue *BaseGV;
1132 AddrMode() : BaseGV(0), BaseOffs(0), HasBaseReg(false), Scale(0) {}
1135 /// isLegalAddressingMode - Return true if the addressing mode represented by
1136 /// AM is legal for this target, for a load/store of the specified type.
1137 /// The type may be VoidTy, in which case only return true if the addressing
1138 /// mode is legal for a load/store of any legal type.
1139 /// TODO: Handle pre/postinc as well.
1140 virtual bool isLegalAddressingMode(const AddrMode &AM, Type *Ty) const;
1142 /// isLegalICmpImmediate - Return true if the specified immediate is legal
1143 /// icmp immediate, that is the target has icmp instructions which can compare
1144 /// a register against the immediate without having to materialize the
1145 /// immediate into a register.
1146 virtual bool isLegalICmpImmediate(int64_t) const {
1150 /// isLegalAddImmediate - Return true if the specified immediate is legal
1151 /// add immediate, that is the target has add instructions which can add
1152 /// a register with the immediate without having to materialize the
1153 /// immediate into a register.
1154 virtual bool isLegalAddImmediate(int64_t) const {
1158 /// isTruncateFree - Return true if it's free to truncate a value of
1159 /// type Ty1 to type Ty2. e.g. On x86 it's free to truncate a i32 value in
1160 /// register EAX to i16 by referencing its sub-register AX.
1161 virtual bool isTruncateFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1165 virtual bool isTruncateFree(EVT /*VT1*/, EVT /*VT2*/) const {
1169 /// isZExtFree - Return true if any actual instruction that defines a
1170 /// value of type Ty1 implicitly zero-extends the value to Ty2 in the result
1171 /// register. This does not necessarily include registers defined in
1172 /// unknown ways, such as incoming arguments, or copies from unknown
1173 /// virtual registers. Also, if isTruncateFree(Ty2, Ty1) is true, this
1174 /// does not necessarily apply to truncate instructions. e.g. on x86-64,
1175 /// all instructions that define 32-bit values implicit zero-extend the
1176 /// result out to 64 bits.
1177 virtual bool isZExtFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1181 virtual bool isZExtFree(EVT /*VT1*/, EVT /*VT2*/) const {
1185 /// isZExtFree - Return true if zero-extending the specific node Val to type
1186 /// VT2 is free (either because it's implicitly zero-extended such as ARM
1187 /// ldrb / ldrh or because it's folded such as X86 zero-extending loads).
1188 virtual bool isZExtFree(SDValue Val, EVT VT2) const {
1189 return isZExtFree(Val.getValueType(), VT2);
1192 /// isFNegFree - Return true if an fneg operation is free to the point where
1193 /// it is never worthwhile to replace it with a bitwise operation.
1194 virtual bool isFNegFree(EVT) const {
1198 /// isFAbsFree - Return true if an fneg operation is free to the point where
1199 /// it is never worthwhile to replace it with a bitwise operation.
1200 virtual bool isFAbsFree(EVT) const {
1204 /// isFMAFasterThanMulAndAdd - Return true if an FMA operation is faster than
1205 /// a pair of mul and add instructions. fmuladd intrinsics will be expanded to
1206 /// FMAs when this method returns true (and FMAs are legal), otherwise fmuladd
1207 /// is expanded to mul + add.
1208 virtual bool isFMAFasterThanMulAndAdd(EVT) const {
1212 /// isNarrowingProfitable - Return true if it's profitable to narrow
1213 /// operations of type VT1 to VT2. e.g. on x86, it's profitable to narrow
1214 /// from i32 to i8 but not from i32 to i16.
1215 virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
1219 //===--------------------------------------------------------------------===//
1220 // Runtime Library hooks
1223 /// setLibcallName - Rename the default libcall routine name for the specified
1225 void setLibcallName(RTLIB::Libcall Call, const char *Name) {
1226 LibcallRoutineNames[Call] = Name;
1229 /// getLibcallName - Get the libcall routine name for the specified libcall.
1231 const char *getLibcallName(RTLIB::Libcall Call) const {
1232 return LibcallRoutineNames[Call];
1235 /// setCmpLibcallCC - Override the default CondCode to be used to test the
1236 /// result of the comparison libcall against zero.
1237 void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
1238 CmpLibcallCCs[Call] = CC;
1241 /// getCmpLibcallCC - Get the CondCode that's to be used to test the result of
1242 /// the comparison libcall against zero.
1243 ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
1244 return CmpLibcallCCs[Call];
1247 /// setLibcallCallingConv - Set the CallingConv that should be used for the
1248 /// specified libcall.
1249 void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
1250 LibcallCallingConvs[Call] = CC;
1253 /// getLibcallCallingConv - Get the CallingConv that should be used for the
1254 /// specified libcall.
1255 CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
1256 return LibcallCallingConvs[Call];
1260 const TargetMachine &TM;
1261 const DataLayout *TD;
1262 const TargetLoweringObjectFile &TLOF;
1264 /// PointerTy - The type to use for pointers for the default address space,
1265 /// usually i32 or i64.
1269 /// IsLittleEndian - True if this is a little endian target.
1271 bool IsLittleEndian;
1273 /// SelectIsExpensive - Tells the code generator not to expand operations
1274 /// into sequences that use the select operations if possible.
1275 bool SelectIsExpensive;
1277 /// IntDivIsCheap - Tells the code generator not to expand integer divides by
1278 /// constants into a sequence of muls, adds, and shifts. This is a hack until
1279 /// a real cost model is in place. If we ever optimize for size, this will be
1280 /// set to true unconditionally.
1283 /// BypassSlowDivMap - Tells the code generator to bypass slow divide or
1284 /// remainder instructions. For example, BypassSlowDivWidths[32,8] tells the
1285 /// code generator to bypass 32-bit integer div/rem with an 8-bit unsigned
1286 /// integer div/rem when the operands are positive and less than 256.
1287 DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
1289 /// Pow2DivIsCheap - Tells the code generator that it shouldn't generate
1290 /// srl/add/sra for a signed divide by power of two, and let the target handle
1292 bool Pow2DivIsCheap;
1294 /// JumpIsExpensive - Tells the code generator that it shouldn't generate
1295 /// extra flow control instructions and should attempt to combine flow
1296 /// control instructions via predication.
1297 bool JumpIsExpensive;
1299 /// UseUnderscoreSetJmp - This target prefers to use _setjmp to implement
1300 /// llvm.setjmp. Defaults to false.
1301 bool UseUnderscoreSetJmp;
1303 /// UseUnderscoreLongJmp - This target prefers to use _longjmp to implement
1304 /// llvm.longjmp. Defaults to false.
1305 bool UseUnderscoreLongJmp;
1307 /// SupportJumpTables - Whether the target can generate code for jumptables.
1308 /// If it's not true, then each jumptable must be lowered into if-then-else's.
1309 bool SupportJumpTables;
1311 /// MinimumJumpTableEntries - Number of blocks threshold to use jump tables.
1312 int MinimumJumpTableEntries;
1314 /// BooleanContents - Information about the contents of the high-bits in
1315 /// boolean values held in a type wider than i1. See getBooleanContents.
1316 BooleanContent BooleanContents;
1317 /// BooleanVectorContents - Information about the contents of the high-bits
1318 /// in boolean vector values when the element type is wider than i1. See
1319 /// getBooleanContents.
1320 BooleanContent BooleanVectorContents;
1322 /// SchedPreferenceInfo - The target scheduling preference: shortest possible
1323 /// total cycles or lowest register usage.
1324 Sched::Preference SchedPreferenceInfo;
1326 /// JumpBufSize - The size, in bytes, of the target's jmp_buf buffers
1327 unsigned JumpBufSize;
1329 /// JumpBufAlignment - The alignment, in bytes, of the target's jmp_buf
1331 unsigned JumpBufAlignment;
1333 /// MinStackArgumentAlignment - The minimum alignment that any argument
1334 /// on the stack needs to have.
1336 unsigned MinStackArgumentAlignment;
1338 /// MinFunctionAlignment - The minimum function alignment (used when
1339 /// optimizing for size, and to prevent explicitly provided alignment
1340 /// from leading to incorrect code).
1342 unsigned MinFunctionAlignment;
1344 /// PrefFunctionAlignment - The preferred function alignment (used when
1345 /// alignment unspecified and optimizing for speed).
1347 unsigned PrefFunctionAlignment;
1349 /// PrefLoopAlignment - The preferred loop alignment.
1351 unsigned PrefLoopAlignment;
1353 /// ShouldFoldAtomicFences - Whether fencing MEMBARRIER instructions should
1354 /// be folded into the enclosed atomic intrinsic instruction by the
1356 bool ShouldFoldAtomicFences;
1358 /// InsertFencesForAtomic - Whether the DAG builder should automatically
1359 /// insert fences and reduce ordering for atomics. (This will be set for
1360 /// for most architectures with weak memory ordering.)
1361 bool InsertFencesForAtomic;
1363 /// StackPointerRegisterToSaveRestore - If set to a physical register, this
1364 /// specifies the register that llvm.savestack/llvm.restorestack should save
1366 unsigned StackPointerRegisterToSaveRestore;
1368 /// ExceptionPointerRegister - If set to a physical register, this specifies
1369 /// the register that receives the exception address on entry to a landing
1371 unsigned ExceptionPointerRegister;
1373 /// ExceptionSelectorRegister - If set to a physical register, this specifies
1374 /// the register that receives the exception typeid on entry to a landing
1376 unsigned ExceptionSelectorRegister;
1378 /// RegClassForVT - This indicates the default register class to use for
1379 /// each ValueType the target supports natively.
1380 const TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
1381 unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
1382 MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
1384 /// RepRegClassForVT - This indicates the "representative" register class to
1385 /// use for each ValueType the target supports natively. This information is
1386 /// used by the scheduler to track register pressure. By default, the
1387 /// representative register class is the largest legal super-reg register
1388 /// class of the register class of the specified type. e.g. On x86, i8, i16,
1389 /// and i32's representative class would be GR32.
1390 const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
1392 /// RepRegClassCostForVT - This indicates the "cost" of the "representative"
1393 /// register class for each ValueType. The cost is used by the scheduler to
1394 /// approximate register pressure.
1395 uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
1397 /// TransformToType - For any value types we are promoting or expanding, this
1398 /// contains the value type that we are changing to. For Expanded types, this
1399 /// contains one step of the expand (e.g. i64 -> i32), even if there are
1400 /// multiple steps required (e.g. i64 -> i16). For types natively supported
1401 /// by the system, this holds the same type (e.g. i32 -> i32).
1402 MVT TransformToType[MVT::LAST_VALUETYPE];
1404 /// OpActions - For each operation and each value type, keep a LegalizeAction
1405 /// that indicates how instruction selection should deal with the operation.
1406 /// Most operations are Legal (aka, supported natively by the target), but
1407 /// operations that are not should be described. Note that operations on
1408 /// non-legal value types are not described here.
1409 uint8_t OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END];
1411 /// LoadExtActions - For each load extension type and each value type,
1412 /// keep a LegalizeAction that indicates how instruction selection should deal
1413 /// with a load of a specific value type and extension type.
1414 uint8_t LoadExtActions[MVT::LAST_VALUETYPE][ISD::LAST_LOADEXT_TYPE];
1416 /// TruncStoreActions - For each value type pair keep a LegalizeAction that
1417 /// indicates whether a truncating store of a specific value type and
1418 /// truncating type is legal.
1419 uint8_t TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
1421 /// IndexedModeActions - For each indexed mode and each value type,
1422 /// keep a pair of LegalizeAction that indicates how instruction
1423 /// selection should deal with the load / store. The first dimension is the
1424 /// value_type for the reference. The second dimension represents the various
1425 /// modes for load store.
1426 uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
1428 /// CondCodeActions - For each condition code (ISD::CondCode) keep a
1429 /// LegalizeAction that indicates how instruction selection should
1430 /// deal with the condition code.
1431 /// Because each CC action takes up 2 bits, we need to have the array size
1432 /// be large enough to fit all of the value types. This can be done by
1433 /// dividing the MVT::LAST_VALUETYPE by 32 and adding one.
1434 uint64_t CondCodeActions[ISD::SETCC_INVALID][(MVT::LAST_VALUETYPE / 32) + 1];
1436 ValueTypeActionImpl ValueTypeActions;
1440 getTypeConversion(LLVMContext &Context, EVT VT) const {
1441 // If this is a simple type, use the ComputeRegisterProp mechanism.
1442 if (VT.isSimple()) {
1443 MVT SVT = VT.getSimpleVT();
1444 assert((unsigned)SVT.SimpleTy < array_lengthof(TransformToType));
1445 MVT NVT = TransformToType[SVT.SimpleTy];
1446 LegalizeTypeAction LA = ValueTypeActions.getTypeAction(SVT);
1450 ValueTypeActions.getTypeAction(NVT) != TypePromoteInteger)
1451 && "Promote may not follow Expand or Promote");
1453 if (LA == TypeSplitVector)
1454 return LegalizeKind(LA, EVT::getVectorVT(Context,
1455 SVT.getVectorElementType(),
1456 SVT.getVectorNumElements()/2));
1457 if (LA == TypeScalarizeVector)
1458 return LegalizeKind(LA, SVT.getVectorElementType());
1459 return LegalizeKind(LA, NVT);
1462 // Handle Extended Scalar Types.
1463 if (!VT.isVector()) {
1464 assert(VT.isInteger() && "Float types must be simple");
1465 unsigned BitSize = VT.getSizeInBits();
1466 // First promote to a power-of-two size, then expand if necessary.
1467 if (BitSize < 8 || !isPowerOf2_32(BitSize)) {
1468 EVT NVT = VT.getRoundIntegerType(Context);
1469 assert(NVT != VT && "Unable to round integer VT");
1470 LegalizeKind NextStep = getTypeConversion(Context, NVT);
1471 // Avoid multi-step promotion.
1472 if (NextStep.first == TypePromoteInteger) return NextStep;
1473 // Return rounded integer type.
1474 return LegalizeKind(TypePromoteInteger, NVT);
1477 return LegalizeKind(TypeExpandInteger,
1478 EVT::getIntegerVT(Context, VT.getSizeInBits()/2));
1481 // Handle vector types.
1482 unsigned NumElts = VT.getVectorNumElements();
1483 EVT EltVT = VT.getVectorElementType();
1485 // Vectors with only one element are always scalarized.
1487 return LegalizeKind(TypeScalarizeVector, EltVT);
1489 // Try to widen vector elements until a legal type is found.
1490 if (EltVT.isInteger()) {
1491 // Vectors with a number of elements that is not a power of two are always
1492 // widened, for example <3 x float> -> <4 x float>.
1493 if (!VT.isPow2VectorType()) {
1494 NumElts = (unsigned)NextPowerOf2(NumElts);
1495 EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts);
1496 return LegalizeKind(TypeWidenVector, NVT);
1499 // Examine the element type.
1500 LegalizeKind LK = getTypeConversion(Context, EltVT);
1502 // If type is to be expanded, split the vector.
1503 // <4 x i140> -> <2 x i140>
1504 if (LK.first == TypeExpandInteger)
1505 return LegalizeKind(TypeSplitVector,
1506 EVT::getVectorVT(Context, EltVT, NumElts / 2));
1508 // Promote the integer element types until a legal vector type is found
1509 // or until the element integer type is too big. If a legal type was not
1510 // found, fallback to the usual mechanism of widening/splitting the
1513 // Increase the bitwidth of the element to the next pow-of-two
1514 // (which is greater than 8 bits).
1515 EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits()
1516 ).getRoundIntegerType(Context);
1518 // Stop trying when getting a non-simple element type.
1519 // Note that vector elements may be greater than legal vector element
1520 // types. Example: X86 XMM registers hold 64bit element on 32bit systems.
1521 if (!EltVT.isSimple()) break;
1523 // Build a new vector type and check if it is legal.
1524 MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1525 // Found a legal promoted vector type.
1526 if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal)
1527 return LegalizeKind(TypePromoteInteger,
1528 EVT::getVectorVT(Context, EltVT, NumElts));
1532 // Try to widen the vector until a legal type is found.
1533 // If there is no wider legal type, split the vector.
1535 // Round up to the next power of 2.
1536 NumElts = (unsigned)NextPowerOf2(NumElts);
1538 // If there is no simple vector type with this many elements then there
1539 // cannot be a larger legal vector type. Note that this assumes that
1540 // there are no skipped intermediate vector types in the simple types.
1541 if (!EltVT.isSimple()) break;
1542 MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1543 if (LargerVector == MVT()) break;
1545 // If this type is legal then widen the vector.
1546 if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal)
1547 return LegalizeKind(TypeWidenVector, LargerVector);
1550 // Widen odd vectors to next power of two.
1551 if (!VT.isPow2VectorType()) {
1552 EVT NVT = VT.getPow2VectorType(Context);
1553 return LegalizeKind(TypeWidenVector, NVT);
1556 // Vectors with illegal element types are expanded.
1557 EVT NVT = EVT::getVectorVT(Context, EltVT, VT.getVectorNumElements() / 2);
1558 return LegalizeKind(TypeSplitVector, NVT);
1562 std::vector<std::pair<MVT, const TargetRegisterClass*> > AvailableRegClasses;
1564 /// TargetDAGCombineArray - Targets can specify ISD nodes that they would
1565 /// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(),
1566 /// which sets a bit in this array.
1568 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
1570 /// PromoteToType - For operations that must be promoted to a specific type,
1571 /// this holds the destination type. This map should be sparse, so don't hold
1574 /// Targets add entries to this map with AddPromotedToType(..), clients access
1575 /// this with getTypeToPromoteTo(..).
1576 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
1579 /// LibcallRoutineNames - Stores the name each libcall.
1581 const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
1583 /// CmpLibcallCCs - The ISD::CondCode that should be used to test the result
1584 /// of each of the comparison libcall against zero.
1585 ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
1587 /// LibcallCallingConvs - Stores the CallingConv that should be used for each
1589 CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
1592 /// When lowering \@llvm.memset this field specifies the maximum number of
1593 /// store operations that may be substituted for the call to memset. Targets
1594 /// must set this value based on the cost threshold for that target. Targets
1595 /// should assume that the memset will be done using as many of the largest
1596 /// store operations first, followed by smaller ones, if necessary, per
1597 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
1598 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
1599 /// store. This only applies to setting a constant array of a constant size.
1600 /// @brief Specify maximum number of store instructions per memset call.
1601 unsigned MaxStoresPerMemset;
1603 /// Maximum number of stores operations that may be substituted for the call
1604 /// to memset, used for functions with OptSize attribute.
1605 unsigned MaxStoresPerMemsetOptSize;
1607 /// When lowering \@llvm.memcpy this field specifies the maximum number of
1608 /// store operations that may be substituted for a call to memcpy. Targets
1609 /// must set this value based on the cost threshold for that target. Targets
1610 /// should assume that the memcpy will be done using as many of the largest
1611 /// store operations first, followed by smaller ones, if necessary, per
1612 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
1613 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
1614 /// and one 1-byte store. This only applies to copying a constant array of
1616 /// @brief Specify maximum bytes of store instructions per memcpy call.
1617 unsigned MaxStoresPerMemcpy;
1619 /// Maximum number of store operations that may be substituted for a call
1620 /// to memcpy, used for functions with OptSize attribute.
1621 unsigned MaxStoresPerMemcpyOptSize;
1623 /// When lowering \@llvm.memmove this field specifies the maximum number of
1624 /// store instructions that may be substituted for a call to memmove. Targets
1625 /// must set this value based on the cost threshold for that target. Targets
1626 /// should assume that the memmove will be done using as many of the largest
1627 /// store operations first, followed by smaller ones, if necessary, per
1628 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
1629 /// with 8-bit alignment would result in nine 1-byte stores. This only
1630 /// applies to copying a constant array of constant size.
1631 /// @brief Specify maximum bytes of store instructions per memmove call.
1632 unsigned MaxStoresPerMemmove;
1634 /// Maximum number of store instructions that may be substituted for a call
1635 /// to memmove, used for functions with OpSize attribute.
1636 unsigned MaxStoresPerMemmoveOptSize;
1638 /// This field specifies whether the target can benefit from code placement
1640 bool BenefitFromCodePlacementOpt;
1642 /// PredictableSelectIsExpensive - Tells the code generator that select is
1643 /// more expensive than a branch if the branch is usually predicted right.
1644 bool PredictableSelectIsExpensive;
1647 /// isLegalRC - Return true if the value types that can be represented by the
1648 /// specified register class are all legal.
1649 bool isLegalRC(const TargetRegisterClass *RC) const;
1652 //===----------------------------------------------------------------------===//
1653 /// TargetLowering - This class defines information used to lower LLVM code to
1654 /// legal SelectionDAG operators that the target instruction selector can accept
1657 /// This class also defines callbacks that targets must implement to lower
1658 /// target-specific constructs to SelectionDAG operators.
1660 class TargetLowering : public TargetLoweringBase {
1661 TargetLowering(const TargetLowering&) LLVM_DELETED_FUNCTION;
1662 void operator=(const TargetLowering&) LLVM_DELETED_FUNCTION;
1665 /// NOTE: The constructor takes ownership of TLOF.
1666 explicit TargetLowering(const TargetMachine &TM,
1667 const TargetLoweringObjectFile *TLOF);
1669 /// getPreIndexedAddressParts - returns true by value, base pointer and
1670 /// offset pointer and addressing mode by reference if the node's address
1671 /// can be legally represented as pre-indexed load / store address.
1672 virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
1673 SDValue &/*Offset*/,
1674 ISD::MemIndexedMode &/*AM*/,
1675 SelectionDAG &/*DAG*/) const {
1679 /// getPostIndexedAddressParts - returns true by value, base pointer and
1680 /// offset pointer and addressing mode by reference if this node can be
1681 /// combined with a load / store to form a post-indexed load / store.
1682 virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
1683 SDValue &/*Base*/, SDValue &/*Offset*/,
1684 ISD::MemIndexedMode &/*AM*/,
1685 SelectionDAG &/*DAG*/) const {
1689 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1690 /// current function. The returned value is a member of the
1691 /// MachineJumpTableInfo::JTEntryKind enum.
1692 virtual unsigned getJumpTableEncoding() const;
1694 virtual const MCExpr *
1695 LowerCustomJumpTableEntry(const MachineJumpTableInfo * /*MJTI*/,
1696 const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
1697 MCContext &/*Ctx*/) const {
1698 llvm_unreachable("Need to implement this hook if target has custom JTIs");
1701 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1703 virtual SDValue getPICJumpTableRelocBase(SDValue Table,
1704 SelectionDAG &DAG) const;
1706 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1707 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1709 virtual const MCExpr *
1710 getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
1711 unsigned JTI, MCContext &Ctx) const;
1713 /// isOffsetFoldingLegal - Return true if folding a constant offset
1714 /// with the given GlobalAddress is legal. It is frequently not legal in
1715 /// PIC relocation models.
1716 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
1718 bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
1719 SDValue &Chain) const;
1721 void softenSetCCOperands(SelectionDAG &DAG, EVT VT,
1722 SDValue &NewLHS, SDValue &NewRHS,
1723 ISD::CondCode &CCCode, DebugLoc DL) const;
1725 SDValue makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT,
1726 const SDValue *Ops, unsigned NumOps,
1727 bool isSigned, DebugLoc dl) const;
1729 //===--------------------------------------------------------------------===//
1730 // TargetLowering Optimization Methods
1733 /// TargetLoweringOpt - A convenience struct that encapsulates a DAG, and two
1734 /// SDValues for returning information from TargetLowering to its clients
1735 /// that want to combine
1736 struct TargetLoweringOpt {
1743 explicit TargetLoweringOpt(SelectionDAG &InDAG,
1745 DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
1747 bool LegalTypes() const { return LegalTys; }
1748 bool LegalOperations() const { return LegalOps; }
1750 bool CombineTo(SDValue O, SDValue N) {
1756 /// ShrinkDemandedConstant - Check to see if the specified operand of the
1757 /// specified instruction is a constant integer. If so, check to see if
1758 /// there are any bits set in the constant that are not demanded. If so,
1759 /// shrink the constant and return true.
1760 bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded);
1762 /// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the
1763 /// casts are free. This uses isZExtFree and ZERO_EXTEND for the widening
1764 /// cast, but it could be generalized for targets with other types of
1765 /// implicit widening casts.
1766 bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
1770 /// SimplifyDemandedBits - Look at Op. At this point, we know that only the
1771 /// DemandedMask bits of the result of Op are ever used downstream. If we can
1772 /// use this information to simplify Op, create a new simplified DAG node and
1773 /// return true, returning the original and new nodes in Old and New.
1774 /// Otherwise, analyze the expression and return a mask of KnownOne and
1775 /// KnownZero bits for the expression (used to simplify the caller).
1776 /// The KnownZero/One bits may only be accurate for those bits in the
1778 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
1779 APInt &KnownZero, APInt &KnownOne,
1780 TargetLoweringOpt &TLO, unsigned Depth = 0) const;
1782 /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
1783 /// Mask are known to be either zero or one and return them in the
1784 /// KnownZero/KnownOne bitsets.
1785 virtual void computeMaskedBitsForTargetNode(const SDValue Op,
1788 const SelectionDAG &DAG,
1789 unsigned Depth = 0) const;
1791 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
1792 /// targets that want to expose additional information about sign bits to the
1794 virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
1795 unsigned Depth = 0) const;
1797 struct DAGCombinerInfo {
1798 void *DC; // The DAG Combiner object.
1800 bool CalledByLegalizer;
1804 DAGCombinerInfo(SelectionDAG &dag, CombineLevel level, bool cl, void *dc)
1805 : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
1807 bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
1808 bool isBeforeLegalizeOps() const { return Level < AfterLegalizeVectorOps; }
1809 bool isAfterLegalizeVectorOps() const {
1810 return Level == AfterLegalizeDAG;
1812 CombineLevel getDAGCombineLevel() { return Level; }
1813 bool isCalledByLegalizer() const { return CalledByLegalizer; }
1815 void AddToWorklist(SDNode *N);
1816 void RemoveFromWorklist(SDNode *N);
1817 SDValue CombineTo(SDNode *N, const std::vector<SDValue> &To,
1819 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
1820 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
1822 void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
1825 /// SimplifySetCC - Try to simplify a setcc built with the specified operands
1826 /// and cc. If it is unable to simplify it, return a null SDValue.
1827 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
1828 ISD::CondCode Cond, bool foldBooleans,
1829 DAGCombinerInfo &DCI, DebugLoc dl) const;
1831 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
1832 /// node is a GlobalAddress + offset.
1834 isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
1836 /// PerformDAGCombine - This method will be invoked for all target nodes and
1837 /// for any target-independent nodes that the target has registered with
1840 /// The semantics are as follows:
1842 /// SDValue.Val == 0 - No change was made
1843 /// SDValue.Val == N - N was replaced, is dead, and is already handled.
1844 /// otherwise - N should be replaced by the returned Operand.
1846 /// In addition, methods provided by DAGCombinerInfo may be used to perform
1847 /// more complex transformations.
1849 virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
1851 /// isTypeDesirableForOp - Return true if the target has native support for
1852 /// the specified value type and it is 'desirable' to use the type for the
1853 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
1854 /// instruction encodings are longer and some i16 instructions are slow.
1855 virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
1856 // By default, assume all legal types are desirable.
1857 return isTypeLegal(VT);
1860 /// isDesirableToPromoteOp - Return true if it is profitable for dag combiner
1861 /// to transform a floating point op of specified opcode to a equivalent op of
1862 /// an integer type. e.g. f32 load -> i32 load can be profitable on ARM.
1863 virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
1868 /// IsDesirableToPromoteOp - This method query the target whether it is
1869 /// beneficial for dag combiner to promote the specified node. If true, it
1870 /// should return the desired promotion type by reference.
1871 virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
1875 //===--------------------------------------------------------------------===//
1876 // Lowering methods - These methods must be implemented by targets so that
1877 // the SelectionDAGBuilder code knows how to lower these.
1880 /// LowerFormalArguments - This hook must be implemented to lower the
1881 /// incoming (formal) arguments, described by the Ins array, into the
1882 /// specified DAG. The implementation should fill in the InVals array
1883 /// with legal-type argument values, and return the resulting token
1887 LowerFormalArguments(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
1889 const SmallVectorImpl<ISD::InputArg> &/*Ins*/,
1890 DebugLoc /*dl*/, SelectionDAG &/*DAG*/,
1891 SmallVectorImpl<SDValue> &/*InVals*/) const {
1892 llvm_unreachable("Not Implemented");
1895 struct ArgListEntry {
1906 ArgListEntry() : isSExt(false), isZExt(false), isInReg(false),
1907 isSRet(false), isNest(false), isByVal(false), Alignment(0) { }
1909 typedef std::vector<ArgListEntry> ArgListTy;
1911 /// CallLoweringInfo - This structure contains all information that is
1912 /// necessary for lowering calls. It is passed to TLI::LowerCallTo when the
1913 /// SelectionDAG builder needs to lower a call, and targets will see this
1914 /// struct in their LowerCall implementation.
1915 struct CallLoweringInfo {
1922 bool DoesNotReturn : 1;
1923 bool IsReturnValueUsed : 1;
1925 // IsTailCall should be modified by implementations of
1926 // TargetLowering::LowerCall that perform tail call conversions.
1929 unsigned NumFixedArgs;
1930 CallingConv::ID CallConv;
1935 ImmutableCallSite *CS;
1936 SmallVector<ISD::OutputArg, 32> Outs;
1937 SmallVector<SDValue, 32> OutVals;
1938 SmallVector<ISD::InputArg, 32> Ins;
1941 /// CallLoweringInfo - Constructs a call lowering context based on the
1942 /// ImmutableCallSite \p cs.
1943 CallLoweringInfo(SDValue chain, Type *retTy,
1944 FunctionType *FTy, bool isTailCall, SDValue callee,
1945 ArgListTy &args, SelectionDAG &dag, DebugLoc dl,
1946 ImmutableCallSite &cs)
1947 : Chain(chain), RetTy(retTy), RetSExt(cs.paramHasAttr(0, Attribute::SExt)),
1948 RetZExt(cs.paramHasAttr(0, Attribute::ZExt)), IsVarArg(FTy->isVarArg()),
1949 IsInReg(cs.paramHasAttr(0, Attribute::InReg)),
1950 DoesNotReturn(cs.doesNotReturn()),
1951 IsReturnValueUsed(!cs.getInstruction()->use_empty()),
1952 IsTailCall(isTailCall), NumFixedArgs(FTy->getNumParams()),
1953 CallConv(cs.getCallingConv()), Callee(callee), Args(args), DAG(dag),
1956 /// CallLoweringInfo - Constructs a call lowering context based on the
1957 /// provided call information.
1958 CallLoweringInfo(SDValue chain, Type *retTy, bool retSExt, bool retZExt,
1959 bool isVarArg, bool isInReg, unsigned numFixedArgs,
1960 CallingConv::ID callConv, bool isTailCall,
1961 bool doesNotReturn, bool isReturnValueUsed, SDValue callee,
1962 ArgListTy &args, SelectionDAG &dag, DebugLoc dl)
1963 : Chain(chain), RetTy(retTy), RetSExt(retSExt), RetZExt(retZExt),
1964 IsVarArg(isVarArg), IsInReg(isInReg), DoesNotReturn(doesNotReturn),
1965 IsReturnValueUsed(isReturnValueUsed), IsTailCall(isTailCall),
1966 NumFixedArgs(numFixedArgs), CallConv(callConv), Callee(callee),
1967 Args(args), DAG(dag), DL(dl), CS(NULL) {}
1970 /// LowerCallTo - This function lowers an abstract call to a function into an
1971 /// actual call. This returns a pair of operands. The first element is the
1972 /// return value for the function (if RetTy is not VoidTy). The second
1973 /// element is the outgoing token chain. It calls LowerCall to do the actual
1975 std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
1977 /// LowerCall - This hook must be implemented to lower calls into the
1978 /// the specified DAG. The outgoing arguments to the call are described
1979 /// by the Outs array, and the values to be returned by the call are
1980 /// described by the Ins array. The implementation should fill in the
1981 /// InVals array with legal-type return values from the call, and return
1982 /// the resulting token chain value.
1984 LowerCall(CallLoweringInfo &/*CLI*/,
1985 SmallVectorImpl<SDValue> &/*InVals*/) const {
1986 llvm_unreachable("Not Implemented");
1989 /// HandleByVal - Target-specific cleanup for formal ByVal parameters.
1990 virtual void HandleByVal(CCState *, unsigned &, unsigned) const {}
1992 /// CanLowerReturn - This hook should be implemented to check whether the
1993 /// return values described by the Outs array can fit into the return
1994 /// registers. If false is returned, an sret-demotion is performed.
1996 virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
1997 MachineFunction &/*MF*/, bool /*isVarArg*/,
1998 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
1999 LLVMContext &/*Context*/) const
2001 // Return true by default to get preexisting behavior.
2005 /// LowerReturn - This hook must be implemented to lower outgoing
2006 /// return values, described by the Outs array, into the specified
2007 /// DAG. The implementation should return the resulting token chain
2011 LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
2013 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
2014 const SmallVectorImpl<SDValue> &/*OutVals*/,
2015 DebugLoc /*dl*/, SelectionDAG &/*DAG*/) const {
2016 llvm_unreachable("Not Implemented");
2019 /// isUsedByReturnOnly - Return true if result of the specified node is used
2020 /// by a return node only. It also compute and return the input chain for the
2022 /// This is used to determine whether it is possible
2023 /// to codegen a libcall as tail call at legalization time.
2024 virtual bool isUsedByReturnOnly(SDNode *, SDValue &Chain) const {
2028 /// mayBeEmittedAsTailCall - Return true if the target may be able emit the
2029 /// call instruction as a tail call. This is used by optimization passes to
2030 /// determine if it's profitable to duplicate return instructions to enable
2031 /// tailcall optimization.
2032 virtual bool mayBeEmittedAsTailCall(CallInst *) const {
2036 /// getTypeForExtArgOrReturn - Return the type that should be used to zero or
2037 /// sign extend a zeroext/signext integer argument or return value.
2038 /// FIXME: Most C calling convention requires the return type to be promoted,
2039 /// but this is not true all the time, e.g. i1 on x86-64. It is also not
2040 /// necessary for non-C calling conventions. The frontend should handle this
2041 /// and include all of the necessary information.
2042 virtual MVT getTypeForExtArgOrReturn(MVT VT,
2043 ISD::NodeType /*ExtendKind*/) const {
2044 MVT MinVT = getRegisterType(MVT::i32);
2045 return VT.bitsLT(MinVT) ? MinVT : VT;
2048 /// LowerOperationWrapper - This callback is invoked by the type legalizer
2049 /// to legalize nodes with an illegal operand type but legal result types.
2050 /// It replaces the LowerOperation callback in the type Legalizer.
2051 /// The reason we can not do away with LowerOperation entirely is that
2052 /// LegalizeDAG isn't yet ready to use this callback.
2053 /// TODO: Consider merging with ReplaceNodeResults.
2055 /// The target places new result values for the node in Results (their number
2056 /// and types must exactly match those of the original return values of
2057 /// the node), or leaves Results empty, which indicates that the node is not
2058 /// to be custom lowered after all.
2059 /// The default implementation calls LowerOperation.
2060 virtual void LowerOperationWrapper(SDNode *N,
2061 SmallVectorImpl<SDValue> &Results,
2062 SelectionDAG &DAG) const;
2064 /// LowerOperation - This callback is invoked for operations that are
2065 /// unsupported by the target, which are registered to use 'custom' lowering,
2066 /// and whose defined values are all legal.
2067 /// If the target has no operations that require custom lowering, it need not
2068 /// implement this. The default implementation of this aborts.
2069 virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
2071 /// ReplaceNodeResults - This callback is invoked when a node result type is
2072 /// illegal for the target, and the operation was registered to use 'custom'
2073 /// lowering for that result type. The target places new result values for
2074 /// the node in Results (their number and types must exactly match those of
2075 /// the original return values of the node), or leaves Results empty, which
2076 /// indicates that the node is not to be custom lowered after all.
2078 /// If the target has no operations that require custom lowering, it need not
2079 /// implement this. The default implementation aborts.
2080 virtual void ReplaceNodeResults(SDNode * /*N*/,
2081 SmallVectorImpl<SDValue> &/*Results*/,
2082 SelectionDAG &/*DAG*/) const {
2083 llvm_unreachable("ReplaceNodeResults not implemented for this target!");
2086 /// getTargetNodeName() - This method returns the name of a target specific
2088 virtual const char *getTargetNodeName(unsigned Opcode) const;
2090 /// createFastISel - This method returns a target specific FastISel object,
2091 /// or null if the target does not support "fast" ISel.
2092 virtual FastISel *createFastISel(FunctionLoweringInfo &,
2093 const TargetLibraryInfo *) const {
2097 //===--------------------------------------------------------------------===//
2098 // Inline Asm Support hooks
2101 /// ExpandInlineAsm - This hook allows the target to expand an inline asm
2102 /// call to be explicit llvm code if it wants to. This is useful for
2103 /// turning simple inline asms into LLVM intrinsics, which gives the
2104 /// compiler more information about the behavior of the code.
2105 virtual bool ExpandInlineAsm(CallInst *) const {
2109 enum ConstraintType {
2110 C_Register, // Constraint represents specific register(s).
2111 C_RegisterClass, // Constraint represents any of register(s) in class.
2112 C_Memory, // Memory constraint.
2113 C_Other, // Something else.
2114 C_Unknown // Unsupported constraint.
2117 enum ConstraintWeight {
2119 CW_Invalid = -1, // No match.
2120 CW_Okay = 0, // Acceptable.
2121 CW_Good = 1, // Good weight.
2122 CW_Better = 2, // Better weight.
2123 CW_Best = 3, // Best weight.
2125 // Well-known weights.
2126 CW_SpecificReg = CW_Okay, // Specific register operands.
2127 CW_Register = CW_Good, // Register operands.
2128 CW_Memory = CW_Better, // Memory operands.
2129 CW_Constant = CW_Best, // Constant operand.
2130 CW_Default = CW_Okay // Default or don't know type.
2133 /// AsmOperandInfo - This contains information for each constraint that we are
2135 struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
2136 /// ConstraintCode - This contains the actual string for the code, like "m".
2137 /// TargetLowering picks the 'best' code from ConstraintInfo::Codes that
2138 /// most closely matches the operand.
2139 std::string ConstraintCode;
2141 /// ConstraintType - Information about the constraint code, e.g. Register,
2142 /// RegisterClass, Memory, Other, Unknown.
2143 TargetLowering::ConstraintType ConstraintType;
2145 /// CallOperandval - If this is the result output operand or a
2146 /// clobber, this is null, otherwise it is the incoming operand to the
2147 /// CallInst. This gets modified as the asm is processed.
2148 Value *CallOperandVal;
2150 /// ConstraintVT - The ValueType for the operand value.
2153 /// isMatchingInputConstraint - Return true of this is an input operand that
2154 /// is a matching constraint like "4".
2155 bool isMatchingInputConstraint() const;
2157 /// getMatchedOperand - If this is an input matching constraint, this method
2158 /// returns the output operand it matches.
2159 unsigned getMatchedOperand() const;
2161 /// Copy constructor for copying from an AsmOperandInfo.
2162 AsmOperandInfo(const AsmOperandInfo &info)
2163 : InlineAsm::ConstraintInfo(info),
2164 ConstraintCode(info.ConstraintCode),
2165 ConstraintType(info.ConstraintType),
2166 CallOperandVal(info.CallOperandVal),
2167 ConstraintVT(info.ConstraintVT) {
2170 /// Copy constructor for copying from a ConstraintInfo.
2171 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
2172 : InlineAsm::ConstraintInfo(info),
2173 ConstraintType(TargetLowering::C_Unknown),
2174 CallOperandVal(0), ConstraintVT(MVT::Other) {
2178 typedef std::vector<AsmOperandInfo> AsmOperandInfoVector;
2180 /// ParseConstraints - Split up the constraint string from the inline
2181 /// assembly value into the specific constraints and their prefixes,
2182 /// and also tie in the associated operand values.
2183 /// If this returns an empty vector, and if the constraint string itself
2184 /// isn't empty, there was an error parsing.
2185 virtual AsmOperandInfoVector ParseConstraints(ImmutableCallSite CS) const;
2187 /// Examine constraint type and operand type and determine a weight value.
2188 /// The operand object must already have been set up with the operand type.
2189 virtual ConstraintWeight getMultipleConstraintMatchWeight(
2190 AsmOperandInfo &info, int maIndex) const;
2192 /// Examine constraint string and operand type and determine a weight value.
2193 /// The operand object must already have been set up with the operand type.
2194 virtual ConstraintWeight getSingleConstraintMatchWeight(
2195 AsmOperandInfo &info, const char *constraint) const;
2197 /// ComputeConstraintToUse - Determines the constraint code and constraint
2198 /// type to use for the specific AsmOperandInfo, setting
2199 /// OpInfo.ConstraintCode and OpInfo.ConstraintType. If the actual operand
2200 /// being passed in is available, it can be passed in as Op, otherwise an
2201 /// empty SDValue can be passed.
2202 virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
2204 SelectionDAG *DAG = 0) const;
2206 /// getConstraintType - Given a constraint, return the type of constraint it
2207 /// is for this target.
2208 virtual ConstraintType getConstraintType(const std::string &Constraint) const;
2210 /// getRegForInlineAsmConstraint - Given a physical register constraint (e.g.
2211 /// {edx}), return the register number and the register class for the
2214 /// Given a register class constraint, like 'r', if this corresponds directly
2215 /// to an LLVM register class, return a register of 0 and the register class
2218 /// This should only be used for C_Register constraints. On error,
2219 /// this returns a register number of 0 and a null register class pointer..
2220 virtual std::pair<unsigned, const TargetRegisterClass*>
2221 getRegForInlineAsmConstraint(const std::string &Constraint,
2224 /// LowerXConstraint - try to replace an X constraint, which matches anything,
2225 /// with another that has more specific requirements based on the type of the
2226 /// corresponding operand. This returns null if there is no replacement to
2228 virtual const char *LowerXConstraint(EVT ConstraintVT) const;
2230 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
2231 /// vector. If it is invalid, don't add anything to Ops.
2232 virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
2233 std::vector<SDValue> &Ops,
2234 SelectionDAG &DAG) const;
2236 //===--------------------------------------------------------------------===//
2237 // Div utility functions
2239 SDValue BuildExactSDIV(SDValue Op1, SDValue Op2, DebugLoc dl,
2240 SelectionDAG &DAG) const;
2241 SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
2242 std::vector<SDNode*> *Created) const;
2243 SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
2244 std::vector<SDNode*> *Created) const;
2246 //===--------------------------------------------------------------------===//
2247 // Instruction Emitting Hooks
2250 // EmitInstrWithCustomInserter - This method should be implemented by targets
2251 // that mark instructions with the 'usesCustomInserter' flag. These
2252 // instructions are special in various ways, which require special support to
2253 // insert. The specified MachineInstr is created but not inserted into any
2254 // basic blocks, and this method is called to expand it into a sequence of
2255 // instructions, potentially also creating new basic blocks and control flow.
2256 virtual MachineBasicBlock *
2257 EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const;
2259 /// AdjustInstrPostInstrSelection - This method should be implemented by
2260 /// targets that mark instructions with the 'hasPostISelHook' flag. These
2261 /// instructions must be adjusted after instruction selection by target hooks.
2262 /// e.g. To fill in optional defs for ARM 's' setting instructions.
2264 AdjustInstrPostInstrSelection(MachineInstr *MI, SDNode *Node) const;
2267 /// GetReturnInfo - Given an LLVM IR type and return type attributes,
2268 /// compute the return value EVTs and flags, and optionally also
2269 /// the offsets, if the return value is being lowered to memory.
2270 void GetReturnInfo(Type* ReturnType, AttributeSet attr,
2271 SmallVectorImpl<ISD::OutputArg> &Outs,
2272 const TargetLowering &TLI);
2274 } // end llvm namespace