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/CallingConv.h"
26 #include "llvm/InlineAsm.h"
27 #include "llvm/Attributes.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/CodeGen/SelectionDAGNodes.h"
30 #include "llvm/CodeGen/RuntimeLibcalls.h"
31 #include "llvm/Support/DebugLoc.h"
32 #include "llvm/Target/TargetCallingConv.h"
33 #include "llvm/Target/TargetMachine.h"
45 class FunctionLoweringInfo;
46 class ImmutableCallSite;
47 class MachineBasicBlock;
48 class MachineFunction;
49 class MachineFrameInfo;
51 class MachineJumpTableInfo;
57 template<typename T> class SmallVectorImpl;
60 class TargetRegisterClass;
61 class TargetLoweringObjectFile;
64 // FIXME: should this be here?
73 TLSModel::Model getTLSModel(const GlobalValue *GV, Reloc::Model reloc);
76 //===----------------------------------------------------------------------===//
77 /// TargetLowering - This class defines information used to lower LLVM code to
78 /// legal SelectionDAG operators that the target instruction selector can accept
81 /// This class also defines callbacks that targets must implement to lower
82 /// target-specific constructs to SelectionDAG operators.
84 class TargetLowering {
85 TargetLowering(const TargetLowering&); // DO NOT IMPLEMENT
86 void operator=(const TargetLowering&); // DO NOT IMPLEMENT
88 /// LegalizeAction - This enum indicates whether operations are valid for a
89 /// target, and if not, what action should be used to make them valid.
91 Legal, // The target natively supports this operation.
92 Promote, // This operation should be executed in a larger type.
93 Expand, // Try to expand this to other ops, otherwise use a libcall.
94 Custom // Use the LowerOperation hook to implement custom lowering.
97 /// LegalizeAction - This enum indicates whether a types are legal for a
98 /// target, and if not, what action should be used to make them valid.
99 enum LegalizeTypeAction {
100 TypeLegal, // The target natively supports this type.
101 TypePromoteInteger, // Replace this integer with a larger one.
102 TypeExpandInteger, // Split this integer into two of half the size.
103 TypeSoftenFloat, // Convert this float to a same size integer type.
104 TypeExpandFloat, // Split this float into two of half the size.
105 TypeScalarizeVector, // Replace this one-element vector with its element.
106 TypeSplitVector, // Split this vector into two of half the size.
107 TypeWidenVector // This vector should be widened into a larger vector.
110 enum BooleanContent { // How the target represents true/false values.
111 UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
112 ZeroOrOneBooleanContent, // All bits zero except for bit 0.
113 ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
116 /// NOTE: The constructor takes ownership of TLOF.
117 explicit TargetLowering(const TargetMachine &TM,
118 const TargetLoweringObjectFile *TLOF);
119 virtual ~TargetLowering();
121 const TargetMachine &getTargetMachine() const { return TM; }
122 const TargetData *getTargetData() const { return TD; }
123 const TargetLoweringObjectFile &getObjFileLowering() const { return TLOF; }
125 bool isBigEndian() const { return !IsLittleEndian; }
126 bool isLittleEndian() const { return IsLittleEndian; }
127 MVT getPointerTy() const { return PointerTy; }
128 virtual MVT getShiftAmountTy(EVT LHSTy) const;
130 /// isSelectExpensive - Return true if the select operation is expensive for
132 bool isSelectExpensive() const { return SelectIsExpensive; }
134 /// isIntDivCheap() - Return true if integer divide is usually cheaper than
135 /// a sequence of several shifts, adds, and multiplies for this target.
136 bool isIntDivCheap() const { return IntDivIsCheap; }
138 /// isPow2DivCheap() - Return true if pow2 div is cheaper than a chain of
140 bool isPow2DivCheap() const { return Pow2DivIsCheap; }
142 /// isJumpExpensive() - Return true if Flow Control is an expensive operation
143 /// that should be avoided.
144 bool isJumpExpensive() const { return JumpIsExpensive; }
146 /// getSetCCResultType - Return the ValueType of the result of SETCC
147 /// operations. Also used to obtain the target's preferred type for
148 /// the condition operand of SELECT and BRCOND nodes. In the case of
149 /// BRCOND the argument passed is MVT::Other since there are no other
150 /// operands to get a type hint from.
152 MVT::SimpleValueType getSetCCResultType(EVT VT) const;
154 /// getCmpLibcallReturnType - Return the ValueType for comparison
155 /// libcalls. Comparions libcalls include floating point comparion calls,
156 /// and Ordered/Unordered check calls on floating point numbers.
158 MVT::SimpleValueType getCmpLibcallReturnType() const;
160 /// getBooleanContents - For targets without i1 registers, this gives the
161 /// nature of the high-bits of boolean values held in types wider than i1.
162 /// "Boolean values" are special true/false values produced by nodes like
163 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
164 /// Not to be confused with general values promoted from i1.
165 BooleanContent getBooleanContents() const { return BooleanContents;}
167 /// getSchedulingPreference - Return target scheduling preference.
168 Sched::Preference getSchedulingPreference() const {
169 return SchedPreferenceInfo;
172 /// getSchedulingPreference - Some scheduler, e.g. hybrid, can switch to
173 /// different scheduling heuristics for different nodes. This function returns
174 /// the preference (or none) for the given node.
175 virtual Sched::Preference getSchedulingPreference(SDNode *N) const {
179 /// getRegClassFor - Return the register class that should be used for the
180 /// specified value type.
181 virtual TargetRegisterClass *getRegClassFor(EVT VT) const {
182 assert(VT.isSimple() && "getRegClassFor called on illegal type!");
183 TargetRegisterClass *RC = RegClassForVT[VT.getSimpleVT().SimpleTy];
184 assert(RC && "This value type is not natively supported!");
188 /// getRepRegClassFor - Return the 'representative' register class for the
189 /// specified value type. The 'representative' register class is the largest
190 /// legal super-reg register class for the register class of the value type.
191 /// For example, on i386 the rep register class for i8, i16, and i32 are GR32;
192 /// while the rep register class is GR64 on x86_64.
193 virtual const TargetRegisterClass *getRepRegClassFor(EVT VT) const {
194 assert(VT.isSimple() && "getRepRegClassFor called on illegal type!");
195 const TargetRegisterClass *RC = RepRegClassForVT[VT.getSimpleVT().SimpleTy];
199 /// getRepRegClassCostFor - Return the cost of the 'representative' register
200 /// class for the specified value type.
201 virtual uint8_t getRepRegClassCostFor(EVT VT) const {
202 assert(VT.isSimple() && "getRepRegClassCostFor called on illegal type!");
203 return RepRegClassCostForVT[VT.getSimpleVT().SimpleTy];
206 /// isTypeLegal - Return true if the target has native support for the
207 /// specified value type. This means that it has a register that directly
208 /// holds it without promotions or expansions.
209 bool isTypeLegal(EVT VT) const {
210 assert(!VT.isSimple() ||
211 (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
212 return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != 0;
215 class ValueTypeActionImpl {
216 /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
217 /// that indicates how instruction selection should deal with the type.
218 uint8_t ValueTypeActions[MVT::LAST_VALUETYPE];
221 ValueTypeActionImpl() {
222 std::fill(ValueTypeActions, array_endof(ValueTypeActions), 0);
225 LegalizeTypeAction getTypeAction(MVT VT) const {
226 return (LegalizeTypeAction)ValueTypeActions[VT.SimpleTy];
229 void setTypeAction(EVT VT, LegalizeTypeAction Action) {
230 unsigned I = VT.getSimpleVT().SimpleTy;
231 ValueTypeActions[I] = Action;
235 const ValueTypeActionImpl &getValueTypeActions() const {
236 return ValueTypeActions;
239 /// getTypeAction - Return how we should legalize values of this type, either
240 /// it is already legal (return 'Legal') or we need to promote it to a larger
241 /// type (return 'Promote'), or we need to expand it into multiple registers
242 /// of smaller integer type (return 'Expand'). 'Custom' is not an option.
243 LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const {
244 return getTypeConversion(Context, VT).first;
246 LegalizeTypeAction getTypeAction(MVT VT) const {
247 return ValueTypeActions.getTypeAction(VT);
250 /// getTypeToTransformTo - For types supported by the target, this is an
251 /// identity function. For types that must be promoted to larger types, this
252 /// returns the larger type to promote to. For integer types that are larger
253 /// than the largest integer register, this contains one step in the expansion
254 /// to get to the smaller register. For illegal floating point types, this
255 /// returns the integer type to transform to.
256 EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
257 return getTypeConversion(Context, VT).second;
260 /// getTypeToExpandTo - For types supported by the target, this is an
261 /// identity function. For types that must be expanded (i.e. integer types
262 /// that are larger than the largest integer register or illegal floating
263 /// point types), this returns the largest legal type it will be expanded to.
264 EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
265 assert(!VT.isVector());
267 switch (getTypeAction(Context, VT)) {
271 VT = getTypeToTransformTo(Context, VT);
274 assert(false && "Type is not legal nor is it to be expanded!");
281 /// getVectorTypeBreakdown - Vector types are broken down into some number of
282 /// legal first class types. For example, EVT::v8f32 maps to 2 EVT::v4f32
283 /// with Altivec or SSE1, or 8 promoted EVT::f64 values with the X86 FP stack.
284 /// Similarly, EVT::v2i64 turns into 4 EVT::i32 values with both PPC and X86.
286 /// This method returns the number of registers needed, and the VT for each
287 /// register. It also returns the VT and quantity of the intermediate values
288 /// before they are promoted/expanded.
290 unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
292 unsigned &NumIntermediates,
293 EVT &RegisterVT) const;
295 /// getTgtMemIntrinsic: Given an intrinsic, checks if on the target the
296 /// intrinsic will need to map to a MemIntrinsicNode (touches memory). If
297 /// this is the case, it returns true and store the intrinsic
298 /// information into the IntrinsicInfo that was passed to the function.
299 struct IntrinsicInfo {
300 unsigned opc; // target opcode
301 EVT memVT; // memory VT
302 const Value* ptrVal; // value representing memory location
303 int offset; // offset off of ptrVal
304 unsigned align; // alignment
305 bool vol; // is volatile?
306 bool readMem; // reads memory?
307 bool writeMem; // writes memory?
310 virtual bool getTgtMemIntrinsic(IntrinsicInfo &Info,
311 const CallInst &I, unsigned Intrinsic) const {
315 /// isFPImmLegal - Returns true if the target can instruction select the
316 /// specified FP immediate natively. If false, the legalizer will materialize
317 /// the FP immediate as a load from a constant pool.
318 virtual bool isFPImmLegal(const APFloat &Imm, EVT VT) const {
322 /// isShuffleMaskLegal - Targets can use this to indicate that they only
323 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
324 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
325 /// are assumed to be legal.
326 virtual bool isShuffleMaskLegal(const SmallVectorImpl<int> &Mask,
331 /// canOpTrap - Returns true if the operation can trap for the value type.
332 /// VT must be a legal type. By default, we optimistically assume most
333 /// operations don't trap except for divide and remainder.
334 virtual bool canOpTrap(unsigned Op, EVT VT) const;
336 /// isVectorClearMaskLegal - Similar to isShuffleMaskLegal. This is
337 /// used by Targets can use this to indicate if there is a suitable
338 /// VECTOR_SHUFFLE that can be used to replace a VAND with a constant
340 virtual bool isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
345 /// getOperationAction - Return how this operation should be treated: either
346 /// it is legal, needs to be promoted to a larger size, needs to be
347 /// expanded to some other code sequence, or the target has a custom expander
349 LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
350 if (VT.isExtended()) return Expand;
351 assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
352 unsigned I = (unsigned) VT.getSimpleVT().SimpleTy;
353 return (LegalizeAction)OpActions[I][Op];
356 /// isOperationLegalOrCustom - Return true if the specified operation is
357 /// legal on this target or can be made legal with custom lowering. This
358 /// is used to help guide high-level lowering decisions.
359 bool isOperationLegalOrCustom(unsigned Op, EVT VT) const {
360 return (VT == MVT::Other || isTypeLegal(VT)) &&
361 (getOperationAction(Op, VT) == Legal ||
362 getOperationAction(Op, VT) == Custom);
365 /// isOperationLegal - Return true if the specified operation is legal on this
367 bool isOperationLegal(unsigned Op, EVT VT) const {
368 return (VT == MVT::Other || isTypeLegal(VT)) &&
369 getOperationAction(Op, VT) == Legal;
372 /// getLoadExtAction - Return how this load with extension should be treated:
373 /// either it is legal, needs to be promoted to a larger size, needs to be
374 /// expanded to some other code sequence, or the target has a custom expander
376 LegalizeAction getLoadExtAction(unsigned ExtType, EVT VT) const {
377 assert(ExtType < ISD::LAST_LOADEXT_TYPE &&
378 VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
379 "Table isn't big enough!");
380 return (LegalizeAction)LoadExtActions[VT.getSimpleVT().SimpleTy][ExtType];
383 /// isLoadExtLegal - Return true if the specified load with extension is legal
385 bool isLoadExtLegal(unsigned ExtType, EVT VT) const {
386 return VT.isSimple() &&
387 (getLoadExtAction(ExtType, VT) == Legal ||
388 getLoadExtAction(ExtType, VT) == Custom);
391 /// getTruncStoreAction - Return how this store with truncation should be
392 /// treated: either it is legal, needs to be promoted to a larger size, needs
393 /// to be expanded to some other code sequence, or the target has a custom
395 LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT) const {
396 assert(ValVT.getSimpleVT() < MVT::LAST_VALUETYPE &&
397 MemVT.getSimpleVT() < MVT::LAST_VALUETYPE &&
398 "Table isn't big enough!");
399 return (LegalizeAction)TruncStoreActions[ValVT.getSimpleVT().SimpleTy]
400 [MemVT.getSimpleVT().SimpleTy];
403 /// isTruncStoreLegal - Return true if the specified store with truncation is
404 /// legal on this target.
405 bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
406 return isTypeLegal(ValVT) && MemVT.isSimple() &&
407 (getTruncStoreAction(ValVT, MemVT) == Legal ||
408 getTruncStoreAction(ValVT, MemVT) == Custom);
411 /// getIndexedLoadAction - Return how the indexed load should be treated:
412 /// either it is legal, needs to be promoted to a larger size, needs to be
413 /// expanded to some other code sequence, or the target has a custom expander
416 getIndexedLoadAction(unsigned IdxMode, EVT VT) const {
417 assert(IdxMode < ISD::LAST_INDEXED_MODE &&
418 VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
419 "Table isn't big enough!");
420 unsigned Ty = (unsigned)VT.getSimpleVT().SimpleTy;
421 return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] & 0xf0) >> 4);
424 /// isIndexedLoadLegal - Return true if the specified indexed load is legal
426 bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
427 return VT.isSimple() &&
428 (getIndexedLoadAction(IdxMode, VT) == Legal ||
429 getIndexedLoadAction(IdxMode, VT) == Custom);
432 /// getIndexedStoreAction - Return how the indexed store should be treated:
433 /// either it is legal, needs to be promoted to a larger size, needs to be
434 /// expanded to some other code sequence, or the target has a custom expander
437 getIndexedStoreAction(unsigned IdxMode, EVT VT) const {
438 assert(IdxMode < ISD::LAST_INDEXED_MODE &&
439 VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
440 "Table isn't big enough!");
441 unsigned Ty = (unsigned)VT.getSimpleVT().SimpleTy;
442 return (LegalizeAction)(IndexedModeActions[Ty][IdxMode] & 0x0f);
445 /// isIndexedStoreLegal - Return true if the specified indexed load is legal
447 bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
448 return VT.isSimple() &&
449 (getIndexedStoreAction(IdxMode, VT) == Legal ||
450 getIndexedStoreAction(IdxMode, VT) == Custom);
453 /// getCondCodeAction - Return how the condition code should be treated:
454 /// either it is legal, needs to be expanded to some other code sequence,
455 /// or the target has a custom expander for it.
457 getCondCodeAction(ISD::CondCode CC, EVT VT) const {
458 assert((unsigned)CC < array_lengthof(CondCodeActions) &&
459 (unsigned)VT.getSimpleVT().SimpleTy < sizeof(CondCodeActions[0])*4 &&
460 "Table isn't big enough!");
461 LegalizeAction Action = (LegalizeAction)
462 ((CondCodeActions[CC] >> (2*VT.getSimpleVT().SimpleTy)) & 3);
463 assert(Action != Promote && "Can't promote condition code!");
467 /// isCondCodeLegal - Return true if the specified condition code is legal
469 bool isCondCodeLegal(ISD::CondCode CC, EVT VT) const {
470 return getCondCodeAction(CC, VT) == Legal ||
471 getCondCodeAction(CC, VT) == Custom;
475 /// getTypeToPromoteTo - If the action for this operation is to promote, this
476 /// method returns the ValueType to promote to.
477 EVT getTypeToPromoteTo(unsigned Op, EVT VT) const {
478 assert(getOperationAction(Op, VT) == Promote &&
479 "This operation isn't promoted!");
481 // See if this has an explicit type specified.
482 std::map<std::pair<unsigned, MVT::SimpleValueType>,
483 MVT::SimpleValueType>::const_iterator PTTI =
484 PromoteToType.find(std::make_pair(Op, VT.getSimpleVT().SimpleTy));
485 if (PTTI != PromoteToType.end()) return PTTI->second;
487 assert((VT.isInteger() || VT.isFloatingPoint()) &&
488 "Cannot autopromote this type, add it with AddPromotedToType.");
492 NVT = (MVT::SimpleValueType)(NVT.getSimpleVT().SimpleTy+1);
493 assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
494 "Didn't find type to promote to!");
495 } while (!isTypeLegal(NVT) ||
496 getOperationAction(Op, NVT) == Promote);
500 /// getValueType - Return the EVT corresponding to this LLVM type.
501 /// This is fixed by the LLVM operations except for the pointer size. If
502 /// AllowUnknown is true, this will return MVT::Other for types with no EVT
503 /// counterpart (e.g. structs), otherwise it will assert.
504 EVT getValueType(const Type *Ty, bool AllowUnknown = false) const {
505 EVT VT = EVT::getEVT(Ty, AllowUnknown);
506 return VT == MVT::iPTR ? PointerTy : VT;
509 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
510 /// function arguments in the caller parameter area. This is the actual
511 /// alignment, not its logarithm.
512 virtual unsigned getByValTypeAlignment(const Type *Ty) const;
514 /// getRegisterType - Return the type of registers that this ValueType will
515 /// eventually require.
516 EVT getRegisterType(MVT VT) const {
517 assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
518 return RegisterTypeForVT[VT.SimpleTy];
521 /// getRegisterType - Return the type of registers that this ValueType will
522 /// eventually require.
523 EVT getRegisterType(LLVMContext &Context, EVT VT) const {
525 assert((unsigned)VT.getSimpleVT().SimpleTy <
526 array_lengthof(RegisterTypeForVT));
527 return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
531 unsigned NumIntermediates;
532 (void)getVectorTypeBreakdown(Context, VT, VT1,
533 NumIntermediates, RegisterVT);
536 if (VT.isInteger()) {
537 return getRegisterType(Context, getTypeToTransformTo(Context, VT));
539 assert(0 && "Unsupported extended type!");
540 return EVT(MVT::Other); // Not reached
543 /// getNumRegisters - Return the number of registers that this ValueType will
544 /// eventually require. This is one for any types promoted to live in larger
545 /// registers, but may be more than one for types (like i64) that are split
546 /// into pieces. For types like i140, which are first promoted then expanded,
547 /// it is the number of registers needed to hold all the bits of the original
548 /// type. For an i140 on a 32 bit machine this means 5 registers.
549 unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
551 assert((unsigned)VT.getSimpleVT().SimpleTy <
552 array_lengthof(NumRegistersForVT));
553 return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
557 unsigned NumIntermediates;
558 return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
560 if (VT.isInteger()) {
561 unsigned BitWidth = VT.getSizeInBits();
562 unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
563 return (BitWidth + RegWidth - 1) / RegWidth;
565 assert(0 && "Unsupported extended type!");
566 return 0; // Not reached
569 /// ShouldShrinkFPConstant - If true, then instruction selection should
570 /// seek to shrink the FP constant of the specified type to a smaller type
571 /// in order to save space and / or reduce runtime.
572 virtual bool ShouldShrinkFPConstant(EVT VT) const { return true; }
574 /// hasTargetDAGCombine - If true, the target has custom DAG combine
575 /// transformations that it can perform for the specified node.
576 bool hasTargetDAGCombine(ISD::NodeType NT) const {
577 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
578 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
581 /// This function returns the maximum number of store operations permitted
582 /// to replace a call to llvm.memset. The value is set by the target at the
583 /// performance threshold for such a replacement. If OptSize is true,
584 /// return the limit for functions that have OptSize attribute.
585 /// @brief Get maximum # of store operations permitted for llvm.memset
586 unsigned getMaxStoresPerMemset(bool OptSize) const {
587 return OptSize ? maxStoresPerMemsetOptSize : maxStoresPerMemset;
590 /// This function returns the maximum number of store operations permitted
591 /// to replace a call to llvm.memcpy. The value is set by the target at the
592 /// performance threshold for such a replacement. If OptSize is true,
593 /// return the limit for functions that have OptSize attribute.
594 /// @brief Get maximum # of store operations permitted for llvm.memcpy
595 unsigned getMaxStoresPerMemcpy(bool OptSize) const {
596 return OptSize ? maxStoresPerMemcpyOptSize : maxStoresPerMemcpy;
599 /// This function returns the maximum number of store operations permitted
600 /// to replace a call to llvm.memmove. The value is set by the target at the
601 /// performance threshold for such a replacement. If OptSize is true,
602 /// return the limit for functions that have OptSize attribute.
603 /// @brief Get maximum # of store operations permitted for llvm.memmove
604 unsigned getMaxStoresPerMemmove(bool OptSize) const {
605 return OptSize ? maxStoresPerMemmoveOptSize : maxStoresPerMemmove;
608 /// This function returns true if the target allows unaligned memory accesses.
609 /// of the specified type. This is used, for example, in situations where an
610 /// array copy/move/set is converted to a sequence of store operations. It's
611 /// use helps to ensure that such replacements don't generate code that causes
612 /// an alignment error (trap) on the target machine.
613 /// @brief Determine if the target supports unaligned memory accesses.
614 virtual bool allowsUnalignedMemoryAccesses(EVT VT) const {
618 /// This function returns true if the target would benefit from code placement
620 /// @brief Determine if the target should perform code placement optimization.
621 bool shouldOptimizeCodePlacement() const {
622 return benefitFromCodePlacementOpt;
625 /// getOptimalMemOpType - Returns the target specific optimal type for load
626 /// and store operations as a result of memset, memcpy, and memmove
627 /// lowering. If DstAlign is zero that means it's safe to destination
628 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
629 /// means there isn't a need to check it against alignment requirement,
630 /// probably because the source does not need to be loaded. If
631 /// 'NonScalarIntSafe' is true, that means it's safe to return a
632 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
633 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
634 /// constant so it does not need to be loaded.
635 /// It returns EVT::Other if the type should be determined using generic
636 /// target-independent logic.
637 virtual EVT getOptimalMemOpType(uint64_t Size,
638 unsigned DstAlign, unsigned SrcAlign,
639 bool NonScalarIntSafe, bool MemcpyStrSrc,
640 MachineFunction &MF) const {
644 /// usesUnderscoreSetJmp - Determine if we should use _setjmp or setjmp
645 /// to implement llvm.setjmp.
646 bool usesUnderscoreSetJmp() const {
647 return UseUnderscoreSetJmp;
650 /// usesUnderscoreLongJmp - Determine if we should use _longjmp or longjmp
651 /// to implement llvm.longjmp.
652 bool usesUnderscoreLongJmp() const {
653 return UseUnderscoreLongJmp;
656 /// getStackPointerRegisterToSaveRestore - If a physical register, this
657 /// specifies the register that llvm.savestack/llvm.restorestack should save
659 unsigned getStackPointerRegisterToSaveRestore() const {
660 return StackPointerRegisterToSaveRestore;
663 /// getExceptionAddressRegister - If a physical register, this returns
664 /// the register that receives the exception address on entry to a landing
666 unsigned getExceptionAddressRegister() const {
667 return ExceptionPointerRegister;
670 /// getExceptionSelectorRegister - If a physical register, this returns
671 /// the register that receives the exception typeid on entry to a landing
673 unsigned getExceptionSelectorRegister() const {
674 return ExceptionSelectorRegister;
677 /// getJumpBufSize - returns the target's jmp_buf size in bytes (if never
678 /// set, the default is 200)
679 unsigned getJumpBufSize() const {
683 /// getJumpBufAlignment - returns the target's jmp_buf alignment in bytes
684 /// (if never set, the default is 0)
685 unsigned getJumpBufAlignment() const {
686 return JumpBufAlignment;
689 /// getMinStackArgumentAlignment - return the minimum stack alignment of an
691 unsigned getMinStackArgumentAlignment() const {
692 return MinStackArgumentAlignment;
695 /// getMinFunctionAlignment - return the minimum function alignment.
697 unsigned getMinFunctionAlignment() const {
698 return MinFunctionAlignment;
701 /// getPrefFunctionAlignment - return the preferred function alignment.
703 unsigned getPrefFunctionAlignment() const {
704 return PrefFunctionAlignment;
707 /// getPrefLoopAlignment - return the preferred loop alignment.
709 unsigned getPrefLoopAlignment() const {
710 return PrefLoopAlignment;
713 /// getShouldFoldAtomicFences - return whether the combiner should fold
714 /// fence MEMBARRIER instructions into the atomic intrinsic instructions.
716 bool getShouldFoldAtomicFences() const {
717 return ShouldFoldAtomicFences;
720 /// getPreIndexedAddressParts - returns true by value, base pointer and
721 /// offset pointer and addressing mode by reference if the node's address
722 /// can be legally represented as pre-indexed load / store address.
723 virtual bool getPreIndexedAddressParts(SDNode *N, SDValue &Base,
725 ISD::MemIndexedMode &AM,
726 SelectionDAG &DAG) const {
730 /// getPostIndexedAddressParts - returns true by value, base pointer and
731 /// offset pointer and addressing mode by reference if this node can be
732 /// combined with a load / store to form a post-indexed load / store.
733 virtual bool getPostIndexedAddressParts(SDNode *N, SDNode *Op,
734 SDValue &Base, SDValue &Offset,
735 ISD::MemIndexedMode &AM,
736 SelectionDAG &DAG) const {
740 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
741 /// current function. The returned value is a member of the
742 /// MachineJumpTableInfo::JTEntryKind enum.
743 virtual unsigned getJumpTableEncoding() const;
745 virtual const MCExpr *
746 LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
747 const MachineBasicBlock *MBB, unsigned uid,
748 MCContext &Ctx) const {
749 assert(0 && "Need to implement this hook if target has custom JTIs");
753 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
755 virtual SDValue getPICJumpTableRelocBase(SDValue Table,
756 SelectionDAG &DAG) const;
758 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
759 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
761 virtual const MCExpr *
762 getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
763 unsigned JTI, MCContext &Ctx) const;
765 /// isOffsetFoldingLegal - Return true if folding a constant offset
766 /// with the given GlobalAddress is legal. It is frequently not legal in
767 /// PIC relocation models.
768 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
770 /// getStackCookieLocation - Return true if the target stores stack
771 /// protector cookies at a fixed offset in some non-standard address
772 /// space, and populates the address space and offset as
774 virtual bool getStackCookieLocation(unsigned &AddressSpace, unsigned &Offset) const {
778 /// getMaximalGlobalOffset - Returns the maximal possible offset which can be
779 /// used for loads / stores from the global.
780 virtual unsigned getMaximalGlobalOffset() const {
784 //===--------------------------------------------------------------------===//
785 // TargetLowering Optimization Methods
788 /// TargetLoweringOpt - A convenience struct that encapsulates a DAG, and two
789 /// SDValues for returning information from TargetLowering to its clients
790 /// that want to combine
791 struct TargetLoweringOpt {
798 explicit TargetLoweringOpt(SelectionDAG &InDAG,
800 DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
802 bool LegalTypes() const { return LegalTys; }
803 bool LegalOperations() const { return LegalOps; }
805 bool CombineTo(SDValue O, SDValue N) {
811 /// ShrinkDemandedConstant - Check to see if the specified operand of the
812 /// specified instruction is a constant integer. If so, check to see if
813 /// there are any bits set in the constant that are not demanded. If so,
814 /// shrink the constant and return true.
815 bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded);
817 /// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the
818 /// casts are free. This uses isZExtFree and ZERO_EXTEND for the widening
819 /// cast, but it could be generalized for targets with other types of
820 /// implicit widening casts.
821 bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
825 /// SimplifyDemandedBits - Look at Op. At this point, we know that only the
826 /// DemandedMask bits of the result of Op are ever used downstream. If we can
827 /// use this information to simplify Op, create a new simplified DAG node and
828 /// return true, returning the original and new nodes in Old and New.
829 /// Otherwise, analyze the expression and return a mask of KnownOne and
830 /// KnownZero bits for the expression (used to simplify the caller).
831 /// The KnownZero/One bits may only be accurate for those bits in the
833 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
834 APInt &KnownZero, APInt &KnownOne,
835 TargetLoweringOpt &TLO, unsigned Depth = 0) const;
837 /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
838 /// Mask are known to be either zero or one and return them in the
839 /// KnownZero/KnownOne bitsets.
840 virtual void computeMaskedBitsForTargetNode(const SDValue Op,
844 const SelectionDAG &DAG,
845 unsigned Depth = 0) const;
847 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
848 /// targets that want to expose additional information about sign bits to the
850 virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
851 unsigned Depth = 0) const;
853 struct DAGCombinerInfo {
854 void *DC; // The DAG Combiner object.
856 bool BeforeLegalizeOps;
857 bool CalledByLegalizer;
861 DAGCombinerInfo(SelectionDAG &dag, bool bl, bool blo, bool cl, void *dc)
862 : DC(dc), BeforeLegalize(bl), BeforeLegalizeOps(blo),
863 CalledByLegalizer(cl), DAG(dag) {}
865 bool isBeforeLegalize() const { return BeforeLegalize; }
866 bool isBeforeLegalizeOps() const { return BeforeLegalizeOps; }
867 bool isCalledByLegalizer() const { return CalledByLegalizer; }
869 void AddToWorklist(SDNode *N);
870 void RemoveFromWorklist(SDNode *N);
871 SDValue CombineTo(SDNode *N, const std::vector<SDValue> &To,
873 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
874 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
876 void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
879 /// SimplifySetCC - Try to simplify a setcc built with the specified operands
880 /// and cc. If it is unable to simplify it, return a null SDValue.
881 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
882 ISD::CondCode Cond, bool foldBooleans,
883 DAGCombinerInfo &DCI, DebugLoc dl) const;
885 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
886 /// node is a GlobalAddress + offset.
888 isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
890 /// PerformDAGCombine - This method will be invoked for all target nodes and
891 /// for any target-independent nodes that the target has registered with
894 /// The semantics are as follows:
896 /// SDValue.Val == 0 - No change was made
897 /// SDValue.Val == N - N was replaced, is dead, and is already handled.
898 /// otherwise - N should be replaced by the returned Operand.
900 /// In addition, methods provided by DAGCombinerInfo may be used to perform
901 /// more complex transformations.
903 virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
905 /// isTypeDesirableForOp - Return true if the target has native support for
906 /// the specified value type and it is 'desirable' to use the type for the
907 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
908 /// instruction encodings are longer and some i16 instructions are slow.
909 virtual bool isTypeDesirableForOp(unsigned Opc, EVT VT) const {
910 // By default, assume all legal types are desirable.
911 return isTypeLegal(VT);
914 /// isDesirableToPromoteOp - Return true if it is profitable for dag combiner
915 /// to transform a floating point op of specified opcode to a equivalent op of
916 /// an integer type. e.g. f32 load -> i32 load can be profitable on ARM.
917 virtual bool isDesirableToTransformToIntegerOp(unsigned Opc, EVT VT) const {
921 /// IsDesirableToPromoteOp - This method query the target whether it is
922 /// beneficial for dag combiner to promote the specified node. If true, it
923 /// should return the desired promotion type by reference.
924 virtual bool IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
928 //===--------------------------------------------------------------------===//
929 // TargetLowering Configuration Methods - These methods should be invoked by
930 // the derived class constructor to configure this object for the target.
934 /// setBooleanContents - Specify how the target extends the result of a
935 /// boolean value from i1 to a wider type. See getBooleanContents.
936 void setBooleanContents(BooleanContent Ty) { BooleanContents = Ty; }
938 /// setSchedulingPreference - Specify the target scheduling preference.
939 void setSchedulingPreference(Sched::Preference Pref) {
940 SchedPreferenceInfo = Pref;
943 /// setUseUnderscoreSetJmp - Indicate whether this target prefers to
944 /// use _setjmp to implement llvm.setjmp or the non _ version.
945 /// Defaults to false.
946 void setUseUnderscoreSetJmp(bool Val) {
947 UseUnderscoreSetJmp = Val;
950 /// setUseUnderscoreLongJmp - Indicate whether this target prefers to
951 /// use _longjmp to implement llvm.longjmp or the non _ version.
952 /// Defaults to false.
953 void setUseUnderscoreLongJmp(bool Val) {
954 UseUnderscoreLongJmp = Val;
957 /// setStackPointerRegisterToSaveRestore - If set to a physical register, this
958 /// specifies the register that llvm.savestack/llvm.restorestack should save
960 void setStackPointerRegisterToSaveRestore(unsigned R) {
961 StackPointerRegisterToSaveRestore = R;
964 /// setExceptionPointerRegister - If set to a physical register, this sets
965 /// the register that receives the exception address on entry to a landing
967 void setExceptionPointerRegister(unsigned R) {
968 ExceptionPointerRegister = R;
971 /// setExceptionSelectorRegister - If set to a physical register, this sets
972 /// the register that receives the exception typeid on entry to a landing
974 void setExceptionSelectorRegister(unsigned R) {
975 ExceptionSelectorRegister = R;
978 /// SelectIsExpensive - Tells the code generator not to expand operations
979 /// into sequences that use the select operations if possible.
980 void setSelectIsExpensive(bool isExpensive = true) {
981 SelectIsExpensive = isExpensive;
984 /// JumpIsExpensive - Tells the code generator not to expand sequence of
985 /// operations into a separate sequences that increases the amount of
987 void setJumpIsExpensive(bool isExpensive = true) {
988 JumpIsExpensive = isExpensive;
991 /// setIntDivIsCheap - Tells the code generator that integer divide is
992 /// expensive, and if possible, should be replaced by an alternate sequence
993 /// of instructions not containing an integer divide.
994 void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
996 /// setPow2DivIsCheap - Tells the code generator that it shouldn't generate
997 /// srl/add/sra for a signed divide by power of two, and let the target handle
999 void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
1001 /// addRegisterClass - Add the specified register class as an available
1002 /// regclass for the specified value type. This indicates the selector can
1003 /// handle values of that class natively.
1004 void addRegisterClass(EVT VT, TargetRegisterClass *RC) {
1005 assert((unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
1006 AvailableRegClasses.push_back(std::make_pair(VT, RC));
1007 RegClassForVT[VT.getSimpleVT().SimpleTy] = RC;
1010 /// findRepresentativeClass - Return the largest legal super-reg register class
1011 /// of the register class for the specified type and its associated "cost".
1012 virtual std::pair<const TargetRegisterClass*, uint8_t>
1013 findRepresentativeClass(EVT VT) const;
1015 /// computeRegisterProperties - Once all of the register classes are added,
1016 /// this allows us to compute derived properties we expose.
1017 void computeRegisterProperties();
1019 /// setOperationAction - Indicate that the specified operation does not work
1020 /// with the specified type and indicate what to do about it.
1021 void setOperationAction(unsigned Op, MVT VT,
1022 LegalizeAction Action) {
1023 assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
1024 OpActions[(unsigned)VT.SimpleTy][Op] = (uint8_t)Action;
1027 /// setLoadExtAction - Indicate that the specified load with extension does
1028 /// not work with the specified type and indicate what to do about it.
1029 void setLoadExtAction(unsigned ExtType, MVT VT,
1030 LegalizeAction Action) {
1031 assert(ExtType < ISD::LAST_LOADEXT_TYPE && VT < MVT::LAST_VALUETYPE &&
1032 "Table isn't big enough!");
1033 LoadExtActions[VT.SimpleTy][ExtType] = (uint8_t)Action;
1036 /// setTruncStoreAction - Indicate that the specified truncating store does
1037 /// not work with the specified type and indicate what to do about it.
1038 void setTruncStoreAction(MVT ValVT, MVT MemVT,
1039 LegalizeAction Action) {
1040 assert(ValVT < MVT::LAST_VALUETYPE && MemVT < MVT::LAST_VALUETYPE &&
1041 "Table isn't big enough!");
1042 TruncStoreActions[ValVT.SimpleTy][MemVT.SimpleTy] = (uint8_t)Action;
1045 /// setIndexedLoadAction - Indicate that the specified indexed load does or
1046 /// does not work with the specified type and indicate what to do abort
1047 /// it. NOTE: All indexed mode loads are initialized to Expand in
1048 /// TargetLowering.cpp
1049 void setIndexedLoadAction(unsigned IdxMode, MVT VT,
1050 LegalizeAction Action) {
1051 assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
1052 (unsigned)Action < 0xf && "Table isn't big enough!");
1053 // Load action are kept in the upper half.
1054 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0xf0;
1055 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action) <<4;
1058 /// setIndexedStoreAction - Indicate that the specified indexed store does or
1059 /// does not work with the specified type and indicate what to do about
1060 /// it. NOTE: All indexed mode stores are initialized to Expand in
1061 /// TargetLowering.cpp
1062 void setIndexedStoreAction(unsigned IdxMode, MVT VT,
1063 LegalizeAction Action) {
1064 assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
1065 (unsigned)Action < 0xf && "Table isn't big enough!");
1066 // Store action are kept in the lower half.
1067 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0x0f;
1068 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action);
1071 /// setCondCodeAction - Indicate that the specified condition code is or isn't
1072 /// supported on the target and indicate what to do about it.
1073 void setCondCodeAction(ISD::CondCode CC, MVT VT,
1074 LegalizeAction Action) {
1075 assert(VT < MVT::LAST_VALUETYPE &&
1076 (unsigned)CC < array_lengthof(CondCodeActions) &&
1077 "Table isn't big enough!");
1078 CondCodeActions[(unsigned)CC] &= ~(uint64_t(3UL) << VT.SimpleTy*2);
1079 CondCodeActions[(unsigned)CC] |= (uint64_t)Action << VT.SimpleTy*2;
1082 /// AddPromotedToType - If Opc/OrigVT is specified as being promoted, the
1083 /// promotion code defaults to trying a larger integer/fp until it can find
1084 /// one that works. If that default is insufficient, this method can be used
1085 /// by the target to override the default.
1086 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1087 PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
1090 /// setTargetDAGCombine - Targets should invoke this method for each target
1091 /// independent node that they want to provide a custom DAG combiner for by
1092 /// implementing the PerformDAGCombine virtual method.
1093 void setTargetDAGCombine(ISD::NodeType NT) {
1094 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1095 TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
1098 /// setJumpBufSize - Set the target's required jmp_buf buffer size (in
1099 /// bytes); default is 200
1100 void setJumpBufSize(unsigned Size) {
1104 /// setJumpBufAlignment - Set the target's required jmp_buf buffer
1105 /// alignment (in bytes); default is 0
1106 void setJumpBufAlignment(unsigned Align) {
1107 JumpBufAlignment = Align;
1110 /// setMinFunctionAlignment - Set the target's minimum function alignment.
1111 void setMinFunctionAlignment(unsigned Align) {
1112 MinFunctionAlignment = Align;
1115 /// setPrefFunctionAlignment - Set the target's preferred function alignment.
1116 /// This should be set if there is a performance benefit to
1117 /// higher-than-minimum alignment
1118 void setPrefFunctionAlignment(unsigned Align) {
1119 PrefFunctionAlignment = Align;
1122 /// setPrefLoopAlignment - Set the target's preferred loop alignment. Default
1123 /// alignment is zero, it means the target does not care about loop alignment.
1124 void setPrefLoopAlignment(unsigned Align) {
1125 PrefLoopAlignment = Align;
1128 /// setMinStackArgumentAlignment - Set the minimum stack alignment of an
1130 void setMinStackArgumentAlignment(unsigned Align) {
1131 MinStackArgumentAlignment = Align;
1134 /// setShouldFoldAtomicFences - Set if the target's implementation of the
1135 /// atomic operation intrinsics includes locking. Default is false.
1136 void setShouldFoldAtomicFences(bool fold) {
1137 ShouldFoldAtomicFences = fold;
1141 //===--------------------------------------------------------------------===//
1142 // Lowering methods - These methods must be implemented by targets so that
1143 // the SelectionDAGLowering code knows how to lower these.
1146 /// LowerFormalArguments - This hook must be implemented to lower the
1147 /// incoming (formal) arguments, described by the Ins array, into the
1148 /// specified DAG. The implementation should fill in the InVals array
1149 /// with legal-type argument values, and return the resulting token
1153 LowerFormalArguments(SDValue Chain,
1154 CallingConv::ID CallConv, bool isVarArg,
1155 const SmallVectorImpl<ISD::InputArg> &Ins,
1156 DebugLoc dl, SelectionDAG &DAG,
1157 SmallVectorImpl<SDValue> &InVals) const {
1158 assert(0 && "Not Implemented");
1159 return SDValue(); // this is here to silence compiler errors
1162 /// LowerCallTo - This function lowers an abstract call to a function into an
1163 /// actual call. This returns a pair of operands. The first element is the
1164 /// return value for the function (if RetTy is not VoidTy). The second
1165 /// element is the outgoing token chain. It calls LowerCall to do the actual
1167 struct ArgListEntry {
1178 ArgListEntry() : isSExt(false), isZExt(false), isInReg(false),
1179 isSRet(false), isNest(false), isByVal(false), Alignment(0) { }
1181 typedef std::vector<ArgListEntry> ArgListTy;
1182 std::pair<SDValue, SDValue>
1183 LowerCallTo(SDValue Chain, const Type *RetTy, bool RetSExt, bool RetZExt,
1184 bool isVarArg, bool isInreg, unsigned NumFixedArgs,
1185 CallingConv::ID CallConv, bool isTailCall,
1186 bool isReturnValueUsed, SDValue Callee, ArgListTy &Args,
1187 SelectionDAG &DAG, DebugLoc dl) const;
1189 /// LowerCall - This hook must be implemented to lower calls into the
1190 /// the specified DAG. The outgoing arguments to the call are described
1191 /// by the Outs array, and the values to be returned by the call are
1192 /// described by the Ins array. The implementation should fill in the
1193 /// InVals array with legal-type return values from the call, and return
1194 /// the resulting token chain value.
1196 LowerCall(SDValue Chain, SDValue Callee,
1197 CallingConv::ID CallConv, bool isVarArg, bool &isTailCall,
1198 const SmallVectorImpl<ISD::OutputArg> &Outs,
1199 const SmallVectorImpl<SDValue> &OutVals,
1200 const SmallVectorImpl<ISD::InputArg> &Ins,
1201 DebugLoc dl, SelectionDAG &DAG,
1202 SmallVectorImpl<SDValue> &InVals) const {
1203 assert(0 && "Not Implemented");
1204 return SDValue(); // this is here to silence compiler errors
1207 /// HandleByVal - Target-specific cleanup for formal ByVal parameters.
1208 virtual void HandleByVal(CCState *, unsigned &) const {}
1210 /// CanLowerReturn - This hook should be implemented to check whether the
1211 /// return values described by the Outs array can fit into the return
1212 /// registers. If false is returned, an sret-demotion is performed.
1214 virtual bool CanLowerReturn(CallingConv::ID CallConv,
1215 MachineFunction &MF, bool isVarArg,
1216 const SmallVectorImpl<ISD::OutputArg> &Outs,
1217 LLVMContext &Context) const
1219 // Return true by default to get preexisting behavior.
1223 /// LowerReturn - This hook must be implemented to lower outgoing
1224 /// return values, described by the Outs array, into the specified
1225 /// DAG. The implementation should return the resulting token chain
1229 LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1230 const SmallVectorImpl<ISD::OutputArg> &Outs,
1231 const SmallVectorImpl<SDValue> &OutVals,
1232 DebugLoc dl, SelectionDAG &DAG) const {
1233 assert(0 && "Not Implemented");
1234 return SDValue(); // this is here to silence compiler errors
1237 /// isUsedByReturnOnly - Return true if result of the specified node is used
1238 /// by a return node only. This is used to determine whether it is possible
1239 /// to codegen a libcall as tail call at legalization time.
1240 virtual bool isUsedByReturnOnly(SDNode *N) const {
1244 /// mayBeEmittedAsTailCall - Return true if the target may be able emit the
1245 /// call instruction as a tail call. This is used by optimization passes to
1246 /// determine if it's profitable to duplicate return instructions to enable
1247 /// tailcall optimization.
1248 virtual bool mayBeEmittedAsTailCall(CallInst *CI) const {
1252 /// getTypeForExtArgOrReturn - Return the type that should be used to zero or
1253 /// sign extend a zeroext/signext integer argument or return value.
1254 /// FIXME: Most C calling convention requires the return type to be promoted,
1255 /// but this is not true all the time, e.g. i1 on x86-64. It is also not
1256 /// necessary for non-C calling conventions. The frontend should handle this
1257 /// and include all of the necessary information.
1258 virtual EVT getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1259 ISD::NodeType ExtendKind) const {
1260 EVT MinVT = getRegisterType(Context, MVT::i32);
1261 return VT.bitsLT(MinVT) ? MinVT : VT;
1264 /// LowerOperationWrapper - This callback is invoked by the type legalizer
1265 /// to legalize nodes with an illegal operand type but legal result types.
1266 /// It replaces the LowerOperation callback in the type Legalizer.
1267 /// The reason we can not do away with LowerOperation entirely is that
1268 /// LegalizeDAG isn't yet ready to use this callback.
1269 /// TODO: Consider merging with ReplaceNodeResults.
1271 /// The target places new result values for the node in Results (their number
1272 /// and types must exactly match those of the original return values of
1273 /// the node), or leaves Results empty, which indicates that the node is not
1274 /// to be custom lowered after all.
1275 /// The default implementation calls LowerOperation.
1276 virtual void LowerOperationWrapper(SDNode *N,
1277 SmallVectorImpl<SDValue> &Results,
1278 SelectionDAG &DAG) const;
1280 /// LowerOperation - This callback is invoked for operations that are
1281 /// unsupported by the target, which are registered to use 'custom' lowering,
1282 /// and whose defined values are all legal.
1283 /// If the target has no operations that require custom lowering, it need not
1284 /// implement this. The default implementation of this aborts.
1285 virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
1287 /// ReplaceNodeResults - This callback is invoked when a node result type is
1288 /// illegal for the target, and the operation was registered to use 'custom'
1289 /// lowering for that result type. The target places new result values for
1290 /// the node in Results (their number and types must exactly match those of
1291 /// the original return values of the node), or leaves Results empty, which
1292 /// indicates that the node is not to be custom lowered after all.
1294 /// If the target has no operations that require custom lowering, it need not
1295 /// implement this. The default implementation aborts.
1296 virtual void ReplaceNodeResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
1297 SelectionDAG &DAG) const {
1298 assert(0 && "ReplaceNodeResults not implemented for this target!");
1301 /// getTargetNodeName() - This method returns the name of a target specific
1303 virtual const char *getTargetNodeName(unsigned Opcode) const;
1305 /// createFastISel - This method returns a target specific FastISel object,
1306 /// or null if the target does not support "fast" ISel.
1307 virtual FastISel *createFastISel(FunctionLoweringInfo &funcInfo) const {
1311 //===--------------------------------------------------------------------===//
1312 // Inline Asm Support hooks
1315 /// ExpandInlineAsm - This hook allows the target to expand an inline asm
1316 /// call to be explicit llvm code if it wants to. This is useful for
1317 /// turning simple inline asms into LLVM intrinsics, which gives the
1318 /// compiler more information about the behavior of the code.
1319 virtual bool ExpandInlineAsm(CallInst *CI) const {
1323 enum ConstraintType {
1324 C_Register, // Constraint represents specific register(s).
1325 C_RegisterClass, // Constraint represents any of register(s) in class.
1326 C_Memory, // Memory constraint.
1327 C_Other, // Something else.
1328 C_Unknown // Unsupported constraint.
1331 enum ConstraintWeight {
1333 CW_Invalid = -1, // No match.
1334 CW_Okay = 0, // Acceptable.
1335 CW_Good = 1, // Good weight.
1336 CW_Better = 2, // Better weight.
1337 CW_Best = 3, // Best weight.
1339 // Well-known weights.
1340 CW_SpecificReg = CW_Okay, // Specific register operands.
1341 CW_Register = CW_Good, // Register operands.
1342 CW_Memory = CW_Better, // Memory operands.
1343 CW_Constant = CW_Best, // Constant operand.
1344 CW_Default = CW_Okay // Default or don't know type.
1347 /// AsmOperandInfo - This contains information for each constraint that we are
1349 struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
1350 /// ConstraintCode - This contains the actual string for the code, like "m".
1351 /// TargetLowering picks the 'best' code from ConstraintInfo::Codes that
1352 /// most closely matches the operand.
1353 std::string ConstraintCode;
1355 /// ConstraintType - Information about the constraint code, e.g. Register,
1356 /// RegisterClass, Memory, Other, Unknown.
1357 TargetLowering::ConstraintType ConstraintType;
1359 /// CallOperandval - If this is the result output operand or a
1360 /// clobber, this is null, otherwise it is the incoming operand to the
1361 /// CallInst. This gets modified as the asm is processed.
1362 Value *CallOperandVal;
1364 /// ConstraintVT - The ValueType for the operand value.
1367 /// isMatchingInputConstraint - Return true of this is an input operand that
1368 /// is a matching constraint like "4".
1369 bool isMatchingInputConstraint() const;
1371 /// getMatchedOperand - If this is an input matching constraint, this method
1372 /// returns the output operand it matches.
1373 unsigned getMatchedOperand() const;
1375 /// Copy constructor for copying from an AsmOperandInfo.
1376 AsmOperandInfo(const AsmOperandInfo &info)
1377 : InlineAsm::ConstraintInfo(info),
1378 ConstraintCode(info.ConstraintCode),
1379 ConstraintType(info.ConstraintType),
1380 CallOperandVal(info.CallOperandVal),
1381 ConstraintVT(info.ConstraintVT) {
1384 /// Copy constructor for copying from a ConstraintInfo.
1385 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
1386 : InlineAsm::ConstraintInfo(info),
1387 ConstraintType(TargetLowering::C_Unknown),
1388 CallOperandVal(0), ConstraintVT(MVT::Other) {
1392 typedef std::vector<AsmOperandInfo> AsmOperandInfoVector;
1394 /// ParseConstraints - Split up the constraint string from the inline
1395 /// assembly value into the specific constraints and their prefixes,
1396 /// and also tie in the associated operand values.
1397 /// If this returns an empty vector, and if the constraint string itself
1398 /// isn't empty, there was an error parsing.
1399 virtual AsmOperandInfoVector ParseConstraints(ImmutableCallSite CS) const;
1401 /// Examine constraint type and operand type and determine a weight value.
1402 /// The operand object must already have been set up with the operand type.
1403 virtual ConstraintWeight getMultipleConstraintMatchWeight(
1404 AsmOperandInfo &info, int maIndex) const;
1406 /// Examine constraint string and operand type and determine a weight value.
1407 /// The operand object must already have been set up with the operand type.
1408 virtual ConstraintWeight getSingleConstraintMatchWeight(
1409 AsmOperandInfo &info, const char *constraint) const;
1411 /// ComputeConstraintToUse - Determines the constraint code and constraint
1412 /// type to use for the specific AsmOperandInfo, setting
1413 /// OpInfo.ConstraintCode and OpInfo.ConstraintType. If the actual operand
1414 /// being passed in is available, it can be passed in as Op, otherwise an
1415 /// empty SDValue can be passed.
1416 virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
1418 SelectionDAG *DAG = 0) const;
1420 /// getConstraintType - Given a constraint, return the type of constraint it
1421 /// is for this target.
1422 virtual ConstraintType getConstraintType(const std::string &Constraint) const;
1424 /// getRegForInlineAsmConstraint - Given a physical register constraint (e.g.
1425 /// {edx}), return the register number and the register class for the
1428 /// Given a register class constraint, like 'r', if this corresponds directly
1429 /// to an LLVM register class, return a register of 0 and the register class
1432 /// This should only be used for C_Register constraints. On error,
1433 /// this returns a register number of 0 and a null register class pointer..
1434 virtual std::pair<unsigned, const TargetRegisterClass*>
1435 getRegForInlineAsmConstraint(const std::string &Constraint,
1438 /// LowerXConstraint - try to replace an X constraint, which matches anything,
1439 /// with another that has more specific requirements based on the type of the
1440 /// corresponding operand. This returns null if there is no replacement to
1442 virtual const char *LowerXConstraint(EVT ConstraintVT) const;
1444 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
1445 /// vector. If it is invalid, don't add anything to Ops.
1446 virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
1447 std::vector<SDValue> &Ops,
1448 SelectionDAG &DAG) const;
1450 //===--------------------------------------------------------------------===//
1451 // Instruction Emitting Hooks
1454 // EmitInstrWithCustomInserter - This method should be implemented by targets
1455 // that mark instructions with the 'usesCustomInserter' flag. These
1456 // instructions are special in various ways, which require special support to
1457 // insert. The specified MachineInstr is created but not inserted into any
1458 // basic blocks, and this method is called to expand it into a sequence of
1459 // instructions, potentially also creating new basic blocks and control flow.
1460 virtual MachineBasicBlock *
1461 EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const;
1463 //===--------------------------------------------------------------------===//
1464 // Addressing mode description hooks (used by LSR etc).
1467 /// AddrMode - This represents an addressing mode of:
1468 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
1469 /// If BaseGV is null, there is no BaseGV.
1470 /// If BaseOffs is zero, there is no base offset.
1471 /// If HasBaseReg is false, there is no base register.
1472 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
1476 GlobalValue *BaseGV;
1480 AddrMode() : BaseGV(0), BaseOffs(0), HasBaseReg(false), Scale(0) {}
1483 /// isLegalAddressingMode - Return true if the addressing mode represented by
1484 /// AM is legal for this target, for a load/store of the specified type.
1485 /// The type may be VoidTy, in which case only return true if the addressing
1486 /// mode is legal for a load/store of any legal type.
1487 /// TODO: Handle pre/postinc as well.
1488 virtual bool isLegalAddressingMode(const AddrMode &AM, const Type *Ty) const;
1490 /// isTruncateFree - Return true if it's free to truncate a value of
1491 /// type Ty1 to type Ty2. e.g. On x86 it's free to truncate a i32 value in
1492 /// register EAX to i16 by referencing its sub-register AX.
1493 virtual bool isTruncateFree(const Type *Ty1, const Type *Ty2) const {
1497 virtual bool isTruncateFree(EVT VT1, EVT VT2) const {
1501 /// isZExtFree - Return true if any actual instruction that defines a
1502 /// value of type Ty1 implicitly zero-extends the value to Ty2 in the result
1503 /// register. This does not necessarily include registers defined in
1504 /// unknown ways, such as incoming arguments, or copies from unknown
1505 /// virtual registers. Also, if isTruncateFree(Ty2, Ty1) is true, this
1506 /// does not necessarily apply to truncate instructions. e.g. on x86-64,
1507 /// all instructions that define 32-bit values implicit zero-extend the
1508 /// result out to 64 bits.
1509 virtual bool isZExtFree(const Type *Ty1, const Type *Ty2) const {
1513 virtual bool isZExtFree(EVT VT1, EVT VT2) const {
1517 /// isNarrowingProfitable - Return true if it's profitable to narrow
1518 /// operations of type VT1 to VT2. e.g. on x86, it's profitable to narrow
1519 /// from i32 to i8 but not from i32 to i16.
1520 virtual bool isNarrowingProfitable(EVT VT1, EVT VT2) const {
1524 /// isLegalICmpImmediate - Return true if the specified immediate is legal
1525 /// icmp immediate, that is the target has icmp instructions which can compare
1526 /// a register against the immediate without having to materialize the
1527 /// immediate into a register.
1528 virtual bool isLegalICmpImmediate(int64_t Imm) const {
1532 /// isLegalAddImmediate - Return true if the specified immediate is legal
1533 /// add immediate, that is the target has add instructions which can add
1534 /// a register with the immediate without having to materialize the
1535 /// immediate into a register.
1536 virtual bool isLegalAddImmediate(int64_t Imm) const {
1540 //===--------------------------------------------------------------------===//
1541 // Div utility functions
1543 SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG,
1544 std::vector<SDNode*>* Created) const;
1545 SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG,
1546 std::vector<SDNode*>* Created) const;
1549 //===--------------------------------------------------------------------===//
1550 // Runtime Library hooks
1553 /// setLibcallName - Rename the default libcall routine name for the specified
1555 void setLibcallName(RTLIB::Libcall Call, const char *Name) {
1556 LibcallRoutineNames[Call] = Name;
1559 /// getLibcallName - Get the libcall routine name for the specified libcall.
1561 const char *getLibcallName(RTLIB::Libcall Call) const {
1562 return LibcallRoutineNames[Call];
1565 /// setCmpLibcallCC - Override the default CondCode to be used to test the
1566 /// result of the comparison libcall against zero.
1567 void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
1568 CmpLibcallCCs[Call] = CC;
1571 /// getCmpLibcallCC - Get the CondCode that's to be used to test the result of
1572 /// the comparison libcall against zero.
1573 ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
1574 return CmpLibcallCCs[Call];
1577 /// setLibcallCallingConv - Set the CallingConv that should be used for the
1578 /// specified libcall.
1579 void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
1580 LibcallCallingConvs[Call] = CC;
1583 /// getLibcallCallingConv - Get the CallingConv that should be used for the
1584 /// specified libcall.
1585 CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
1586 return LibcallCallingConvs[Call];
1590 const TargetMachine &TM;
1591 const TargetData *TD;
1592 const TargetLoweringObjectFile &TLOF;
1594 /// We are in the process of implementing a new TypeLegalization action
1595 /// which is the promotion of vector elements. This feature is under
1596 /// development. Until this feature is complete, it is only enabled using a
1597 /// flag. We pass this flag using a member because of circular dep issues.
1598 /// This member will be removed with the flag once we complete the transition.
1599 bool mayPromoteElements;
1601 /// PointerTy - The type to use for pointers, usually i32 or i64.
1605 /// IsLittleEndian - True if this is a little endian target.
1607 bool IsLittleEndian;
1609 /// SelectIsExpensive - Tells the code generator not to expand operations
1610 /// into sequences that use the select operations if possible.
1611 bool SelectIsExpensive;
1613 /// IntDivIsCheap - Tells the code generator not to expand integer divides by
1614 /// constants into a sequence of muls, adds, and shifts. This is a hack until
1615 /// a real cost model is in place. If we ever optimize for size, this will be
1616 /// set to true unconditionally.
1619 /// Pow2DivIsCheap - Tells the code generator that it shouldn't generate
1620 /// srl/add/sra for a signed divide by power of two, and let the target handle
1622 bool Pow2DivIsCheap;
1624 /// JumpIsExpensive - Tells the code generator that it shouldn't generate
1625 /// extra flow control instructions and should attempt to combine flow
1626 /// control instructions via predication.
1627 bool JumpIsExpensive;
1629 /// UseUnderscoreSetJmp - This target prefers to use _setjmp to implement
1630 /// llvm.setjmp. Defaults to false.
1631 bool UseUnderscoreSetJmp;
1633 /// UseUnderscoreLongJmp - This target prefers to use _longjmp to implement
1634 /// llvm.longjmp. Defaults to false.
1635 bool UseUnderscoreLongJmp;
1637 /// BooleanContents - Information about the contents of the high-bits in
1638 /// boolean values held in a type wider than i1. See getBooleanContents.
1639 BooleanContent BooleanContents;
1641 /// SchedPreferenceInfo - The target scheduling preference: shortest possible
1642 /// total cycles or lowest register usage.
1643 Sched::Preference SchedPreferenceInfo;
1645 /// JumpBufSize - The size, in bytes, of the target's jmp_buf buffers
1646 unsigned JumpBufSize;
1648 /// JumpBufAlignment - The alignment, in bytes, of the target's jmp_buf
1650 unsigned JumpBufAlignment;
1652 /// MinStackArgumentAlignment - The minimum alignment that any argument
1653 /// on the stack needs to have.
1655 unsigned MinStackArgumentAlignment;
1657 /// MinFunctionAlignment - The minimum function alignment (used when
1658 /// optimizing for size, and to prevent explicitly provided alignment
1659 /// from leading to incorrect code).
1661 unsigned MinFunctionAlignment;
1663 /// PrefFunctionAlignment - The preferred function alignment (used when
1664 /// alignment unspecified and optimizing for speed).
1666 unsigned PrefFunctionAlignment;
1668 /// PrefLoopAlignment - The preferred loop alignment.
1670 unsigned PrefLoopAlignment;
1672 /// ShouldFoldAtomicFences - Whether fencing MEMBARRIER instructions should
1673 /// be folded into the enclosed atomic intrinsic instruction by the
1675 bool ShouldFoldAtomicFences;
1677 /// StackPointerRegisterToSaveRestore - If set to a physical register, this
1678 /// specifies the register that llvm.savestack/llvm.restorestack should save
1680 unsigned StackPointerRegisterToSaveRestore;
1682 /// ExceptionPointerRegister - If set to a physical register, this specifies
1683 /// the register that receives the exception address on entry to a landing
1685 unsigned ExceptionPointerRegister;
1687 /// ExceptionSelectorRegister - If set to a physical register, this specifies
1688 /// the register that receives the exception typeid on entry to a landing
1690 unsigned ExceptionSelectorRegister;
1692 /// RegClassForVT - This indicates the default register class to use for
1693 /// each ValueType the target supports natively.
1694 TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
1695 unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
1696 EVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
1698 /// RepRegClassForVT - This indicates the "representative" register class to
1699 /// use for each ValueType the target supports natively. This information is
1700 /// used by the scheduler to track register pressure. By default, the
1701 /// representative register class is the largest legal super-reg register
1702 /// class of the register class of the specified type. e.g. On x86, i8, i16,
1703 /// and i32's representative class would be GR32.
1704 const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
1706 /// RepRegClassCostForVT - This indicates the "cost" of the "representative"
1707 /// register class for each ValueType. The cost is used by the scheduler to
1708 /// approximate register pressure.
1709 uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
1711 /// TransformToType - For any value types we are promoting or expanding, this
1712 /// contains the value type that we are changing to. For Expanded types, this
1713 /// contains one step of the expand (e.g. i64 -> i32), even if there are
1714 /// multiple steps required (e.g. i64 -> i16). For types natively supported
1715 /// by the system, this holds the same type (e.g. i32 -> i32).
1716 EVT TransformToType[MVT::LAST_VALUETYPE];
1718 /// OpActions - For each operation and each value type, keep a LegalizeAction
1719 /// that indicates how instruction selection should deal with the operation.
1720 /// Most operations are Legal (aka, supported natively by the target), but
1721 /// operations that are not should be described. Note that operations on
1722 /// non-legal value types are not described here.
1723 uint8_t OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END];
1725 /// LoadExtActions - For each load extension type and each value type,
1726 /// keep a LegalizeAction that indicates how instruction selection should deal
1727 /// with a load of a specific value type and extension type.
1728 uint8_t LoadExtActions[MVT::LAST_VALUETYPE][ISD::LAST_LOADEXT_TYPE];
1730 /// TruncStoreActions - For each value type pair keep a LegalizeAction that
1731 /// indicates whether a truncating store of a specific value type and
1732 /// truncating type is legal.
1733 uint8_t TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
1735 /// IndexedModeActions - For each indexed mode and each value type,
1736 /// keep a pair of LegalizeAction that indicates how instruction
1737 /// selection should deal with the load / store. The first dimension is the
1738 /// value_type for the reference. The second dimension represents the various
1739 /// modes for load store.
1740 uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
1742 /// CondCodeActions - For each condition code (ISD::CondCode) keep a
1743 /// LegalizeAction that indicates how instruction selection should
1744 /// deal with the condition code.
1745 uint64_t CondCodeActions[ISD::SETCC_INVALID];
1747 ValueTypeActionImpl ValueTypeActions;
1749 typedef std::pair<LegalizeTypeAction, EVT> LegalizeKind;
1752 getTypeConversion(LLVMContext &Context, EVT VT) const {
1753 // If this is a simple type, use the ComputeRegisterProp mechanism.
1754 if (VT.isSimple()) {
1755 assert((unsigned)VT.getSimpleVT().SimpleTy <
1756 array_lengthof(TransformToType));
1757 EVT NVT = TransformToType[VT.getSimpleVT().SimpleTy];
1758 LegalizeTypeAction LA = ValueTypeActions.getTypeAction(VT.getSimpleVT());
1761 (!(NVT.isSimple() && LA != TypeLegal) ||
1762 ValueTypeActions.getTypeAction(NVT.getSimpleVT()) != TypePromoteInteger)
1763 && "Promote may not follow Expand or Promote");
1765 return LegalizeKind(LA, NVT);
1768 // Handle Extended Scalar Types.
1769 if (!VT.isVector()) {
1770 assert(VT.isInteger() && "Float types must be simple");
1771 unsigned BitSize = VT.getSizeInBits();
1772 // First promote to a power-of-two size, then expand if necessary.
1773 if (BitSize < 8 || !isPowerOf2_32(BitSize)) {
1774 EVT NVT = VT.getRoundIntegerType(Context);
1775 assert(NVT != VT && "Unable to round integer VT");
1776 LegalizeKind NextStep = getTypeConversion(Context, NVT);
1777 // Avoid multi-step promotion.
1778 if (NextStep.first == TypePromoteInteger) return NextStep;
1779 // Return rounded integer type.
1780 return LegalizeKind(TypePromoteInteger, NVT);
1783 return LegalizeKind(TypeExpandInteger,
1784 EVT::getIntegerVT(Context, VT.getSizeInBits()/2));
1787 // Handle vector types.
1788 unsigned NumElts = VT.getVectorNumElements();
1789 EVT EltVT = VT.getVectorElementType();
1791 // Vectors with only one element are always scalarized.
1793 return LegalizeKind(TypeScalarizeVector, EltVT);
1795 // If we allow the promotion of vector elements using a flag,
1796 // then try to widen vector elements until a legal type is found.
1797 if (mayPromoteElements && EltVT.isInteger()) {
1798 // Vectors with a number of elements that is not a power of two are always
1799 // widened, for example <3 x float> -> <4 x float>.
1800 if (!VT.isPow2VectorType()) {
1801 NumElts = (unsigned)NextPowerOf2(NumElts);
1802 EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts);
1803 return LegalizeKind(TypeWidenVector, NVT);
1806 // Examine the element type.
1807 LegalizeKind LK = getTypeConversion(Context, EltVT);
1809 // If type is to be expanded, split the vector.
1810 // <4 x i140> -> <2 x i140>
1811 if (LK.first == TypeExpandInteger)
1812 return LegalizeKind(TypeSplitVector,
1813 EVT::getVectorVT(Context, EltVT, NumElts / 2));
1815 // Promote the integer element types until a legal vector type is found
1816 // or until the element integer type is too big. If a legal type was not
1817 // found, fallback to the usual mechanism of widening/splitting the
1820 // Increase the bitwidth of the element to the next pow-of-two
1821 // (which is greater than 8 bits).
1822 EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits()
1823 ).getRoundIntegerType(Context);
1825 // Stop trying when getting a non-simple element type.
1826 // Note that vector elements may be greater than legal vector element
1827 // types. Example: X86 XMM registers hold 64bit element on 32bit systems.
1828 if (!EltVT.isSimple()) break;
1830 // Build a new vector type and check if it is legal.
1831 MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1832 // Found a legal promoted vector type.
1833 if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal)
1834 return LegalizeKind(TypePromoteInteger,
1835 EVT::getVectorVT(Context, EltVT, NumElts));
1839 // Try to widen the vector until a legal type is found.
1840 // If there is no wider legal type, split the vector.
1842 // Round up to the next power of 2.
1843 NumElts = (unsigned)NextPowerOf2(NumElts);
1845 // If there is no simple vector type with this many elements then there
1846 // cannot be a larger legal vector type. Note that this assumes that
1847 // there are no skipped intermediate vector types in the simple types.
1848 if (!EltVT.isSimple()) break;
1849 MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1850 if (LargerVector == MVT()) break;
1852 // If this type is legal then widen the vector.
1853 if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal)
1854 return LegalizeKind(TypeWidenVector, LargerVector);
1857 // Widen odd vectors to next power of two.
1858 if (!VT.isPow2VectorType()) {
1859 EVT NVT = VT.getPow2VectorType(Context);
1860 return LegalizeKind(TypeWidenVector, NVT);
1863 // Vectors with illegal element types are expanded.
1864 EVT NVT = EVT::getVectorVT(Context, EltVT, VT.getVectorNumElements() / 2);
1865 return LegalizeKind(TypeSplitVector, NVT);
1867 assert(false && "Unable to handle this kind of vector type");
1868 return LegalizeKind(TypeLegal, VT);
1871 std::vector<std::pair<EVT, TargetRegisterClass*> > AvailableRegClasses;
1873 /// TargetDAGCombineArray - Targets can specify ISD nodes that they would
1874 /// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(),
1875 /// which sets a bit in this array.
1877 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
1879 /// PromoteToType - For operations that must be promoted to a specific type,
1880 /// this holds the destination type. This map should be sparse, so don't hold
1883 /// Targets add entries to this map with AddPromotedToType(..), clients access
1884 /// this with getTypeToPromoteTo(..).
1885 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
1888 /// LibcallRoutineNames - Stores the name each libcall.
1890 const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
1892 /// CmpLibcallCCs - The ISD::CondCode that should be used to test the result
1893 /// of each of the comparison libcall against zero.
1894 ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
1896 /// LibcallCallingConvs - Stores the CallingConv that should be used for each
1898 CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
1901 /// When lowering \@llvm.memset this field specifies the maximum number of
1902 /// store operations that may be substituted for the call to memset. Targets
1903 /// must set this value based on the cost threshold for that target. Targets
1904 /// should assume that the memset will be done using as many of the largest
1905 /// store operations first, followed by smaller ones, if necessary, per
1906 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
1907 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
1908 /// store. This only applies to setting a constant array of a constant size.
1909 /// @brief Specify maximum number of store instructions per memset call.
1910 unsigned maxStoresPerMemset;
1912 /// Maximum number of stores operations that may be substituted for the call
1913 /// to memset, used for functions with OptSize attribute.
1914 unsigned maxStoresPerMemsetOptSize;
1916 /// When lowering \@llvm.memcpy this field specifies the maximum number of
1917 /// store operations that may be substituted for a call to memcpy. Targets
1918 /// must set this value based on the cost threshold for that target. Targets
1919 /// should assume that the memcpy will be done using as many of the largest
1920 /// store operations first, followed by smaller ones, if necessary, per
1921 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
1922 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
1923 /// and one 1-byte store. This only applies to copying a constant array of
1925 /// @brief Specify maximum bytes of store instructions per memcpy call.
1926 unsigned maxStoresPerMemcpy;
1928 /// Maximum number of store operations that may be substituted for a call
1929 /// to memcpy, used for functions with OptSize attribute.
1930 unsigned maxStoresPerMemcpyOptSize;
1932 /// When lowering \@llvm.memmove this field specifies the maximum number of
1933 /// store instructions that may be substituted for a call to memmove. Targets
1934 /// must set this value based on the cost threshold for that target. Targets
1935 /// should assume that the memmove will be done using as many of the largest
1936 /// store operations first, followed by smaller ones, if necessary, per
1937 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
1938 /// with 8-bit alignment would result in nine 1-byte stores. This only
1939 /// applies to copying a constant array of constant size.
1940 /// @brief Specify maximum bytes of store instructions per memmove call.
1941 unsigned maxStoresPerMemmove;
1943 /// Maximum number of store instructions that may be substituted for a call
1944 /// to memmove, used for functions with OpSize attribute.
1945 unsigned maxStoresPerMemmoveOptSize;
1947 /// This field specifies whether the target can benefit from code placement
1949 bool benefitFromCodePlacementOpt;
1952 /// isLegalRC - Return true if the value types that can be represented by the
1953 /// specified register class are all legal.
1954 bool isLegalRC(const TargetRegisterClass *RC) const;
1956 /// hasLegalSuperRegRegClasses - Return true if the specified register class
1957 /// has one or more super-reg register classes that are legal.
1958 bool hasLegalSuperRegRegClasses(const TargetRegisterClass *RC) const;
1961 /// GetReturnInfo - Given an LLVM IR type and return type attributes,
1962 /// compute the return value EVTs and flags, and optionally also
1963 /// the offsets, if the return value is being lowered to memory.
1964 void GetReturnInfo(const Type* ReturnType, Attributes attr,
1965 SmallVectorImpl<ISD::OutputArg> &Outs,
1966 const TargetLowering &TLI,
1967 SmallVectorImpl<uint64_t> *Offsets = 0);
1969 } // end llvm namespace