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/InlineAsm.h"
26 #include "llvm/CodeGen/SelectionDAGNodes.h"
27 #include "llvm/CodeGen/RuntimeLibcalls.h"
28 #include "llvm/ADT/APFloat.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Support/DebugLoc.h"
34 #include "llvm/Target/TargetMachine.h"
44 class MachineBasicBlock;
45 class MachineFunction;
46 class MachineFrameInfo;
48 class MachineModuleInfo;
55 class TargetRegisterClass;
56 class TargetSubtarget;
59 // FIXME: should this be here?
68 TLSModel::Model getTLSModel(const GlobalValue *GV, Reloc::Model reloc);
71 //===----------------------------------------------------------------------===//
72 /// TargetLowering - This class defines information used to lower LLVM code to
73 /// legal SelectionDAG operators that the target instruction selector can accept
76 /// This class also defines callbacks that targets must implement to lower
77 /// target-specific constructs to SelectionDAG operators.
79 class TargetLowering {
81 /// LegalizeAction - This enum indicates whether operations are valid for a
82 /// target, and if not, what action should be used to make them valid.
84 Legal, // The target natively supports this operation.
85 Promote, // This operation should be executed in a larger type.
86 Expand, // Try to expand this to other ops, otherwise use a libcall.
87 Custom // Use the LowerOperation hook to implement custom lowering.
90 enum OutOfRangeShiftAmount {
91 Undefined, // Oversized shift amounts are undefined (default).
92 Mask, // Shift amounts are auto masked (anded) to value size.
93 Extend // Oversized shift pulls in zeros or sign bits.
96 enum BooleanContent { // How the target represents true/false values.
97 UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
98 ZeroOrOneBooleanContent, // All bits zero except for bit 0.
99 ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
102 enum SchedPreference {
103 SchedulingForLatency, // Scheduling for shortest total latency.
104 SchedulingForRegPressure // Scheduling for lowest register pressure.
107 explicit TargetLowering(TargetMachine &TM);
108 virtual ~TargetLowering();
110 TargetMachine &getTargetMachine() const { return TM; }
111 const TargetData *getTargetData() const { return TD; }
113 bool isBigEndian() const { return !IsLittleEndian; }
114 bool isLittleEndian() const { return IsLittleEndian; }
115 MVT getPointerTy() const { return PointerTy; }
116 MVT getShiftAmountTy() const { return ShiftAmountTy; }
117 OutOfRangeShiftAmount getShiftAmountFlavor() const {return ShiftAmtHandling; }
119 /// usesGlobalOffsetTable - Return true if this target uses a GOT for PIC
121 bool usesGlobalOffsetTable() const { return UsesGlobalOffsetTable; }
123 /// isSelectExpensive - Return true if the select operation is expensive for
125 bool isSelectExpensive() const { return SelectIsExpensive; }
127 /// isIntDivCheap() - Return true if integer divide is usually cheaper than
128 /// a sequence of several shifts, adds, and multiplies for this target.
129 bool isIntDivCheap() const { return IntDivIsCheap; }
131 /// isPow2DivCheap() - Return true if pow2 div is cheaper than a chain of
133 bool isPow2DivCheap() const { return Pow2DivIsCheap; }
135 /// getSetCCResultType - Return the ValueType of the result of SETCC
136 /// operations. Also used to obtain the target's preferred type for
137 /// the condition operand of SELECT and BRCOND nodes. In the case of
138 /// BRCOND the argument passed is MVT::Other since there are no other
139 /// operands to get a type hint from.
140 virtual MVT getSetCCResultType(MVT VT) const;
142 /// getBooleanContents - For targets without i1 registers, this gives the
143 /// nature of the high-bits of boolean values held in types wider than i1.
144 /// "Boolean values" are special true/false values produced by nodes like
145 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
146 /// Not to be confused with general values promoted from i1.
147 BooleanContent getBooleanContents() const { return BooleanContents;}
149 /// getSchedulingPreference - Return target scheduling preference.
150 SchedPreference getSchedulingPreference() const {
151 return SchedPreferenceInfo;
154 /// getRegClassFor - Return the register class that should be used for the
155 /// specified value type. This may only be called on legal types.
156 TargetRegisterClass *getRegClassFor(MVT VT) const {
157 assert((unsigned)VT.getSimpleVT() < array_lengthof(RegClassForVT));
158 TargetRegisterClass *RC = RegClassForVT[VT.getSimpleVT()];
159 assert(RC && "This value type is not natively supported!");
163 /// isTypeLegal - Return true if the target has native support for the
164 /// specified value type. This means that it has a register that directly
165 /// holds it without promotions or expansions.
166 bool isTypeLegal(MVT VT) const {
167 assert(!VT.isSimple() ||
168 (unsigned)VT.getSimpleVT() < array_lengthof(RegClassForVT));
169 return VT.isSimple() && RegClassForVT[VT.getSimpleVT()] != 0;
172 class ValueTypeActionImpl {
173 /// ValueTypeActions - This is a bitvector that contains two bits for each
174 /// value type, where the two bits correspond to the LegalizeAction enum.
175 /// This can be queried with "getTypeAction(VT)".
176 /// dimension by (MVT::MAX_ALLOWED_VALUETYPE/32) * 2
177 uint32_t ValueTypeActions[(MVT::MAX_ALLOWED_VALUETYPE/32)*2];
179 ValueTypeActionImpl() {
180 ValueTypeActions[0] = ValueTypeActions[1] = 0;
181 ValueTypeActions[2] = ValueTypeActions[3] = 0;
183 ValueTypeActionImpl(const ValueTypeActionImpl &RHS) {
184 ValueTypeActions[0] = RHS.ValueTypeActions[0];
185 ValueTypeActions[1] = RHS.ValueTypeActions[1];
186 ValueTypeActions[2] = RHS.ValueTypeActions[2];
187 ValueTypeActions[3] = RHS.ValueTypeActions[3];
190 LegalizeAction getTypeAction(MVT VT) const {
191 if (VT.isExtended()) {
193 return VT.isPow2VectorType() ? Expand : Promote;
196 // First promote to a power-of-two size, then expand if necessary.
197 return VT == VT.getRoundIntegerType() ? Expand : Promote;
198 assert(0 && "Unsupported extended type!");
201 unsigned I = VT.getSimpleVT();
202 assert(I<4*array_lengthof(ValueTypeActions)*sizeof(ValueTypeActions[0]));
203 return (LegalizeAction)((ValueTypeActions[I>>4] >> ((2*I) & 31)) & 3);
205 void setTypeAction(MVT VT, LegalizeAction Action) {
206 unsigned I = VT.getSimpleVT();
207 assert(I<4*array_lengthof(ValueTypeActions)*sizeof(ValueTypeActions[0]));
208 ValueTypeActions[I>>4] |= Action << ((I*2) & 31);
212 const ValueTypeActionImpl &getValueTypeActions() const {
213 return ValueTypeActions;
216 /// getTypeAction - Return how we should legalize values of this type, either
217 /// it is already legal (return 'Legal') or we need to promote it to a larger
218 /// type (return 'Promote'), or we need to expand it into multiple registers
219 /// of smaller integer type (return 'Expand'). 'Custom' is not an option.
220 LegalizeAction getTypeAction(MVT VT) const {
221 return ValueTypeActions.getTypeAction(VT);
224 /// getTypeToTransformTo - For types supported by the target, this is an
225 /// identity function. For types that must be promoted to larger types, this
226 /// returns the larger type to promote to. For integer types that are larger
227 /// than the largest integer register, this contains one step in the expansion
228 /// to get to the smaller register. For illegal floating point types, this
229 /// returns the integer type to transform to.
230 MVT getTypeToTransformTo(MVT VT) const {
232 assert((unsigned)VT.getSimpleVT() < array_lengthof(TransformToType));
233 MVT NVT = TransformToType[VT.getSimpleVT()];
234 assert(getTypeAction(NVT) != Promote &&
235 "Promote may not follow Expand or Promote");
240 MVT NVT = VT.getPow2VectorType();
242 // Vector length is a power of 2 - split to half the size.
243 unsigned NumElts = VT.getVectorNumElements();
244 MVT EltVT = VT.getVectorElementType();
245 return (NumElts == 1) ? EltVT : MVT::getVectorVT(EltVT, NumElts / 2);
247 // Promote to a power of two size, avoiding multi-step promotion.
248 return getTypeAction(NVT) == Promote ? getTypeToTransformTo(NVT) : NVT;
249 } else if (VT.isInteger()) {
250 MVT NVT = VT.getRoundIntegerType();
252 // Size is a power of two - expand to half the size.
253 return MVT::getIntegerVT(VT.getSizeInBits() / 2);
255 // Promote to a power of two size, avoiding multi-step promotion.
256 return getTypeAction(NVT) == Promote ? getTypeToTransformTo(NVT) : NVT;
258 assert(0 && "Unsupported extended type!");
259 return MVT(); // Not reached
262 /// getTypeToExpandTo - For types supported by the target, this is an
263 /// identity function. For types that must be expanded (i.e. integer types
264 /// that are larger than the largest integer register or illegal floating
265 /// point types), this returns the largest legal type it will be expanded to.
266 MVT getTypeToExpandTo(MVT VT) const {
267 assert(!VT.isVector());
269 switch (getTypeAction(VT)) {
273 VT = getTypeToTransformTo(VT);
276 assert(false && "Type is not legal nor is it to be expanded!");
283 /// getVectorTypeBreakdown - Vector types are broken down into some number of
284 /// legal first class types. For example, MVT::v8f32 maps to 2 MVT::v4f32
285 /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
286 /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
288 /// This method returns the number of registers needed, and the VT for each
289 /// register. It also returns the VT and quantity of the intermediate values
290 /// before they are promoted/expanded.
292 unsigned getVectorTypeBreakdown(MVT VT,
294 unsigned &NumIntermediates,
295 MVT &RegisterVT) const;
297 /// getTgtMemIntrinsic: Given an intrinsic, checks if on the target the
298 /// intrinsic will need to map to a MemIntrinsicNode (touches memory). If
299 /// this is the case, it returns true and store the intrinsic
300 /// information into the IntrinsicInfo that was passed to the function.
301 typedef struct IntrinsicInfo {
302 unsigned opc; // target opcode
303 MVT memVT; // memory VT
304 const Value* ptrVal; // value representing memory location
305 int offset; // offset off of ptrVal
306 unsigned align; // alignment
307 bool vol; // is volatile?
308 bool readMem; // reads memory?
309 bool writeMem; // writes memory?
312 virtual bool getTgtMemIntrinsic(IntrinsicInfo& Info,
313 CallInst &I, unsigned Intrinsic) {
317 /// getWidenVectorType: given a vector type, returns the type to widen to
318 /// (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
319 /// If there is no vector type that we want to widen to, returns MVT::Other
320 /// When and were to widen is target dependent based on the cost of
321 /// scalarizing vs using the wider vector type.
322 virtual MVT getWidenVectorType(MVT VT) const;
324 typedef std::vector<APFloat>::const_iterator legal_fpimm_iterator;
325 legal_fpimm_iterator legal_fpimm_begin() const {
326 return LegalFPImmediates.begin();
328 legal_fpimm_iterator legal_fpimm_end() const {
329 return LegalFPImmediates.end();
332 /// isShuffleMaskLegal - Targets can use this to indicate that they only
333 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
334 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
335 /// are assumed to be legal.
336 virtual bool isShuffleMaskLegal(const SmallVectorImpl<int> &Mask,
341 /// isVectorClearMaskLegal - Similar to isShuffleMaskLegal. This is
342 /// used by Targets can use this to indicate if there is a suitable
343 /// VECTOR_SHUFFLE that can be used to replace a VAND with a constant
345 virtual bool isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
350 /// getOperationAction - Return how this operation should be treated: either
351 /// it is legal, needs to be promoted to a larger size, needs to be
352 /// expanded to some other code sequence, or the target has a custom expander
354 LegalizeAction getOperationAction(unsigned Op, MVT VT) const {
355 if (VT.isExtended()) return Expand;
356 assert(Op < array_lengthof(OpActions[0]) &&
357 (unsigned)VT.getSimpleVT() < sizeof(OpActions[0][0])*8 &&
358 "Table isn't big enough!");
359 unsigned I = (unsigned) VT.getSimpleVT();
362 return (LegalizeAction)((OpActions[I][Op] >> (J*2) ) & 3);
365 /// isOperationLegalOrCustom - Return true if the specified operation is
366 /// legal on this target or can be made legal with custom lowering. This
367 /// is used to help guide high-level lowering decisions.
368 bool isOperationLegalOrCustom(unsigned Op, MVT VT) const {
369 return (VT == MVT::Other || isTypeLegal(VT)) &&
370 (getOperationAction(Op, VT) == Legal ||
371 getOperationAction(Op, VT) == Custom);
374 /// isOperationLegal - Return true if the specified operation is legal on this
376 bool isOperationLegal(unsigned Op, MVT VT) const {
377 return (VT == MVT::Other || isTypeLegal(VT)) &&
378 getOperationAction(Op, VT) == Legal;
381 /// getLoadExtAction - Return how this load with extension should be treated:
382 /// either it is legal, needs to be promoted to a larger size, needs to be
383 /// expanded to some other code sequence, or the target has a custom expander
385 LegalizeAction getLoadExtAction(unsigned LType, MVT VT) const {
386 assert(LType < array_lengthof(LoadExtActions) &&
387 (unsigned)VT.getSimpleVT() < sizeof(LoadExtActions[0])*4 &&
388 "Table isn't big enough!");
389 return (LegalizeAction)((LoadExtActions[LType] >> (2*VT.getSimpleVT())) & 3);
392 /// isLoadExtLegal - Return true if the specified load with extension is legal
394 bool isLoadExtLegal(unsigned LType, MVT VT) const {
395 return VT.isSimple() &&
396 (getLoadExtAction(LType, VT) == Legal ||
397 getLoadExtAction(LType, VT) == Custom);
400 /// getTruncStoreAction - Return how this store with truncation should be
401 /// treated: either it is legal, needs to be promoted to a larger size, needs
402 /// to be expanded to some other code sequence, or the target has a custom
404 LegalizeAction getTruncStoreAction(MVT ValVT,
406 assert((unsigned)ValVT.getSimpleVT() < array_lengthof(TruncStoreActions) &&
407 (unsigned)MemVT.getSimpleVT() < sizeof(TruncStoreActions[0])*4 &&
408 "Table isn't big enough!");
409 return (LegalizeAction)((TruncStoreActions[ValVT.getSimpleVT()] >>
410 (2*MemVT.getSimpleVT())) & 3);
413 /// isTruncStoreLegal - Return true if the specified store with truncation is
414 /// legal on this target.
415 bool isTruncStoreLegal(MVT ValVT, MVT MemVT) const {
416 return isTypeLegal(ValVT) && MemVT.isSimple() &&
417 (getTruncStoreAction(ValVT, MemVT) == Legal ||
418 getTruncStoreAction(ValVT, MemVT) == Custom);
421 /// getIndexedLoadAction - Return how the indexed load should be treated:
422 /// either it is legal, needs to be promoted to a larger size, needs to be
423 /// expanded to some other code sequence, or the target has a custom expander
426 getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
427 assert( IdxMode < array_lengthof(IndexedModeActions[0][0]) &&
428 ((unsigned)VT.getSimpleVT()) < MVT::LAST_VALUETYPE &&
429 "Table isn't big enough!");
430 return (LegalizeAction)((IndexedModeActions[(unsigned)VT.getSimpleVT()][0][IdxMode]));
433 /// isIndexedLoadLegal - Return true if the specified indexed load is legal
435 bool isIndexedLoadLegal(unsigned IdxMode, MVT VT) const {
436 return VT.isSimple() &&
437 (getIndexedLoadAction(IdxMode, VT) == Legal ||
438 getIndexedLoadAction(IdxMode, VT) == Custom);
441 /// getIndexedStoreAction - Return how the indexed store should be treated:
442 /// either it is legal, needs to be promoted to a larger size, needs to be
443 /// expanded to some other code sequence, or the target has a custom expander
446 getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
447 assert(IdxMode < array_lengthof(IndexedModeActions[0][1]) &&
448 (unsigned)VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
449 "Table isn't big enough!");
450 return (LegalizeAction)((IndexedModeActions[(unsigned)VT.getSimpleVT()][1][IdxMode]));
453 /// isIndexedStoreLegal - Return true if the specified indexed load is legal
455 bool isIndexedStoreLegal(unsigned IdxMode, MVT VT) const {
456 return VT.isSimple() &&
457 (getIndexedStoreAction(IdxMode, VT) == Legal ||
458 getIndexedStoreAction(IdxMode, VT) == Custom);
461 /// getConvertAction - Return how the conversion should be treated:
462 /// either it is legal, needs to be promoted to a larger size, needs to be
463 /// expanded to some other code sequence, or the target has a custom expander
466 getConvertAction(MVT FromVT, MVT ToVT) const {
467 assert((unsigned)FromVT.getSimpleVT() < array_lengthof(ConvertActions) &&
468 (unsigned)ToVT.getSimpleVT() < sizeof(ConvertActions[0])*4 &&
469 "Table isn't big enough!");
470 return (LegalizeAction)((ConvertActions[FromVT.getSimpleVT()] >>
471 (2*ToVT.getSimpleVT())) & 3);
474 /// isConvertLegal - Return true if the specified conversion is legal
476 bool isConvertLegal(MVT FromVT, MVT ToVT) const {
477 return isTypeLegal(FromVT) && isTypeLegal(ToVT) &&
478 (getConvertAction(FromVT, ToVT) == Legal ||
479 getConvertAction(FromVT, ToVT) == Custom);
482 /// getCondCodeAction - Return how the condition code should be treated:
483 /// either it is legal, needs to be expanded to some other code sequence,
484 /// or the target has a custom expander for it.
486 getCondCodeAction(ISD::CondCode CC, MVT VT) const {
487 assert((unsigned)CC < array_lengthof(CondCodeActions) &&
488 (unsigned)VT.getSimpleVT() < sizeof(CondCodeActions[0])*4 &&
489 "Table isn't big enough!");
490 LegalizeAction Action = (LegalizeAction)
491 ((CondCodeActions[CC] >> (2*VT.getSimpleVT())) & 3);
492 assert(Action != Promote && "Can't promote condition code!");
496 /// isCondCodeLegal - Return true if the specified condition code is legal
498 bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
499 return getCondCodeAction(CC, VT) == Legal ||
500 getCondCodeAction(CC, VT) == Custom;
504 /// getTypeToPromoteTo - If the action for this operation is to promote, this
505 /// method returns the ValueType to promote to.
506 MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
507 assert(getOperationAction(Op, VT) == Promote &&
508 "This operation isn't promoted!");
510 // See if this has an explicit type specified.
511 std::map<std::pair<unsigned, MVT::SimpleValueType>,
512 MVT::SimpleValueType>::const_iterator PTTI =
513 PromoteToType.find(std::make_pair(Op, VT.getSimpleVT()));
514 if (PTTI != PromoteToType.end()) return PTTI->second;
516 assert((VT.isInteger() || VT.isFloatingPoint()) &&
517 "Cannot autopromote this type, add it with AddPromotedToType.");
521 NVT = (MVT::SimpleValueType)(NVT.getSimpleVT()+1);
522 assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
523 "Didn't find type to promote to!");
524 } while (!isTypeLegal(NVT) ||
525 getOperationAction(Op, NVT) == Promote);
529 /// getValueType - Return the MVT corresponding to this LLVM type.
530 /// This is fixed by the LLVM operations except for the pointer size. If
531 /// AllowUnknown is true, this will return MVT::Other for types with no MVT
532 /// counterpart (e.g. structs), otherwise it will assert.
533 MVT getValueType(const Type *Ty, bool AllowUnknown = false) const {
534 MVT VT = MVT::getMVT(Ty, AllowUnknown);
535 return VT == MVT::iPTR ? PointerTy : VT;
538 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
539 /// function arguments in the caller parameter area. This is the actual
540 /// alignment, not its logarithm.
541 virtual unsigned getByValTypeAlignment(const Type *Ty) const;
543 /// getRegisterType - Return the type of registers that this ValueType will
544 /// eventually require.
545 MVT getRegisterType(MVT VT) const {
547 assert((unsigned)VT.getSimpleVT() < array_lengthof(RegisterTypeForVT));
548 return RegisterTypeForVT[VT.getSimpleVT()];
552 unsigned NumIntermediates;
553 (void)getVectorTypeBreakdown(VT, VT1, NumIntermediates, RegisterVT);
556 if (VT.isInteger()) {
557 return getRegisterType(getTypeToTransformTo(VT));
559 assert(0 && "Unsupported extended type!");
560 return MVT(); // Not reached
563 /// getNumRegisters - Return the number of registers that this ValueType will
564 /// eventually require. This is one for any types promoted to live in larger
565 /// registers, but may be more than one for types (like i64) that are split
566 /// into pieces. For types like i140, which are first promoted then expanded,
567 /// it is the number of registers needed to hold all the bits of the original
568 /// type. For an i140 on a 32 bit machine this means 5 registers.
569 unsigned getNumRegisters(MVT VT) const {
571 assert((unsigned)VT.getSimpleVT() < array_lengthof(NumRegistersForVT));
572 return NumRegistersForVT[VT.getSimpleVT()];
576 unsigned NumIntermediates;
577 return getVectorTypeBreakdown(VT, VT1, NumIntermediates, VT2);
579 if (VT.isInteger()) {
580 unsigned BitWidth = VT.getSizeInBits();
581 unsigned RegWidth = getRegisterType(VT).getSizeInBits();
582 return (BitWidth + RegWidth - 1) / RegWidth;
584 assert(0 && "Unsupported extended type!");
585 return 0; // Not reached
588 /// ShouldShrinkFPConstant - If true, then instruction selection should
589 /// seek to shrink the FP constant of the specified type to a smaller type
590 /// in order to save space and / or reduce runtime.
591 virtual bool ShouldShrinkFPConstant(MVT VT) const { return true; }
593 /// hasTargetDAGCombine - If true, the target has custom DAG combine
594 /// transformations that it can perform for the specified node.
595 bool hasTargetDAGCombine(ISD::NodeType NT) const {
596 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
597 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
600 /// This function returns the maximum number of store operations permitted
601 /// to replace a call to llvm.memset. The value is set by the target at the
602 /// performance threshold for such a replacement.
603 /// @brief Get maximum # of store operations permitted for llvm.memset
604 unsigned getMaxStoresPerMemset() const { return maxStoresPerMemset; }
606 /// This function returns the maximum number of store operations permitted
607 /// to replace a call to llvm.memcpy. The value is set by the target at the
608 /// performance threshold for such a replacement.
609 /// @brief Get maximum # of store operations permitted for llvm.memcpy
610 unsigned getMaxStoresPerMemcpy() const { return maxStoresPerMemcpy; }
612 /// This function returns the maximum number of store operations permitted
613 /// to replace a call to llvm.memmove. The value is set by the target at the
614 /// performance threshold for such a replacement.
615 /// @brief Get maximum # of store operations permitted for llvm.memmove
616 unsigned getMaxStoresPerMemmove() const { return maxStoresPerMemmove; }
618 /// This function returns true if the target allows unaligned memory accesses.
619 /// This is used, for example, in situations where an array copy/move/set is
620 /// converted to a sequence of store operations. It's use helps to ensure that
621 /// such replacements don't generate code that causes an alignment error
622 /// (trap) on the target machine.
623 /// @brief Determine if the target supports unaligned memory accesses.
624 bool allowsUnalignedMemoryAccesses() const {
625 return allowUnalignedMemoryAccesses;
628 /// This function returns true if the target would benefit from code placement
630 /// @brief Determine if the target should perform code placement optimization.
631 bool shouldOptimizeCodePlacement() const {
632 return benefitFromCodePlacementOpt;
635 /// getOptimalMemOpType - Returns the target specific optimal type for load
636 /// and store operations as a result of memset, memcpy, and memmove lowering.
637 /// It returns MVT::iAny if SelectionDAG should be responsible for
639 virtual MVT getOptimalMemOpType(uint64_t Size, unsigned Align,
640 bool isSrcConst, bool isSrcStr,
641 SelectionDAG &DAG) const {
645 /// usesUnderscoreSetJmp - Determine if we should use _setjmp or setjmp
646 /// to implement llvm.setjmp.
647 bool usesUnderscoreSetJmp() const {
648 return UseUnderscoreSetJmp;
651 /// usesUnderscoreLongJmp - Determine if we should use _longjmp or longjmp
652 /// to implement llvm.longjmp.
653 bool usesUnderscoreLongJmp() const {
654 return UseUnderscoreLongJmp;
657 /// getStackPointerRegisterToSaveRestore - If a physical register, this
658 /// specifies the register that llvm.savestack/llvm.restorestack should save
660 unsigned getStackPointerRegisterToSaveRestore() const {
661 return StackPointerRegisterToSaveRestore;
664 /// getExceptionAddressRegister - If a physical register, this returns
665 /// the register that receives the exception address on entry to a landing
667 unsigned getExceptionAddressRegister() const {
668 return ExceptionPointerRegister;
671 /// getExceptionSelectorRegister - If a physical register, this returns
672 /// the register that receives the exception typeid on entry to a landing
674 unsigned getExceptionSelectorRegister() const {
675 return ExceptionSelectorRegister;
678 /// getJumpBufSize - returns the target's jmp_buf size in bytes (if never
679 /// set, the default is 200)
680 unsigned getJumpBufSize() const {
684 /// getJumpBufAlignment - returns the target's jmp_buf alignment in bytes
685 /// (if never set, the default is 0)
686 unsigned getJumpBufAlignment() const {
687 return JumpBufAlignment;
690 /// getIfCvtBlockLimit - returns the target specific if-conversion block size
691 /// limit. Any block whose size is greater should not be predicated.
692 unsigned getIfCvtBlockSizeLimit() const {
693 return IfCvtBlockSizeLimit;
696 /// getIfCvtDupBlockLimit - returns the target specific size limit for a
697 /// block to be considered for duplication. Any block whose size is greater
698 /// should not be duplicated to facilitate its predication.
699 unsigned getIfCvtDupBlockSizeLimit() const {
700 return IfCvtDupBlockSizeLimit;
703 /// getPrefLoopAlignment - return the preferred loop alignment.
705 unsigned getPrefLoopAlignment() const {
706 return PrefLoopAlignment;
709 /// getPreIndexedAddressParts - returns true by value, base pointer and
710 /// offset pointer and addressing mode by reference if the node's address
711 /// can be legally represented as pre-indexed load / store address.
712 virtual bool getPreIndexedAddressParts(SDNode *N, SDValue &Base,
714 ISD::MemIndexedMode &AM,
715 SelectionDAG &DAG) const {
719 /// getPostIndexedAddressParts - returns true by value, base pointer and
720 /// offset pointer and addressing mode by reference if this node can be
721 /// combined with a load / store to form a post-indexed load / store.
722 virtual bool getPostIndexedAddressParts(SDNode *N, SDNode *Op,
723 SDValue &Base, SDValue &Offset,
724 ISD::MemIndexedMode &AM,
725 SelectionDAG &DAG) const {
729 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
731 virtual SDValue getPICJumpTableRelocBase(SDValue Table,
732 SelectionDAG &DAG) const;
734 /// isOffsetFoldingLegal - Return true if folding a constant offset
735 /// with the given GlobalAddress is legal. It is frequently not legal in
736 /// PIC relocation models.
737 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
739 //===--------------------------------------------------------------------===//
740 // TargetLowering Optimization Methods
743 /// TargetLoweringOpt - A convenience struct that encapsulates a DAG, and two
744 /// SDValues for returning information from TargetLowering to its clients
745 /// that want to combine
746 struct TargetLoweringOpt {
751 explicit TargetLoweringOpt(SelectionDAG &InDAG) : DAG(InDAG) {}
753 bool CombineTo(SDValue O, SDValue N) {
759 /// ShrinkDemandedConstant - Check to see if the specified operand of the
760 /// specified instruction is a constant integer. If so, check to see if
761 /// there are any bits set in the constant that are not demanded. If so,
762 /// shrink the constant and return true.
763 bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded);
765 /// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the
766 /// casts are free. This uses isZExtFree and ZERO_EXTEND for the widening
767 /// cast, but it could be generalized for targets with other types of
768 /// implicit widening casts.
769 bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
773 /// SimplifyDemandedBits - Look at Op. At this point, we know that only the
774 /// DemandedMask bits of the result of Op are ever used downstream. If we can
775 /// use this information to simplify Op, create a new simplified DAG node and
776 /// return true, returning the original and new nodes in Old and New.
777 /// Otherwise, analyze the expression and return a mask of KnownOne and
778 /// KnownZero bits for the expression (used to simplify the caller).
779 /// The KnownZero/One bits may only be accurate for those bits in the
781 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
782 APInt &KnownZero, APInt &KnownOne,
783 TargetLoweringOpt &TLO, unsigned Depth = 0) const;
785 /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
786 /// Mask are known to be either zero or one and return them in the
787 /// KnownZero/KnownOne bitsets.
788 virtual void computeMaskedBitsForTargetNode(const SDValue Op,
792 const SelectionDAG &DAG,
793 unsigned Depth = 0) const;
795 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
796 /// targets that want to expose additional information about sign bits to the
798 virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
799 unsigned Depth = 0) const;
801 struct DAGCombinerInfo {
802 void *DC; // The DAG Combiner object.
804 bool CalledByLegalizer;
808 DAGCombinerInfo(SelectionDAG &dag, bool bl, bool cl, void *dc)
809 : DC(dc), BeforeLegalize(bl), CalledByLegalizer(cl), DAG(dag) {}
811 bool isBeforeLegalize() const { return BeforeLegalize; }
812 bool isCalledByLegalizer() const { return CalledByLegalizer; }
814 void AddToWorklist(SDNode *N);
815 SDValue CombineTo(SDNode *N, const std::vector<SDValue> &To,
817 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
818 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
820 void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
823 /// SimplifySetCC - Try to simplify a setcc built with the specified operands
824 /// and cc. If it is unable to simplify it, return a null SDValue.
825 SDValue SimplifySetCC(MVT VT, SDValue N0, SDValue N1,
826 ISD::CondCode Cond, bool foldBooleans,
827 DAGCombinerInfo &DCI, DebugLoc dl) const;
829 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
830 /// node is a GlobalAddress + offset.
832 isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) const;
834 /// isConsecutiveLoad - Return true if LD is loading 'Bytes' bytes from a
835 /// location that is 'Dist' units away from the location that the 'Base' load
837 bool isConsecutiveLoad(LoadSDNode *LD, LoadSDNode *Base, unsigned Bytes,
838 int Dist, const MachineFrameInfo *MFI) const;
840 /// PerformDAGCombine - This method will be invoked for all target nodes and
841 /// for any target-independent nodes that the target has registered with
844 /// The semantics are as follows:
846 /// SDValue.Val == 0 - No change was made
847 /// SDValue.Val == N - N was replaced, is dead, and is already handled.
848 /// otherwise - N should be replaced by the returned Operand.
850 /// In addition, methods provided by DAGCombinerInfo may be used to perform
851 /// more complex transformations.
853 virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
855 //===--------------------------------------------------------------------===//
856 // TargetLowering Configuration Methods - These methods should be invoked by
857 // the derived class constructor to configure this object for the target.
861 /// setUsesGlobalOffsetTable - Specify that this target does or doesn't use a
862 /// GOT for PC-relative code.
863 void setUsesGlobalOffsetTable(bool V) { UsesGlobalOffsetTable = V; }
865 /// setShiftAmountType - Describe the type that should be used for shift
866 /// amounts. This type defaults to the pointer type.
867 void setShiftAmountType(MVT VT) { ShiftAmountTy = VT; }
869 /// setBooleanContents - Specify how the target extends the result of a
870 /// boolean value from i1 to a wider type. See getBooleanContents.
871 void setBooleanContents(BooleanContent Ty) { BooleanContents = Ty; }
873 /// setSchedulingPreference - Specify the target scheduling preference.
874 void setSchedulingPreference(SchedPreference Pref) {
875 SchedPreferenceInfo = Pref;
878 /// setShiftAmountFlavor - Describe how the target handles out of range shift
880 void setShiftAmountFlavor(OutOfRangeShiftAmount OORSA) {
881 ShiftAmtHandling = OORSA;
884 /// setUseUnderscoreSetJmp - Indicate whether this target prefers to
885 /// use _setjmp to implement llvm.setjmp or the non _ version.
886 /// Defaults to false.
887 void setUseUnderscoreSetJmp(bool Val) {
888 UseUnderscoreSetJmp = Val;
891 /// setUseUnderscoreLongJmp - Indicate whether this target prefers to
892 /// use _longjmp to implement llvm.longjmp or the non _ version.
893 /// Defaults to false.
894 void setUseUnderscoreLongJmp(bool Val) {
895 UseUnderscoreLongJmp = Val;
898 /// setStackPointerRegisterToSaveRestore - If set to a physical register, this
899 /// specifies the register that llvm.savestack/llvm.restorestack should save
901 void setStackPointerRegisterToSaveRestore(unsigned R) {
902 StackPointerRegisterToSaveRestore = R;
905 /// setExceptionPointerRegister - If set to a physical register, this sets
906 /// the register that receives the exception address on entry to a landing
908 void setExceptionPointerRegister(unsigned R) {
909 ExceptionPointerRegister = R;
912 /// setExceptionSelectorRegister - If set to a physical register, this sets
913 /// the register that receives the exception typeid on entry to a landing
915 void setExceptionSelectorRegister(unsigned R) {
916 ExceptionSelectorRegister = R;
919 /// SelectIsExpensive - Tells the code generator not to expand operations
920 /// into sequences that use the select operations if possible.
921 void setSelectIsExpensive() { SelectIsExpensive = true; }
923 /// setIntDivIsCheap - Tells the code generator that integer divide is
924 /// expensive, and if possible, should be replaced by an alternate sequence
925 /// of instructions not containing an integer divide.
926 void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
928 /// setPow2DivIsCheap - Tells the code generator that it shouldn't generate
929 /// srl/add/sra for a signed divide by power of two, and let the target handle
931 void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
933 /// addRegisterClass - Add the specified register class as an available
934 /// regclass for the specified value type. This indicates the selector can
935 /// handle values of that class natively.
936 void addRegisterClass(MVT VT, TargetRegisterClass *RC) {
937 assert((unsigned)VT.getSimpleVT() < array_lengthof(RegClassForVT));
938 AvailableRegClasses.push_back(std::make_pair(VT, RC));
939 RegClassForVT[VT.getSimpleVT()] = RC;
942 /// computeRegisterProperties - Once all of the register classes are added,
943 /// this allows us to compute derived properties we expose.
944 void computeRegisterProperties();
946 /// setOperationAction - Indicate that the specified operation does not work
947 /// with the specified type and indicate what to do about it.
948 void setOperationAction(unsigned Op, MVT VT,
949 LegalizeAction Action) {
950 assert((unsigned)VT.getSimpleVT() < sizeof(OpActions[0][0])*8 &&
951 Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
952 unsigned I = (unsigned) VT.getSimpleVT();
955 OpActions[I][Op] &= ~(uint64_t(3UL) << (J*2));
956 OpActions[I][Op] |= (uint64_t)Action << (J*2);
959 /// setLoadExtAction - Indicate that the specified load with extension does
960 /// not work with the with specified type and indicate what to do about it.
961 void setLoadExtAction(unsigned ExtType, MVT VT,
962 LegalizeAction Action) {
963 assert((unsigned)VT.getSimpleVT() < sizeof(LoadExtActions[0])*4 &&
964 ExtType < array_lengthof(LoadExtActions) &&
965 "Table isn't big enough!");
966 LoadExtActions[ExtType] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
967 LoadExtActions[ExtType] |= (uint64_t)Action << VT.getSimpleVT()*2;
970 /// setTruncStoreAction - Indicate that the specified truncating store does
971 /// not work with the with specified type and indicate what to do about it.
972 void setTruncStoreAction(MVT ValVT, MVT MemVT,
973 LegalizeAction Action) {
974 assert((unsigned)ValVT.getSimpleVT() < array_lengthof(TruncStoreActions) &&
975 (unsigned)MemVT.getSimpleVT() < sizeof(TruncStoreActions[0])*4 &&
976 "Table isn't big enough!");
977 TruncStoreActions[ValVT.getSimpleVT()] &= ~(uint64_t(3UL) <<
978 MemVT.getSimpleVT()*2);
979 TruncStoreActions[ValVT.getSimpleVT()] |= (uint64_t)Action <<
980 MemVT.getSimpleVT()*2;
983 /// setIndexedLoadAction - Indicate that the specified indexed load does or
984 /// does not work with the with specified type and indicate what to do abort
985 /// it. NOTE: All indexed mode loads are initialized to Expand in
986 /// TargetLowering.cpp
987 void setIndexedLoadAction(unsigned IdxMode, MVT VT,
988 LegalizeAction Action) {
989 assert((unsigned)VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
990 IdxMode < array_lengthof(IndexedModeActions[0][0]) &&
991 "Table isn't big enough!");
992 IndexedModeActions[(unsigned)VT.getSimpleVT()][0][IdxMode] = (uint8_t)Action;
995 /// setIndexedStoreAction - Indicate that the specified indexed store does or
996 /// does not work with the with specified type and indicate what to do about
997 /// it. NOTE: All indexed mode stores are initialized to Expand in
998 /// TargetLowering.cpp
999 void setIndexedStoreAction(unsigned IdxMode, MVT VT,
1000 LegalizeAction Action) {
1001 assert((unsigned)VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
1002 IdxMode < array_lengthof(IndexedModeActions[0][1] ) &&
1003 "Table isn't big enough!");
1004 IndexedModeActions[(unsigned)VT.getSimpleVT()][1][IdxMode] = (uint8_t)Action;
1007 /// setConvertAction - Indicate that the specified conversion does or does
1008 /// not work with the with specified type and indicate what to do about it.
1009 void setConvertAction(MVT FromVT, MVT ToVT,
1010 LegalizeAction Action) {
1011 assert((unsigned)FromVT.getSimpleVT() < array_lengthof(ConvertActions) &&
1012 (unsigned)ToVT.getSimpleVT() < sizeof(ConvertActions[0])*4 &&
1013 "Table isn't big enough!");
1014 ConvertActions[FromVT.getSimpleVT()] &= ~(uint64_t(3UL) <<
1015 ToVT.getSimpleVT()*2);
1016 ConvertActions[FromVT.getSimpleVT()] |= (uint64_t)Action <<
1017 ToVT.getSimpleVT()*2;
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, LegalizeAction Action) {
1023 assert((unsigned)VT.getSimpleVT() < sizeof(CondCodeActions[0])*4 &&
1024 (unsigned)CC < array_lengthof(CondCodeActions) &&
1025 "Table isn't big enough!");
1026 CondCodeActions[(unsigned)CC] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
1027 CondCodeActions[(unsigned)CC] |= (uint64_t)Action << VT.getSimpleVT()*2;
1030 /// AddPromotedToType - If Opc/OrigVT is specified as being promoted, the
1031 /// promotion code defaults to trying a larger integer/fp until it can find
1032 /// one that works. If that default is insufficient, this method can be used
1033 /// by the target to override the default.
1034 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1035 PromoteToType[std::make_pair(Opc, OrigVT.getSimpleVT())] =
1036 DestVT.getSimpleVT();
1039 /// addLegalFPImmediate - Indicate that this target can instruction select
1040 /// the specified FP immediate natively.
1041 void addLegalFPImmediate(const APFloat& Imm) {
1042 LegalFPImmediates.push_back(Imm);
1045 /// setTargetDAGCombine - Targets should invoke this method for each target
1046 /// independent node that they want to provide a custom DAG combiner for by
1047 /// implementing the PerformDAGCombine virtual method.
1048 void setTargetDAGCombine(ISD::NodeType NT) {
1049 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1050 TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
1053 /// setJumpBufSize - Set the target's required jmp_buf buffer size (in
1054 /// bytes); default is 200
1055 void setJumpBufSize(unsigned Size) {
1059 /// setJumpBufAlignment - Set the target's required jmp_buf buffer
1060 /// alignment (in bytes); default is 0
1061 void setJumpBufAlignment(unsigned Align) {
1062 JumpBufAlignment = Align;
1065 /// setIfCvtBlockSizeLimit - Set the target's if-conversion block size
1066 /// limit (in number of instructions); default is 2.
1067 void setIfCvtBlockSizeLimit(unsigned Limit) {
1068 IfCvtBlockSizeLimit = Limit;
1071 /// setIfCvtDupBlockSizeLimit - Set the target's block size limit (in number
1072 /// of instructions) to be considered for code duplication during
1073 /// if-conversion; default is 2.
1074 void setIfCvtDupBlockSizeLimit(unsigned Limit) {
1075 IfCvtDupBlockSizeLimit = Limit;
1078 /// setPrefLoopAlignment - Set the target's preferred loop alignment. Default
1079 /// alignment is zero, it means the target does not care about loop alignment.
1080 void setPrefLoopAlignment(unsigned Align) {
1081 PrefLoopAlignment = Align;
1086 virtual const TargetSubtarget *getSubtarget() {
1087 assert(0 && "Not Implemented");
1088 return NULL; // this is here to silence compiler errors
1090 //===--------------------------------------------------------------------===//
1091 // Lowering methods - These methods must be implemented by targets so that
1092 // the SelectionDAGLowering code knows how to lower these.
1095 /// LowerArguments - This hook must be implemented to indicate how we should
1096 /// lower the arguments for the specified function, into the specified DAG.
1098 LowerArguments(Function &F, SelectionDAG &DAG,
1099 SmallVectorImpl<SDValue>& ArgValues, DebugLoc dl);
1101 /// LowerCallTo - This hook lowers an abstract call to a function into an
1102 /// actual call. This returns a pair of operands. The first element is the
1103 /// return value for the function (if RetTy is not VoidTy). The second
1104 /// element is the outgoing token chain.
1105 struct ArgListEntry {
1116 ArgListEntry() : isSExt(false), isZExt(false), isInReg(false),
1117 isSRet(false), isNest(false), isByVal(false), Alignment(0) { }
1119 typedef std::vector<ArgListEntry> ArgListTy;
1120 virtual std::pair<SDValue, SDValue>
1121 LowerCallTo(SDValue Chain, const Type *RetTy, bool RetSExt, bool RetZExt,
1122 bool isVarArg, bool isInreg, unsigned CallingConv,
1123 bool isTailCall, SDValue Callee, ArgListTy &Args,
1124 SelectionDAG &DAG, DebugLoc dl);
1126 /// EmitTargetCodeForMemcpy - Emit target-specific code that performs a
1127 /// memcpy. This can be used by targets to provide code sequences for cases
1128 /// that don't fit the target's parameters for simple loads/stores and can be
1129 /// more efficient than using a library call. This function can return a null
1130 /// SDValue if the target declines to use custom code and a different
1131 /// lowering strategy should be used.
1133 /// If AlwaysInline is true, the size is constant and the target should not
1134 /// emit any calls and is strongly encouraged to attempt to emit inline code
1135 /// even if it is beyond the usual threshold because this intrinsic is being
1136 /// expanded in a place where calls are not feasible (e.g. within the prologue
1137 /// for another call). If the target chooses to decline an AlwaysInline
1138 /// request here, legalize will resort to using simple loads and stores.
1140 EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
1142 SDValue Op1, SDValue Op2,
1143 SDValue Op3, unsigned Align,
1145 const Value *DstSV, uint64_t DstOff,
1146 const Value *SrcSV, uint64_t SrcOff) {
1150 /// EmitTargetCodeForMemmove - Emit target-specific code that performs a
1151 /// memmove. This can be used by targets to provide code sequences for cases
1152 /// that don't fit the target's parameters for simple loads/stores and can be
1153 /// more efficient than using a library call. This function can return a null
1154 /// SDValue if the target declines to use custom code and a different
1155 /// lowering strategy should be used.
1157 EmitTargetCodeForMemmove(SelectionDAG &DAG, DebugLoc dl,
1159 SDValue Op1, SDValue Op2,
1160 SDValue Op3, unsigned Align,
1161 const Value *DstSV, uint64_t DstOff,
1162 const Value *SrcSV, uint64_t SrcOff) {
1166 /// EmitTargetCodeForMemset - Emit target-specific code that performs a
1167 /// memset. This can be used by targets to provide code sequences for cases
1168 /// that don't fit the target's parameters for simple stores and can be more
1169 /// efficient than using a library call. This function can return a null
1170 /// SDValue if the target declines to use custom code and a different
1171 /// lowering strategy should be used.
1173 EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
1175 SDValue Op1, SDValue Op2,
1176 SDValue Op3, unsigned Align,
1177 const Value *DstSV, uint64_t DstOff) {
1181 /// LowerOperationWrapper - This callback is invoked by the type legalizer
1182 /// to legalize nodes with an illegal operand type but legal result types.
1183 /// It replaces the LowerOperation callback in the type Legalizer.
1184 /// The reason we can not do away with LowerOperation entirely is that
1185 /// LegalizeDAG isn't yet ready to use this callback.
1186 /// TODO: Consider merging with ReplaceNodeResults.
1188 /// The target places new result values for the node in Results (their number
1189 /// and types must exactly match those of the original return values of
1190 /// the node), or leaves Results empty, which indicates that the node is not
1191 /// to be custom lowered after all.
1192 /// The default implementation calls LowerOperation.
1193 virtual void LowerOperationWrapper(SDNode *N,
1194 SmallVectorImpl<SDValue> &Results,
1197 /// LowerOperation - This callback is invoked for operations that are
1198 /// unsupported by the target, which are registered to use 'custom' lowering,
1199 /// and whose defined values are all legal.
1200 /// If the target has no operations that require custom lowering, it need not
1201 /// implement this. The default implementation of this aborts.
1202 virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG);
1204 /// ReplaceNodeResults - This callback is invoked when a node result type is
1205 /// illegal for the target, and the operation was registered to use 'custom'
1206 /// lowering for that result type. The target places new result values for
1207 /// the node in Results (their number and types must exactly match those of
1208 /// the original return values of the node), or leaves Results empty, which
1209 /// indicates that the node is not to be custom lowered after all.
1211 /// If the target has no operations that require custom lowering, it need not
1212 /// implement this. The default implementation aborts.
1213 virtual void ReplaceNodeResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
1214 SelectionDAG &DAG) {
1215 assert(0 && "ReplaceNodeResults not implemented for this target!");
1218 /// IsEligibleForTailCallOptimization - Check whether the call is eligible for
1219 /// tail call optimization. Targets which want to do tail call optimization
1220 /// should override this function.
1221 virtual bool IsEligibleForTailCallOptimization(CallSDNode *Call,
1223 SelectionDAG &DAG) const {
1227 /// CheckTailCallReturnConstraints - Check whether CALL node immediatly
1228 /// preceeds the RET node and whether the return uses the result of the node
1229 /// or is a void return. This function can be used by the target to determine
1230 /// eligiblity of tail call optimization.
1231 static bool CheckTailCallReturnConstraints(CallSDNode *TheCall, SDValue Ret);
1233 /// GetPossiblePreceedingTailCall - Get preceeding TailCallNodeOpCode node if
1234 /// it exists. Skip a possible ISD::TokenFactor.
1235 static SDValue GetPossiblePreceedingTailCall(SDValue Chain,
1236 unsigned TailCallNodeOpCode) {
1237 if (Chain.getOpcode() == TailCallNodeOpCode) {
1239 } else if (Chain.getOpcode() == ISD::TokenFactor) {
1240 if (Chain.getNumOperands() &&
1241 Chain.getOperand(0).getOpcode() == TailCallNodeOpCode)
1242 return Chain.getOperand(0);
1247 /// getTargetNodeName() - This method returns the name of a target specific
1249 virtual const char *getTargetNodeName(unsigned Opcode) const;
1251 /// createFastISel - This method returns a target specific FastISel object,
1252 /// or null if the target does not support "fast" ISel.
1254 createFastISel(MachineFunction &,
1255 MachineModuleInfo *, DwarfWriter *,
1256 DenseMap<const Value *, unsigned> &,
1257 DenseMap<const BasicBlock *, MachineBasicBlock *> &,
1258 DenseMap<const AllocaInst *, int> &
1260 , SmallSet<Instruction*, 8> &CatchInfoLost
1266 //===--------------------------------------------------------------------===//
1267 // Inline Asm Support hooks
1270 enum ConstraintType {
1271 C_Register, // Constraint represents specific register(s).
1272 C_RegisterClass, // Constraint represents any of register(s) in class.
1273 C_Memory, // Memory constraint.
1274 C_Other, // Something else.
1275 C_Unknown // Unsupported constraint.
1278 /// AsmOperandInfo - This contains information for each constraint that we are
1280 struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
1281 /// ConstraintCode - This contains the actual string for the code, like "m".
1282 /// TargetLowering picks the 'best' code from ConstraintInfo::Codes that
1283 /// most closely matches the operand.
1284 std::string ConstraintCode;
1286 /// ConstraintType - Information about the constraint code, e.g. Register,
1287 /// RegisterClass, Memory, Other, Unknown.
1288 TargetLowering::ConstraintType ConstraintType;
1290 /// CallOperandval - If this is the result output operand or a
1291 /// clobber, this is null, otherwise it is the incoming operand to the
1292 /// CallInst. This gets modified as the asm is processed.
1293 Value *CallOperandVal;
1295 /// ConstraintVT - The ValueType for the operand value.
1298 /// isMatchingInputConstraint - Return true of this is an input operand that
1299 /// is a matching constraint like "4".
1300 bool isMatchingInputConstraint() const;
1302 /// getMatchedOperand - If this is an input matching constraint, this method
1303 /// returns the output operand it matches.
1304 unsigned getMatchedOperand() const;
1306 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
1307 : InlineAsm::ConstraintInfo(info),
1308 ConstraintType(TargetLowering::C_Unknown),
1309 CallOperandVal(0), ConstraintVT(MVT::Other) {
1313 /// ComputeConstraintToUse - Determines the constraint code and constraint
1314 /// type to use for the specific AsmOperandInfo, setting
1315 /// OpInfo.ConstraintCode and OpInfo.ConstraintType. If the actual operand
1316 /// being passed in is available, it can be passed in as Op, otherwise an
1317 /// empty SDValue can be passed. If hasMemory is true it means one of the asm
1318 /// constraint of the inline asm instruction being processed is 'm'.
1319 virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
1322 SelectionDAG *DAG = 0) const;
1324 /// getConstraintType - Given a constraint, return the type of constraint it
1325 /// is for this target.
1326 virtual ConstraintType getConstraintType(const std::string &Constraint) const;
1328 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
1329 /// return a list of registers that can be used to satisfy the constraint.
1330 /// This should only be used for C_RegisterClass constraints.
1331 virtual std::vector<unsigned>
1332 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1335 /// getRegForInlineAsmConstraint - Given a physical register constraint (e.g.
1336 /// {edx}), return the register number and the register class for the
1339 /// Given a register class constraint, like 'r', if this corresponds directly
1340 /// to an LLVM register class, return a register of 0 and the register class
1343 /// This should only be used for C_Register constraints. On error,
1344 /// this returns a register number of 0 and a null register class pointer..
1345 virtual std::pair<unsigned, const TargetRegisterClass*>
1346 getRegForInlineAsmConstraint(const std::string &Constraint,
1349 /// LowerXConstraint - try to replace an X constraint, which matches anything,
1350 /// with another that has more specific requirements based on the type of the
1351 /// corresponding operand. This returns null if there is no replacement to
1353 virtual const char *LowerXConstraint(MVT ConstraintVT) const;
1355 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
1356 /// vector. If it is invalid, don't add anything to Ops. If hasMemory is true
1357 /// it means one of the asm constraint of the inline asm instruction being
1358 /// processed is 'm'.
1359 virtual void LowerAsmOperandForConstraint(SDValue Op, char ConstraintLetter,
1361 std::vector<SDValue> &Ops,
1362 SelectionDAG &DAG) const;
1364 //===--------------------------------------------------------------------===//
1368 // EmitInstrWithCustomInserter - This method should be implemented by targets
1369 // that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1370 // instructions are special in various ways, which require special support to
1371 // insert. The specified MachineInstr is created but not inserted into any
1372 // basic blocks, and the scheduler passes ownership of it to this method.
1373 virtual MachineBasicBlock *EmitInstrWithCustomInserter(MachineInstr *MI,
1374 MachineBasicBlock *MBB) const;
1376 //===--------------------------------------------------------------------===//
1377 // Addressing mode description hooks (used by LSR etc).
1380 /// AddrMode - This represents an addressing mode of:
1381 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
1382 /// If BaseGV is null, there is no BaseGV.
1383 /// If BaseOffs is zero, there is no base offset.
1384 /// If HasBaseReg is false, there is no base register.
1385 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
1389 GlobalValue *BaseGV;
1393 AddrMode() : BaseGV(0), BaseOffs(0), HasBaseReg(false), Scale(0) {}
1396 /// isLegalAddressingMode - Return true if the addressing mode represented by
1397 /// AM is legal for this target, for a load/store of the specified type.
1398 /// The type may be VoidTy, in which case only return true if the addressing
1399 /// mode is legal for a load/store of any legal type.
1400 /// TODO: Handle pre/postinc as well.
1401 virtual bool isLegalAddressingMode(const AddrMode &AM, const Type *Ty) const;
1403 /// isTruncateFree - Return true if it's free to truncate a value of
1404 /// type Ty1 to type Ty2. e.g. On x86 it's free to truncate a i32 value in
1405 /// register EAX to i16 by referencing its sub-register AX.
1406 virtual bool isTruncateFree(const Type *Ty1, const Type *Ty2) const {
1410 virtual bool isTruncateFree(MVT VT1, MVT VT2) const {
1414 /// isZExtFree - Return true if any actual instruction that defines a
1415 /// value of type Ty1 implicit zero-extends the value to Ty2 in the result
1416 /// register. This does not necessarily include registers defined in
1417 /// unknown ways, such as incoming arguments, or copies from unknown
1418 /// virtual registers. Also, if isTruncateFree(Ty2, Ty1) is true, this
1419 /// does not necessarily apply to truncate instructions. e.g. on x86-64,
1420 /// all instructions that define 32-bit values implicit zero-extend the
1421 /// result out to 64 bits.
1422 virtual bool isZExtFree(const Type *Ty1, const Type *Ty2) const {
1426 virtual bool isZExtFree(MVT VT1, MVT VT2) const {
1430 /// isNarrowingProfitable - Return true if it's profitable to narrow
1431 /// operations of type VT1 to VT2. e.g. on x86, it's profitable to narrow
1432 /// from i32 to i8 but not from i32 to i16.
1433 virtual bool isNarrowingProfitable(MVT VT1, MVT VT2) const {
1437 //===--------------------------------------------------------------------===//
1438 // Div utility functions
1440 SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG,
1441 std::vector<SDNode*>* Created) const;
1442 SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG,
1443 std::vector<SDNode*>* Created) const;
1446 //===--------------------------------------------------------------------===//
1447 // Runtime Library hooks
1450 /// setLibcallName - Rename the default libcall routine name for the specified
1452 void setLibcallName(RTLIB::Libcall Call, const char *Name) {
1453 LibcallRoutineNames[Call] = Name;
1456 /// getLibcallName - Get the libcall routine name for the specified libcall.
1458 const char *getLibcallName(RTLIB::Libcall Call) const {
1459 return LibcallRoutineNames[Call];
1462 /// setCmpLibcallCC - Override the default CondCode to be used to test the
1463 /// result of the comparison libcall against zero.
1464 void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
1465 CmpLibcallCCs[Call] = CC;
1468 /// getCmpLibcallCC - Get the CondCode that's to be used to test the result of
1469 /// the comparison libcall against zero.
1470 ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
1471 return CmpLibcallCCs[Call];
1476 const TargetData *TD;
1478 /// PointerTy - The type to use for pointers, usually i32 or i64.
1482 /// IsLittleEndian - True if this is a little endian target.
1484 bool IsLittleEndian;
1486 /// UsesGlobalOffsetTable - True if this target uses a GOT for PIC codegen.
1488 bool UsesGlobalOffsetTable;
1490 /// SelectIsExpensive - Tells the code generator not to expand operations
1491 /// into sequences that use the select operations if possible.
1492 bool SelectIsExpensive;
1494 /// IntDivIsCheap - Tells the code generator not to expand integer divides by
1495 /// constants into a sequence of muls, adds, and shifts. This is a hack until
1496 /// a real cost model is in place. If we ever optimize for size, this will be
1497 /// set to true unconditionally.
1500 /// Pow2DivIsCheap - Tells the code generator that it shouldn't generate
1501 /// srl/add/sra for a signed divide by power of two, and let the target handle
1503 bool Pow2DivIsCheap;
1505 /// UseUnderscoreSetJmp - This target prefers to use _setjmp to implement
1506 /// llvm.setjmp. Defaults to false.
1507 bool UseUnderscoreSetJmp;
1509 /// UseUnderscoreLongJmp - This target prefers to use _longjmp to implement
1510 /// llvm.longjmp. Defaults to false.
1511 bool UseUnderscoreLongJmp;
1513 /// ShiftAmountTy - The type to use for shift amounts, usually i8 or whatever
1517 OutOfRangeShiftAmount ShiftAmtHandling;
1519 /// BooleanContents - Information about the contents of the high-bits in
1520 /// boolean values held in a type wider than i1. See getBooleanContents.
1521 BooleanContent BooleanContents;
1523 /// SchedPreferenceInfo - The target scheduling preference: shortest possible
1524 /// total cycles or lowest register usage.
1525 SchedPreference SchedPreferenceInfo;
1527 /// JumpBufSize - The size, in bytes, of the target's jmp_buf buffers
1528 unsigned JumpBufSize;
1530 /// JumpBufAlignment - The alignment, in bytes, of the target's jmp_buf
1532 unsigned JumpBufAlignment;
1534 /// IfCvtBlockSizeLimit - The maximum allowed size for a block to be
1536 unsigned IfCvtBlockSizeLimit;
1538 /// IfCvtDupBlockSizeLimit - The maximum allowed size for a block to be
1539 /// duplicated during if-conversion.
1540 unsigned IfCvtDupBlockSizeLimit;
1542 /// PrefLoopAlignment - The perferred loop alignment.
1544 unsigned PrefLoopAlignment;
1546 /// StackPointerRegisterToSaveRestore - If set to a physical register, this
1547 /// specifies the register that llvm.savestack/llvm.restorestack should save
1549 unsigned StackPointerRegisterToSaveRestore;
1551 /// ExceptionPointerRegister - If set to a physical register, this specifies
1552 /// the register that receives the exception address on entry to a landing
1554 unsigned ExceptionPointerRegister;
1556 /// ExceptionSelectorRegister - If set to a physical register, this specifies
1557 /// the register that receives the exception typeid on entry to a landing
1559 unsigned ExceptionSelectorRegister;
1561 /// RegClassForVT - This indicates the default register class to use for
1562 /// each ValueType the target supports natively.
1563 TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
1564 unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
1565 MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
1567 /// TransformToType - For any value types we are promoting or expanding, this
1568 /// contains the value type that we are changing to. For Expanded types, this
1569 /// contains one step of the expand (e.g. i64 -> i32), even if there are
1570 /// multiple steps required (e.g. i64 -> i16). For types natively supported
1571 /// by the system, this holds the same type (e.g. i32 -> i32).
1572 MVT TransformToType[MVT::LAST_VALUETYPE];
1574 /// OpActions - For each operation and each value type, keep a LegalizeAction
1575 /// that indicates how instruction selection should deal with the operation.
1576 /// Most operations are Legal (aka, supported natively by the target), but
1577 /// operations that are not should be described. Note that operations on
1578 /// non-legal value types are not described here.
1579 /// This array is accessed using VT.getSimpleVT(), so it is subject to
1580 /// the MVT::MAX_ALLOWED_VALUETYPE * 2 bits.
1581 uint64_t OpActions[MVT::MAX_ALLOWED_VALUETYPE/(sizeof(uint64_t)*4)][ISD::BUILTIN_OP_END];
1583 /// LoadExtActions - For each load of load extension type and each value type,
1584 /// keep a LegalizeAction that indicates how instruction selection should deal
1586 uint64_t LoadExtActions[ISD::LAST_LOADEXT_TYPE];
1588 /// TruncStoreActions - For each truncating store, keep a LegalizeAction that
1589 /// indicates how instruction selection should deal with the store.
1590 uint64_t TruncStoreActions[MVT::LAST_VALUETYPE];
1592 /// IndexedModeActions - For each indexed mode and each value type,
1593 /// keep a pair of LegalizeAction that indicates how instruction
1594 /// selection should deal with the load / store. The first
1595 /// dimension is now the value_type for the reference. The second
1596 /// dimension is the load [0] vs. store[1]. The third dimension
1597 /// represents the various modes for load store.
1598 uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][2][ISD::LAST_INDEXED_MODE];
1600 /// ConvertActions - For each conversion from source type to destination type,
1601 /// keep a LegalizeAction that indicates how instruction selection should
1602 /// deal with the conversion.
1603 /// Currently, this is used only for floating->floating conversions
1604 /// (FP_EXTEND and FP_ROUND).
1605 uint64_t ConvertActions[MVT::LAST_VALUETYPE];
1607 /// CondCodeActions - For each condition code (ISD::CondCode) keep a
1608 /// LegalizeAction that indicates how instruction selection should
1609 /// deal with the condition code.
1610 uint64_t CondCodeActions[ISD::SETCC_INVALID];
1612 ValueTypeActionImpl ValueTypeActions;
1614 std::vector<APFloat> LegalFPImmediates;
1616 std::vector<std::pair<MVT, TargetRegisterClass*> > AvailableRegClasses;
1618 /// TargetDAGCombineArray - Targets can specify ISD nodes that they would
1619 /// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(),
1620 /// which sets a bit in this array.
1622 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
1624 /// PromoteToType - For operations that must be promoted to a specific type,
1625 /// this holds the destination type. This map should be sparse, so don't hold
1628 /// Targets add entries to this map with AddPromotedToType(..), clients access
1629 /// this with getTypeToPromoteTo(..).
1630 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
1633 /// LibcallRoutineNames - Stores the name each libcall.
1635 const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
1637 /// CmpLibcallCCs - The ISD::CondCode that should be used to test the result
1638 /// of each of the comparison libcall against zero.
1639 ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
1642 /// When lowering \@llvm.memset this field specifies the maximum number of
1643 /// store operations that may be substituted for the call to memset. Targets
1644 /// must set this value based on the cost threshold for that target. Targets
1645 /// should assume that the memset will be done using as many of the largest
1646 /// store operations first, followed by smaller ones, if necessary, per
1647 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
1648 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
1649 /// store. This only applies to setting a constant array of a constant size.
1650 /// @brief Specify maximum number of store instructions per memset call.
1651 unsigned maxStoresPerMemset;
1653 /// When lowering \@llvm.memcpy this field specifies the maximum number of
1654 /// store operations that may be substituted for a call to memcpy. Targets
1655 /// must set this value based on the cost threshold for that target. Targets
1656 /// should assume that the memcpy will be done using as many of the largest
1657 /// store operations first, followed by smaller ones, if necessary, per
1658 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
1659 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
1660 /// and one 1-byte store. This only applies to copying a constant array of
1662 /// @brief Specify maximum bytes of store instructions per memcpy call.
1663 unsigned maxStoresPerMemcpy;
1665 /// When lowering \@llvm.memmove this field specifies the maximum number of
1666 /// store instructions that may be substituted for a call to memmove. Targets
1667 /// must set this value based on the cost threshold for that target. Targets
1668 /// should assume that the memmove will be done using as many of the largest
1669 /// store operations first, followed by smaller ones, if necessary, per
1670 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
1671 /// with 8-bit alignment would result in nine 1-byte stores. This only
1672 /// applies to copying a constant array of constant size.
1673 /// @brief Specify maximum bytes of store instructions per memmove call.
1674 unsigned maxStoresPerMemmove;
1676 /// This field specifies whether the target machine permits unaligned memory
1677 /// accesses. This is used, for example, to determine the size of store
1678 /// operations when copying small arrays and other similar tasks.
1679 /// @brief Indicate whether the target permits unaligned memory accesses.
1680 bool allowUnalignedMemoryAccesses;
1682 /// This field specifies whether the target can benefit from code placement
1684 bool benefitFromCodePlacementOpt;
1686 } // end llvm namespace