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/DenseMap.h"
29 #include "llvm/Support/CallSite.h"
30 #include "llvm/CodeGen/SelectionDAGNodes.h"
31 #include "llvm/CodeGen/RuntimeLibcalls.h"
32 #include "llvm/Support/DebugLoc.h"
33 #include "llvm/Target/TargetCallingConv.h"
34 #include "llvm/Target/TargetMachine.h"
43 class FunctionLoweringInfo;
44 class ImmutableCallSite;
46 class MachineBasicBlock;
47 class MachineFunction;
49 class MachineJumpTableInfo;
52 template<typename T> class SmallVectorImpl;
54 class TargetRegisterClass;
55 class TargetLibraryInfo;
56 class TargetLoweringObjectFile;
61 None, // No preference
62 Source, // Follow source order.
63 RegPressure, // Scheduling for lowest register pressure.
64 Hybrid, // Scheduling for both latency and register pressure.
65 ILP, // Scheduling for ILP in low register pressure mode.
66 VLIW // Scheduling for VLIW targets.
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 {
80 TargetLowering(const TargetLowering&); // DO NOT IMPLEMENT
81 void operator=(const TargetLowering&); // DO NOT IMPLEMENT
83 /// LegalizeAction - This enum indicates whether operations are valid for a
84 /// target, and if not, what action should be used to make them valid.
86 Legal, // The target natively supports this operation.
87 Promote, // This operation should be executed in a larger type.
88 Expand, // Try to expand this to other ops, otherwise use a libcall.
89 Custom // Use the LowerOperation hook to implement custom lowering.
92 /// LegalizeTypeAction - This enum indicates whether a types are legal for a
93 /// target, and if not, what action should be used to make them valid.
94 enum LegalizeTypeAction {
95 TypeLegal, // The target natively supports this type.
96 TypePromoteInteger, // Replace this integer with a larger one.
97 TypeExpandInteger, // Split this integer into two of half the size.
98 TypeSoftenFloat, // Convert this float to a same size integer type.
99 TypeExpandFloat, // Split this float into two of half the size.
100 TypeScalarizeVector, // Replace this one-element vector with its element.
101 TypeSplitVector, // Split this vector into two of half the size.
102 TypeWidenVector // This vector should be widened into a larger vector.
105 enum BooleanContent { // How the target represents true/false values.
106 UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
107 ZeroOrOneBooleanContent, // All bits zero except for bit 0.
108 ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
111 enum SelectSupportKind {
112 ScalarValSelect, // The target supports scalar selects (ex: cmov).
113 ScalarCondVectorVal, // The target supports selects with a scalar condition
114 // and vector values (ex: cmov).
115 VectorMaskSelect // The target supports vector selects with a vector
116 // mask (ex: x86 blends).
119 static ISD::NodeType getExtendForContent(BooleanContent Content) {
121 case UndefinedBooleanContent:
122 // Extend by adding rubbish bits.
123 return ISD::ANY_EXTEND;
124 case ZeroOrOneBooleanContent:
125 // Extend by adding zero bits.
126 return ISD::ZERO_EXTEND;
127 case ZeroOrNegativeOneBooleanContent:
128 // Extend by copying the sign bit.
129 return ISD::SIGN_EXTEND;
131 llvm_unreachable("Invalid content kind");
134 /// NOTE: The constructor takes ownership of TLOF.
135 explicit TargetLowering(const TargetMachine &TM,
136 const TargetLoweringObjectFile *TLOF);
137 virtual ~TargetLowering();
139 const TargetMachine &getTargetMachine() const { return TM; }
140 const TargetData *getTargetData() const { return TD; }
141 const TargetLoweringObjectFile &getObjFileLowering() const { return TLOF; }
143 bool isBigEndian() const { return !IsLittleEndian; }
144 bool isLittleEndian() const { return IsLittleEndian; }
145 MVT getPointerTy() const { return PointerTy; }
146 virtual MVT getShiftAmountTy(EVT LHSTy) const;
148 /// isSelectExpensive - Return true if the select operation is expensive for
150 bool isSelectExpensive() const { return SelectIsExpensive; }
152 virtual bool isSelectSupported(SelectSupportKind kind) const { return true; }
154 /// isIntDivCheap() - Return true if integer divide is usually cheaper than
155 /// a sequence of several shifts, adds, and multiplies for this target.
156 bool isIntDivCheap() const { return IntDivIsCheap; }
158 /// isSlowDivBypassed - Returns true if target has indicated at least one
159 /// type should be bypassed.
160 bool isSlowDivBypassed() const { return !BypassSlowDivTypes.empty(); }
162 /// getBypassSlowDivTypes - Returns map of slow types for division or
163 /// remainder with corresponding fast types
164 const DenseMap<Type *, Type *> &getBypassSlowDivTypes() const {
165 return BypassSlowDivTypes;
168 /// isPow2DivCheap() - Return true if pow2 div is cheaper than a chain of
170 bool isPow2DivCheap() const { return Pow2DivIsCheap; }
172 /// isJumpExpensive() - Return true if Flow Control is an expensive operation
173 /// that should be avoided.
174 bool isJumpExpensive() const { return JumpIsExpensive; }
176 /// isPredictableSelectExpensive - Return true if selects are only cheaper
177 /// than branches if the branch is unlikely to be predicted right.
178 bool isPredictableSelectExpensive() const {
179 return predictableSelectIsExpensive;
182 /// getSetCCResultType - Return the ValueType of the result of SETCC
183 /// operations. Also used to obtain the target's preferred type for
184 /// the condition operand of SELECT and BRCOND nodes. In the case of
185 /// BRCOND the argument passed is MVT::Other since there are no other
186 /// operands to get a type hint from.
187 virtual EVT getSetCCResultType(EVT VT) const;
189 /// getCmpLibcallReturnType - Return the ValueType for comparison
190 /// libcalls. Comparions libcalls include floating point comparion calls,
191 /// and Ordered/Unordered check calls on floating point numbers.
193 MVT::SimpleValueType getCmpLibcallReturnType() const;
195 /// getBooleanContents - For targets without i1 registers, this gives the
196 /// nature of the high-bits of boolean values held in types wider than i1.
197 /// "Boolean values" are special true/false values produced by nodes like
198 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
199 /// Not to be confused with general values promoted from i1.
200 /// Some cpus distinguish between vectors of boolean and scalars; the isVec
201 /// parameter selects between the two kinds. For example on X86 a scalar
202 /// boolean should be zero extended from i1, while the elements of a vector
203 /// of booleans should be sign extended from i1.
204 BooleanContent getBooleanContents(bool isVec) const {
205 return isVec ? BooleanVectorContents : BooleanContents;
208 /// getSchedulingPreference - Return target scheduling preference.
209 Sched::Preference getSchedulingPreference() const {
210 return SchedPreferenceInfo;
213 /// getSchedulingPreference - Some scheduler, e.g. hybrid, can switch to
214 /// different scheduling heuristics for different nodes. This function returns
215 /// the preference (or none) for the given node.
216 virtual Sched::Preference getSchedulingPreference(SDNode *) const {
220 /// getRegClassFor - Return the register class that should be used for the
221 /// specified value type.
222 virtual const TargetRegisterClass *getRegClassFor(EVT VT) const {
223 assert(VT.isSimple() && "getRegClassFor called on illegal type!");
224 const TargetRegisterClass *RC = RegClassForVT[VT.getSimpleVT().SimpleTy];
225 assert(RC && "This value type is not natively supported!");
229 /// getRepRegClassFor - Return the 'representative' register class for the
230 /// specified value type. The 'representative' register class is the largest
231 /// legal super-reg register class for the register class of the value type.
232 /// For example, on i386 the rep register class for i8, i16, and i32 are GR32;
233 /// while the rep register class is GR64 on x86_64.
234 virtual const TargetRegisterClass *getRepRegClassFor(EVT VT) const {
235 assert(VT.isSimple() && "getRepRegClassFor called on illegal type!");
236 const TargetRegisterClass *RC = RepRegClassForVT[VT.getSimpleVT().SimpleTy];
240 /// getRepRegClassCostFor - Return the cost of the 'representative' register
241 /// class for the specified value type.
242 virtual uint8_t getRepRegClassCostFor(EVT VT) const {
243 assert(VT.isSimple() && "getRepRegClassCostFor called on illegal type!");
244 return RepRegClassCostForVT[VT.getSimpleVT().SimpleTy];
247 /// isTypeLegal - Return true if the target has native support for the
248 /// specified value type. This means that it has a register that directly
249 /// holds it without promotions or expansions.
250 bool isTypeLegal(EVT VT) const {
251 assert(!VT.isSimple() ||
252 (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
253 return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != 0;
256 class ValueTypeActionImpl {
257 /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
258 /// that indicates how instruction selection should deal with the type.
259 uint8_t ValueTypeActions[MVT::LAST_VALUETYPE];
262 ValueTypeActionImpl() {
263 std::fill(ValueTypeActions, array_endof(ValueTypeActions), 0);
266 LegalizeTypeAction getTypeAction(MVT VT) const {
267 return (LegalizeTypeAction)ValueTypeActions[VT.SimpleTy];
270 void setTypeAction(EVT VT, LegalizeTypeAction Action) {
271 unsigned I = VT.getSimpleVT().SimpleTy;
272 ValueTypeActions[I] = Action;
276 const ValueTypeActionImpl &getValueTypeActions() const {
277 return ValueTypeActions;
280 /// getTypeAction - Return how we should legalize values of this type, either
281 /// it is already legal (return 'Legal') or we need to promote it to a larger
282 /// type (return 'Promote'), or we need to expand it into multiple registers
283 /// of smaller integer type (return 'Expand'). 'Custom' is not an option.
284 LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const {
285 return getTypeConversion(Context, VT).first;
287 LegalizeTypeAction getTypeAction(MVT VT) const {
288 return ValueTypeActions.getTypeAction(VT);
291 /// getTypeToTransformTo - For types supported by the target, this is an
292 /// identity function. For types that must be promoted to larger types, this
293 /// returns the larger type to promote to. For integer types that are larger
294 /// than the largest integer register, this contains one step in the expansion
295 /// to get to the smaller register. For illegal floating point types, this
296 /// returns the integer type to transform to.
297 EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
298 return getTypeConversion(Context, VT).second;
301 /// getTypeToExpandTo - For types supported by the target, this is an
302 /// identity function. For types that must be expanded (i.e. integer types
303 /// that are larger than the largest integer register or illegal floating
304 /// point types), this returns the largest legal type it will be expanded to.
305 EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
306 assert(!VT.isVector());
308 switch (getTypeAction(Context, VT)) {
311 case TypeExpandInteger:
312 VT = getTypeToTransformTo(Context, VT);
315 llvm_unreachable("Type is not legal nor is it to be expanded!");
320 /// getVectorTypeBreakdown - Vector types are broken down into some number of
321 /// legal first class types. For example, EVT::v8f32 maps to 2 EVT::v4f32
322 /// with Altivec or SSE1, or 8 promoted EVT::f64 values with the X86 FP stack.
323 /// Similarly, EVT::v2i64 turns into 4 EVT::i32 values with both PPC and X86.
325 /// This method returns the number of registers needed, and the VT for each
326 /// register. It also returns the VT and quantity of the intermediate values
327 /// before they are promoted/expanded.
329 unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
331 unsigned &NumIntermediates,
332 EVT &RegisterVT) const;
334 /// getTgtMemIntrinsic: Given an intrinsic, checks if on the target the
335 /// intrinsic will need to map to a MemIntrinsicNode (touches memory). If
336 /// this is the case, it returns true and store the intrinsic
337 /// information into the IntrinsicInfo that was passed to the function.
338 struct IntrinsicInfo {
339 unsigned opc; // target opcode
340 EVT memVT; // memory VT
341 const Value* ptrVal; // value representing memory location
342 int offset; // offset off of ptrVal
343 unsigned align; // alignment
344 bool vol; // is volatile?
345 bool readMem; // reads memory?
346 bool writeMem; // writes memory?
349 virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
350 unsigned /*Intrinsic*/) const {
354 /// isFPImmLegal - Returns true if the target can instruction select the
355 /// specified FP immediate natively. If false, the legalizer will materialize
356 /// the FP immediate as a load from a constant pool.
357 virtual bool isFPImmLegal(const APFloat &/*Imm*/, EVT /*VT*/) const {
361 /// isShuffleMaskLegal - Targets can use this to indicate that they only
362 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
363 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
364 /// are assumed to be legal.
365 virtual bool isShuffleMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
370 /// canOpTrap - Returns true if the operation can trap for the value type.
371 /// VT must be a legal type. By default, we optimistically assume most
372 /// operations don't trap except for divide and remainder.
373 virtual bool canOpTrap(unsigned Op, EVT VT) const;
375 /// isVectorClearMaskLegal - Similar to isShuffleMaskLegal. This is
376 /// used by Targets can use this to indicate if there is a suitable
377 /// VECTOR_SHUFFLE that can be used to replace a VAND with a constant
379 virtual bool isVectorClearMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
384 /// getOperationAction - Return how this operation should be treated: either
385 /// it is legal, needs to be promoted to a larger size, needs to be
386 /// expanded to some other code sequence, or the target has a custom expander
388 LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
389 if (VT.isExtended()) return Expand;
390 // If a target-specific SDNode requires legalization, require the target
391 // to provide custom legalization for it.
392 if (Op > array_lengthof(OpActions[0])) return Custom;
393 unsigned I = (unsigned) VT.getSimpleVT().SimpleTy;
394 return (LegalizeAction)OpActions[I][Op];
397 /// isOperationLegalOrCustom - Return true if the specified operation is
398 /// legal on this target or can be made legal with custom lowering. This
399 /// is used to help guide high-level lowering decisions.
400 bool isOperationLegalOrCustom(unsigned Op, EVT VT) const {
401 return (VT == MVT::Other || isTypeLegal(VT)) &&
402 (getOperationAction(Op, VT) == Legal ||
403 getOperationAction(Op, VT) == Custom);
406 /// isOperationLegal - Return true if the specified operation is legal on this
408 bool isOperationLegal(unsigned Op, EVT VT) const {
409 return (VT == MVT::Other || isTypeLegal(VT)) &&
410 getOperationAction(Op, VT) == Legal;
413 /// getLoadExtAction - Return how this load with extension should be treated:
414 /// either it is legal, needs to be promoted to a larger size, needs to be
415 /// expanded to some other code sequence, or the target has a custom expander
417 LegalizeAction getLoadExtAction(unsigned ExtType, EVT VT) const {
418 assert(ExtType < ISD::LAST_LOADEXT_TYPE &&
419 VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
420 "Table isn't big enough!");
421 return (LegalizeAction)LoadExtActions[VT.getSimpleVT().SimpleTy][ExtType];
424 /// isLoadExtLegal - Return true if the specified load with extension is legal
426 bool isLoadExtLegal(unsigned ExtType, EVT VT) const {
427 return VT.isSimple() && getLoadExtAction(ExtType, VT) == Legal;
430 /// getTruncStoreAction - Return how this store with truncation should be
431 /// treated: either it is legal, needs to be promoted to a larger size, needs
432 /// to be expanded to some other code sequence, or the target has a custom
434 LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT) const {
435 assert(ValVT.getSimpleVT() < MVT::LAST_VALUETYPE &&
436 MemVT.getSimpleVT() < MVT::LAST_VALUETYPE &&
437 "Table isn't big enough!");
438 return (LegalizeAction)TruncStoreActions[ValVT.getSimpleVT().SimpleTy]
439 [MemVT.getSimpleVT().SimpleTy];
442 /// isTruncStoreLegal - Return true if the specified store with truncation is
443 /// legal on this target.
444 bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
445 return isTypeLegal(ValVT) && MemVT.isSimple() &&
446 getTruncStoreAction(ValVT, MemVT) == Legal;
449 /// getIndexedLoadAction - Return how the indexed load should be treated:
450 /// either it is legal, needs to be promoted to a larger size, needs to be
451 /// expanded to some other code sequence, or the target has a custom expander
454 getIndexedLoadAction(unsigned IdxMode, EVT VT) const {
455 assert(IdxMode < ISD::LAST_INDEXED_MODE &&
456 VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
457 "Table isn't big enough!");
458 unsigned Ty = (unsigned)VT.getSimpleVT().SimpleTy;
459 return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] & 0xf0) >> 4);
462 /// isIndexedLoadLegal - Return true if the specified indexed load is legal
464 bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
465 return VT.isSimple() &&
466 (getIndexedLoadAction(IdxMode, VT) == Legal ||
467 getIndexedLoadAction(IdxMode, VT) == Custom);
470 /// getIndexedStoreAction - Return how the indexed store should be treated:
471 /// either it is legal, needs to be promoted to a larger size, needs to be
472 /// expanded to some other code sequence, or the target has a custom expander
475 getIndexedStoreAction(unsigned IdxMode, EVT VT) const {
476 assert(IdxMode < ISD::LAST_INDEXED_MODE &&
477 VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
478 "Table isn't big enough!");
479 unsigned Ty = (unsigned)VT.getSimpleVT().SimpleTy;
480 return (LegalizeAction)(IndexedModeActions[Ty][IdxMode] & 0x0f);
483 /// isIndexedStoreLegal - Return true if the specified indexed load is legal
485 bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
486 return VT.isSimple() &&
487 (getIndexedStoreAction(IdxMode, VT) == Legal ||
488 getIndexedStoreAction(IdxMode, VT) == Custom);
491 /// getCondCodeAction - Return how the condition code should be treated:
492 /// either it is legal, needs to be expanded to some other code sequence,
493 /// or the target has a custom expander for it.
495 getCondCodeAction(ISD::CondCode CC, EVT VT) const {
496 assert((unsigned)CC < array_lengthof(CondCodeActions) &&
497 (unsigned)VT.getSimpleVT().SimpleTy < sizeof(CondCodeActions[0])*4 &&
498 "Table isn't big enough!");
499 /// The lower 5 bits of the SimpleTy index into Nth 2bit set from the 64bit
500 /// value and the upper 27 bits index into the second dimension of the
501 /// array to select what 64bit value to use.
502 LegalizeAction Action = (LegalizeAction)
503 ((CondCodeActions[CC][VT.getSimpleVT().SimpleTy >> 5]
504 >> (2*(VT.getSimpleVT().SimpleTy & 0x1F))) & 3);
505 assert(Action != Promote && "Can't promote condition code!");
509 /// isCondCodeLegal - Return true if the specified condition code is legal
511 bool isCondCodeLegal(ISD::CondCode CC, EVT VT) const {
512 return getCondCodeAction(CC, VT) == Legal ||
513 getCondCodeAction(CC, VT) == Custom;
517 /// getTypeToPromoteTo - If the action for this operation is to promote, this
518 /// method returns the ValueType to promote to.
519 EVT getTypeToPromoteTo(unsigned Op, EVT VT) const {
520 assert(getOperationAction(Op, VT) == Promote &&
521 "This operation isn't promoted!");
523 // See if this has an explicit type specified.
524 std::map<std::pair<unsigned, MVT::SimpleValueType>,
525 MVT::SimpleValueType>::const_iterator PTTI =
526 PromoteToType.find(std::make_pair(Op, VT.getSimpleVT().SimpleTy));
527 if (PTTI != PromoteToType.end()) return PTTI->second;
529 assert((VT.isInteger() || VT.isFloatingPoint()) &&
530 "Cannot autopromote this type, add it with AddPromotedToType.");
534 NVT = (MVT::SimpleValueType)(NVT.getSimpleVT().SimpleTy+1);
535 assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
536 "Didn't find type to promote to!");
537 } while (!isTypeLegal(NVT) ||
538 getOperationAction(Op, NVT) == Promote);
542 /// getValueType - Return the EVT corresponding to this LLVM type.
543 /// This is fixed by the LLVM operations except for the pointer size. If
544 /// AllowUnknown is true, this will return MVT::Other for types with no EVT
545 /// counterpart (e.g. structs), otherwise it will assert.
546 EVT getValueType(Type *Ty, bool AllowUnknown = false) const {
547 // Lower scalar pointers to native pointer types.
548 if (Ty->isPointerTy()) return PointerTy;
550 if (Ty->isVectorTy()) {
551 VectorType *VTy = cast<VectorType>(Ty);
552 Type *Elm = VTy->getElementType();
553 // Lower vectors of pointers to native pointer types.
554 if (Elm->isPointerTy())
555 Elm = EVT(PointerTy).getTypeForEVT(Ty->getContext());
556 return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
557 VTy->getNumElements());
559 return EVT::getEVT(Ty, AllowUnknown);
563 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
564 /// function arguments in the caller parameter area. This is the actual
565 /// alignment, not its logarithm.
566 virtual unsigned getByValTypeAlignment(Type *Ty) const;
568 /// getRegisterType - Return the type of registers that this ValueType will
569 /// eventually require.
570 EVT getRegisterType(MVT VT) const {
571 assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
572 return RegisterTypeForVT[VT.SimpleTy];
575 /// getRegisterType - Return the type of registers that this ValueType will
576 /// eventually require.
577 EVT getRegisterType(LLVMContext &Context, EVT VT) const {
579 assert((unsigned)VT.getSimpleVT().SimpleTy <
580 array_lengthof(RegisterTypeForVT));
581 return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
585 unsigned NumIntermediates;
586 (void)getVectorTypeBreakdown(Context, VT, VT1,
587 NumIntermediates, RegisterVT);
590 if (VT.isInteger()) {
591 return getRegisterType(Context, getTypeToTransformTo(Context, VT));
593 llvm_unreachable("Unsupported extended type!");
596 /// getNumRegisters - Return the number of registers that this ValueType will
597 /// eventually require. This is one for any types promoted to live in larger
598 /// registers, but may be more than one for types (like i64) that are split
599 /// into pieces. For types like i140, which are first promoted then expanded,
600 /// it is the number of registers needed to hold all the bits of the original
601 /// type. For an i140 on a 32 bit machine this means 5 registers.
602 unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
604 assert((unsigned)VT.getSimpleVT().SimpleTy <
605 array_lengthof(NumRegistersForVT));
606 return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
610 unsigned NumIntermediates;
611 return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
613 if (VT.isInteger()) {
614 unsigned BitWidth = VT.getSizeInBits();
615 unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
616 return (BitWidth + RegWidth - 1) / RegWidth;
618 llvm_unreachable("Unsupported extended type!");
621 /// ShouldShrinkFPConstant - If true, then instruction selection should
622 /// seek to shrink the FP constant of the specified type to a smaller type
623 /// in order to save space and / or reduce runtime.
624 virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
626 /// hasTargetDAGCombine - If true, the target has custom DAG combine
627 /// transformations that it can perform for the specified node.
628 bool hasTargetDAGCombine(ISD::NodeType NT) const {
629 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
630 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
633 /// This function returns the maximum number of store operations permitted
634 /// to replace a call to llvm.memset. The value is set by the target at the
635 /// performance threshold for such a replacement. If OptSize is true,
636 /// return the limit for functions that have OptSize attribute.
637 /// @brief Get maximum # of store operations permitted for llvm.memset
638 unsigned getMaxStoresPerMemset(bool OptSize) const {
639 return OptSize ? maxStoresPerMemsetOptSize : maxStoresPerMemset;
642 /// This function returns the maximum number of store operations permitted
643 /// to replace a call to llvm.memcpy. The value is set by the target at the
644 /// performance threshold for such a replacement. If OptSize is true,
645 /// return the limit for functions that have OptSize attribute.
646 /// @brief Get maximum # of store operations permitted for llvm.memcpy
647 unsigned getMaxStoresPerMemcpy(bool OptSize) const {
648 return OptSize ? maxStoresPerMemcpyOptSize : maxStoresPerMemcpy;
651 /// This function returns the maximum number of store operations permitted
652 /// to replace a call to llvm.memmove. The value is set by the target at the
653 /// performance threshold for such a replacement. If OptSize is true,
654 /// return the limit for functions that have OptSize attribute.
655 /// @brief Get maximum # of store operations permitted for llvm.memmove
656 unsigned getMaxStoresPerMemmove(bool OptSize) const {
657 return OptSize ? maxStoresPerMemmoveOptSize : maxStoresPerMemmove;
660 /// This function returns true if the target allows unaligned memory accesses.
661 /// of the specified type. This is used, for example, in situations where an
662 /// array copy/move/set is converted to a sequence of store operations. It's
663 /// use helps to ensure that such replacements don't generate code that causes
664 /// an alignment error (trap) on the target machine.
665 /// @brief Determine if the target supports unaligned memory accesses.
666 virtual bool allowsUnalignedMemoryAccesses(EVT) const {
670 /// This function returns true if the target would benefit from code placement
672 /// @brief Determine if the target should perform code placement optimization.
673 bool shouldOptimizeCodePlacement() const {
674 return benefitFromCodePlacementOpt;
677 /// getOptimalMemOpType - Returns the target specific optimal type for load
678 /// and store operations as a result of memset, memcpy, and memmove
679 /// lowering. If DstAlign is zero that means it's safe to destination
680 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
681 /// means there isn't a need to check it against alignment requirement,
682 /// probably because the source does not need to be loaded. If
683 /// 'IsZeroVal' is true, that means it's safe to return a
684 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
685 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
686 /// constant so it does not need to be loaded.
687 /// It returns EVT::Other if the type should be determined using generic
688 /// target-independent logic.
689 virtual EVT getOptimalMemOpType(uint64_t /*Size*/,
690 unsigned /*DstAlign*/, unsigned /*SrcAlign*/,
692 bool /*MemcpyStrSrc*/,
693 MachineFunction &/*MF*/) const {
697 /// usesUnderscoreSetJmp - Determine if we should use _setjmp or setjmp
698 /// to implement llvm.setjmp.
699 bool usesUnderscoreSetJmp() const {
700 return UseUnderscoreSetJmp;
703 /// usesUnderscoreLongJmp - Determine if we should use _longjmp or longjmp
704 /// to implement llvm.longjmp.
705 bool usesUnderscoreLongJmp() const {
706 return UseUnderscoreLongJmp;
709 /// supportJumpTables - return whether the target can generate code for
711 bool supportJumpTables() const {
712 return SupportJumpTables;
715 /// getStackPointerRegisterToSaveRestore - If a physical register, this
716 /// specifies the register that llvm.savestack/llvm.restorestack should save
718 unsigned getStackPointerRegisterToSaveRestore() const {
719 return StackPointerRegisterToSaveRestore;
722 /// getExceptionPointerRegister - If a physical register, this returns
723 /// the register that receives the exception address on entry to a landing
725 unsigned getExceptionPointerRegister() const {
726 return ExceptionPointerRegister;
729 /// getExceptionSelectorRegister - If a physical register, this returns
730 /// the register that receives the exception typeid on entry to a landing
732 unsigned getExceptionSelectorRegister() const {
733 return ExceptionSelectorRegister;
736 /// getJumpBufSize - returns the target's jmp_buf size in bytes (if never
737 /// set, the default is 200)
738 unsigned getJumpBufSize() const {
742 /// getJumpBufAlignment - returns the target's jmp_buf alignment in bytes
743 /// (if never set, the default is 0)
744 unsigned getJumpBufAlignment() const {
745 return JumpBufAlignment;
748 /// getMinStackArgumentAlignment - return the minimum stack alignment of an
750 unsigned getMinStackArgumentAlignment() const {
751 return MinStackArgumentAlignment;
754 /// getMinFunctionAlignment - return the minimum function alignment.
756 unsigned getMinFunctionAlignment() const {
757 return MinFunctionAlignment;
760 /// getPrefFunctionAlignment - return the preferred function alignment.
762 unsigned getPrefFunctionAlignment() const {
763 return PrefFunctionAlignment;
766 /// getPrefLoopAlignment - return the preferred loop alignment.
768 unsigned getPrefLoopAlignment() const {
769 return PrefLoopAlignment;
772 /// getShouldFoldAtomicFences - return whether the combiner should fold
773 /// fence MEMBARRIER instructions into the atomic intrinsic instructions.
775 bool getShouldFoldAtomicFences() const {
776 return ShouldFoldAtomicFences;
779 /// getInsertFencesFor - return whether the DAG builder should automatically
780 /// insert fences and reduce ordering for atomics.
782 bool getInsertFencesForAtomic() const {
783 return InsertFencesForAtomic;
786 /// getPreIndexedAddressParts - returns true by value, base pointer and
787 /// offset pointer and addressing mode by reference if the node's address
788 /// can be legally represented as pre-indexed load / store address.
789 virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
791 ISD::MemIndexedMode &/*AM*/,
792 SelectionDAG &/*DAG*/) const {
796 /// getPostIndexedAddressParts - returns true by value, base pointer and
797 /// offset pointer and addressing mode by reference if this node can be
798 /// combined with a load / store to form a post-indexed load / store.
799 virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
800 SDValue &/*Base*/, SDValue &/*Offset*/,
801 ISD::MemIndexedMode &/*AM*/,
802 SelectionDAG &/*DAG*/) const {
806 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
807 /// current function. The returned value is a member of the
808 /// MachineJumpTableInfo::JTEntryKind enum.
809 virtual unsigned getJumpTableEncoding() const;
811 virtual const MCExpr *
812 LowerCustomJumpTableEntry(const MachineJumpTableInfo * /*MJTI*/,
813 const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
814 MCContext &/*Ctx*/) const {
815 llvm_unreachable("Need to implement this hook if target has custom JTIs");
818 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
820 virtual SDValue getPICJumpTableRelocBase(SDValue Table,
821 SelectionDAG &DAG) const;
823 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
824 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
826 virtual const MCExpr *
827 getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
828 unsigned JTI, MCContext &Ctx) const;
830 /// isOffsetFoldingLegal - Return true if folding a constant offset
831 /// with the given GlobalAddress is legal. It is frequently not legal in
832 /// PIC relocation models.
833 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
835 /// getStackCookieLocation - Return true if the target stores stack
836 /// protector cookies at a fixed offset in some non-standard address
837 /// space, and populates the address space and offset as
839 virtual bool getStackCookieLocation(unsigned &/*AddressSpace*/,
840 unsigned &/*Offset*/) const {
844 /// getMaximalGlobalOffset - Returns the maximal possible offset which can be
845 /// used for loads / stores from the global.
846 virtual unsigned getMaximalGlobalOffset() const {
850 //===--------------------------------------------------------------------===//
851 // TargetLowering Optimization Methods
854 /// TargetLoweringOpt - A convenience struct that encapsulates a DAG, and two
855 /// SDValues for returning information from TargetLowering to its clients
856 /// that want to combine
857 struct TargetLoweringOpt {
864 explicit TargetLoweringOpt(SelectionDAG &InDAG,
866 DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
868 bool LegalTypes() const { return LegalTys; }
869 bool LegalOperations() const { return LegalOps; }
871 bool CombineTo(SDValue O, SDValue N) {
877 /// ShrinkDemandedConstant - Check to see if the specified operand of the
878 /// specified instruction is a constant integer. If so, check to see if
879 /// there are any bits set in the constant that are not demanded. If so,
880 /// shrink the constant and return true.
881 bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded);
883 /// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the
884 /// casts are free. This uses isZExtFree and ZERO_EXTEND for the widening
885 /// cast, but it could be generalized for targets with other types of
886 /// implicit widening casts.
887 bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
891 /// SimplifyDemandedBits - Look at Op. At this point, we know that only the
892 /// DemandedMask bits of the result of Op are ever used downstream. If we can
893 /// use this information to simplify Op, create a new simplified DAG node and
894 /// return true, returning the original and new nodes in Old and New.
895 /// Otherwise, analyze the expression and return a mask of KnownOne and
896 /// KnownZero bits for the expression (used to simplify the caller).
897 /// The KnownZero/One bits may only be accurate for those bits in the
899 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
900 APInt &KnownZero, APInt &KnownOne,
901 TargetLoweringOpt &TLO, unsigned Depth = 0) const;
903 /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
904 /// Mask are known to be either zero or one and return them in the
905 /// KnownZero/KnownOne bitsets.
906 virtual void computeMaskedBitsForTargetNode(const SDValue Op,
909 const SelectionDAG &DAG,
910 unsigned Depth = 0) const;
912 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
913 /// targets that want to expose additional information about sign bits to the
915 virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
916 unsigned Depth = 0) const;
918 struct DAGCombinerInfo {
919 void *DC; // The DAG Combiner object.
921 bool BeforeLegalizeOps;
922 bool CalledByLegalizer;
926 DAGCombinerInfo(SelectionDAG &dag, bool bl, bool blo, bool cl, void *dc)
927 : DC(dc), BeforeLegalize(bl), BeforeLegalizeOps(blo),
928 CalledByLegalizer(cl), DAG(dag) {}
930 bool isBeforeLegalize() const { return BeforeLegalize; }
931 bool isBeforeLegalizeOps() const { return BeforeLegalizeOps; }
932 bool isCalledByLegalizer() const { return CalledByLegalizer; }
934 void AddToWorklist(SDNode *N);
935 void RemoveFromWorklist(SDNode *N);
936 SDValue CombineTo(SDNode *N, const std::vector<SDValue> &To,
938 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
939 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
941 void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
944 /// SimplifySetCC - Try to simplify a setcc built with the specified operands
945 /// and cc. If it is unable to simplify it, return a null SDValue.
946 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
947 ISD::CondCode Cond, bool foldBooleans,
948 DAGCombinerInfo &DCI, DebugLoc dl) const;
950 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
951 /// node is a GlobalAddress + offset.
953 isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
955 /// PerformDAGCombine - This method will be invoked for all target nodes and
956 /// for any target-independent nodes that the target has registered with
959 /// The semantics are as follows:
961 /// SDValue.Val == 0 - No change was made
962 /// SDValue.Val == N - N was replaced, is dead, and is already handled.
963 /// otherwise - N should be replaced by the returned Operand.
965 /// In addition, methods provided by DAGCombinerInfo may be used to perform
966 /// more complex transformations.
968 virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
970 /// isTypeDesirableForOp - Return true if the target has native support for
971 /// the specified value type and it is 'desirable' to use the type for the
972 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
973 /// instruction encodings are longer and some i16 instructions are slow.
974 virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
975 // By default, assume all legal types are desirable.
976 return isTypeLegal(VT);
979 /// isDesirableToPromoteOp - Return true if it is profitable for dag combiner
980 /// to transform a floating point op of specified opcode to a equivalent op of
981 /// an integer type. e.g. f32 load -> i32 load can be profitable on ARM.
982 virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
987 /// IsDesirableToPromoteOp - This method query the target whether it is
988 /// beneficial for dag combiner to promote the specified node. If true, it
989 /// should return the desired promotion type by reference.
990 virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
994 //===--------------------------------------------------------------------===//
995 // TargetLowering Configuration Methods - These methods should be invoked by
996 // the derived class constructor to configure this object for the target.
1000 /// setBooleanContents - Specify how the target extends the result of a
1001 /// boolean value from i1 to a wider type. See getBooleanContents.
1002 void setBooleanContents(BooleanContent Ty) { BooleanContents = Ty; }
1003 /// setBooleanVectorContents - Specify how the target extends the result
1004 /// of a vector boolean value from a vector of i1 to a wider type. See
1005 /// getBooleanContents.
1006 void setBooleanVectorContents(BooleanContent Ty) {
1007 BooleanVectorContents = Ty;
1010 /// setSchedulingPreference - Specify the target scheduling preference.
1011 void setSchedulingPreference(Sched::Preference Pref) {
1012 SchedPreferenceInfo = Pref;
1015 /// setUseUnderscoreSetJmp - Indicate whether this target prefers to
1016 /// use _setjmp to implement llvm.setjmp or the non _ version.
1017 /// Defaults to false.
1018 void setUseUnderscoreSetJmp(bool Val) {
1019 UseUnderscoreSetJmp = Val;
1022 /// setUseUnderscoreLongJmp - Indicate whether this target prefers to
1023 /// use _longjmp to implement llvm.longjmp or the non _ version.
1024 /// Defaults to false.
1025 void setUseUnderscoreLongJmp(bool Val) {
1026 UseUnderscoreLongJmp = Val;
1029 /// setSupportJumpTables - Indicate whether the target can generate code for
1031 void setSupportJumpTables(bool Val) {
1032 SupportJumpTables = Val;
1035 /// setStackPointerRegisterToSaveRestore - If set to a physical register, this
1036 /// specifies the register that llvm.savestack/llvm.restorestack should save
1038 void setStackPointerRegisterToSaveRestore(unsigned R) {
1039 StackPointerRegisterToSaveRestore = R;
1042 /// setExceptionPointerRegister - If set to a physical register, this sets
1043 /// the register that receives the exception address on entry to a landing
1045 void setExceptionPointerRegister(unsigned R) {
1046 ExceptionPointerRegister = R;
1049 /// setExceptionSelectorRegister - If set to a physical register, this sets
1050 /// the register that receives the exception typeid on entry to a landing
1052 void setExceptionSelectorRegister(unsigned R) {
1053 ExceptionSelectorRegister = R;
1056 /// SelectIsExpensive - Tells the code generator not to expand operations
1057 /// into sequences that use the select operations if possible.
1058 void setSelectIsExpensive(bool isExpensive = true) {
1059 SelectIsExpensive = isExpensive;
1062 /// JumpIsExpensive - Tells the code generator not to expand sequence of
1063 /// operations into a separate sequences that increases the amount of
1065 void setJumpIsExpensive(bool isExpensive = true) {
1066 JumpIsExpensive = isExpensive;
1069 /// setIntDivIsCheap - Tells the code generator that integer divide is
1070 /// expensive, and if possible, should be replaced by an alternate sequence
1071 /// of instructions not containing an integer divide.
1072 void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
1074 /// addBypassSlowDivType - Tells the code generator which types to bypass.
1075 void addBypassSlowDivType(Type *slow_type, Type *fast_type) {
1076 BypassSlowDivTypes[slow_type] = fast_type;
1079 /// setPow2DivIsCheap - Tells the code generator that it shouldn't generate
1080 /// srl/add/sra for a signed divide by power of two, and let the target handle
1082 void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
1084 /// addRegisterClass - Add the specified register class as an available
1085 /// regclass for the specified value type. This indicates the selector can
1086 /// handle values of that class natively.
1087 void addRegisterClass(EVT VT, const TargetRegisterClass *RC) {
1088 assert((unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
1089 AvailableRegClasses.push_back(std::make_pair(VT, RC));
1090 RegClassForVT[VT.getSimpleVT().SimpleTy] = RC;
1093 /// findRepresentativeClass - Return the largest legal super-reg register class
1094 /// of the register class for the specified type and its associated "cost".
1095 virtual std::pair<const TargetRegisterClass*, uint8_t>
1096 findRepresentativeClass(EVT VT) const;
1098 /// computeRegisterProperties - Once all of the register classes are added,
1099 /// this allows us to compute derived properties we expose.
1100 void computeRegisterProperties();
1102 /// setOperationAction - Indicate that the specified operation does not work
1103 /// with the specified type and indicate what to do about it.
1104 void setOperationAction(unsigned Op, MVT VT,
1105 LegalizeAction Action) {
1106 assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
1107 OpActions[(unsigned)VT.SimpleTy][Op] = (uint8_t)Action;
1110 /// setLoadExtAction - Indicate that the specified load with extension does
1111 /// not work with the specified type and indicate what to do about it.
1112 void setLoadExtAction(unsigned ExtType, MVT VT,
1113 LegalizeAction Action) {
1114 assert(ExtType < ISD::LAST_LOADEXT_TYPE && VT < MVT::LAST_VALUETYPE &&
1115 "Table isn't big enough!");
1116 LoadExtActions[VT.SimpleTy][ExtType] = (uint8_t)Action;
1119 /// setTruncStoreAction - Indicate that the specified truncating store does
1120 /// not work with the specified type and indicate what to do about it.
1121 void setTruncStoreAction(MVT ValVT, MVT MemVT,
1122 LegalizeAction Action) {
1123 assert(ValVT < MVT::LAST_VALUETYPE && MemVT < MVT::LAST_VALUETYPE &&
1124 "Table isn't big enough!");
1125 TruncStoreActions[ValVT.SimpleTy][MemVT.SimpleTy] = (uint8_t)Action;
1128 /// setIndexedLoadAction - Indicate that the specified indexed load does or
1129 /// does not work with the specified type and indicate what to do abort
1130 /// it. NOTE: All indexed mode loads are initialized to Expand in
1131 /// TargetLowering.cpp
1132 void setIndexedLoadAction(unsigned IdxMode, MVT VT,
1133 LegalizeAction Action) {
1134 assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
1135 (unsigned)Action < 0xf && "Table isn't big enough!");
1136 // Load action are kept in the upper half.
1137 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0xf0;
1138 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action) <<4;
1141 /// setIndexedStoreAction - Indicate that the specified indexed store does or
1142 /// does not work with the specified type and indicate what to do about
1143 /// it. NOTE: All indexed mode stores are initialized to Expand in
1144 /// TargetLowering.cpp
1145 void setIndexedStoreAction(unsigned IdxMode, MVT VT,
1146 LegalizeAction Action) {
1147 assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
1148 (unsigned)Action < 0xf && "Table isn't big enough!");
1149 // Store action are kept in the lower half.
1150 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0x0f;
1151 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action);
1154 /// setCondCodeAction - Indicate that the specified condition code is or isn't
1155 /// supported on the target and indicate what to do about it.
1156 void setCondCodeAction(ISD::CondCode CC, MVT VT,
1157 LegalizeAction Action) {
1158 assert(VT < MVT::LAST_VALUETYPE &&
1159 (unsigned)CC < array_lengthof(CondCodeActions) &&
1160 "Table isn't big enough!");
1161 /// The lower 5 bits of the SimpleTy index into Nth 2bit set from the 64bit
1162 /// value and the upper 27 bits index into the second dimension of the
1163 /// array to select what 64bit value to use.
1164 CondCodeActions[(unsigned)CC][VT.SimpleTy >> 5]
1165 &= ~(uint64_t(3UL) << (VT.SimpleTy & 0x1F)*2);
1166 CondCodeActions[(unsigned)CC][VT.SimpleTy >> 5]
1167 |= (uint64_t)Action << (VT.SimpleTy & 0x1F)*2;
1170 /// AddPromotedToType - If Opc/OrigVT is specified as being promoted, the
1171 /// promotion code defaults to trying a larger integer/fp until it can find
1172 /// one that works. If that default is insufficient, this method can be used
1173 /// by the target to override the default.
1174 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1175 PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
1178 /// setTargetDAGCombine - Targets should invoke this method for each target
1179 /// independent node that they want to provide a custom DAG combiner for by
1180 /// implementing the PerformDAGCombine virtual method.
1181 void setTargetDAGCombine(ISD::NodeType NT) {
1182 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1183 TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
1186 /// setJumpBufSize - Set the target's required jmp_buf buffer size (in
1187 /// bytes); default is 200
1188 void setJumpBufSize(unsigned Size) {
1192 /// setJumpBufAlignment - Set the target's required jmp_buf buffer
1193 /// alignment (in bytes); default is 0
1194 void setJumpBufAlignment(unsigned Align) {
1195 JumpBufAlignment = Align;
1198 /// setMinFunctionAlignment - Set the target's minimum function alignment (in
1200 void setMinFunctionAlignment(unsigned Align) {
1201 MinFunctionAlignment = Align;
1204 /// setPrefFunctionAlignment - Set the target's preferred function alignment.
1205 /// This should be set if there is a performance benefit to
1206 /// higher-than-minimum alignment (in log2(bytes))
1207 void setPrefFunctionAlignment(unsigned Align) {
1208 PrefFunctionAlignment = Align;
1211 /// setPrefLoopAlignment - Set the target's preferred loop alignment. Default
1212 /// alignment is zero, it means the target does not care about loop alignment.
1213 /// The alignment is specified in log2(bytes).
1214 void setPrefLoopAlignment(unsigned Align) {
1215 PrefLoopAlignment = Align;
1218 /// setMinStackArgumentAlignment - Set the minimum stack alignment of an
1219 /// argument (in log2(bytes)).
1220 void setMinStackArgumentAlignment(unsigned Align) {
1221 MinStackArgumentAlignment = Align;
1224 /// setShouldFoldAtomicFences - Set if the target's implementation of the
1225 /// atomic operation intrinsics includes locking. Default is false.
1226 void setShouldFoldAtomicFences(bool fold) {
1227 ShouldFoldAtomicFences = fold;
1230 /// setInsertFencesForAtomic - Set if the DAG builder should
1231 /// automatically insert fences and reduce the order of atomic memory
1232 /// operations to Monotonic.
1233 void setInsertFencesForAtomic(bool fence) {
1234 InsertFencesForAtomic = fence;
1238 //===--------------------------------------------------------------------===//
1239 // Lowering methods - These methods must be implemented by targets so that
1240 // the SelectionDAGLowering code knows how to lower these.
1243 /// LowerFormalArguments - This hook must be implemented to lower the
1244 /// incoming (formal) arguments, described by the Ins array, into the
1245 /// specified DAG. The implementation should fill in the InVals array
1246 /// with legal-type argument values, and return the resulting token
1250 LowerFormalArguments(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
1252 const SmallVectorImpl<ISD::InputArg> &/*Ins*/,
1253 DebugLoc /*dl*/, SelectionDAG &/*DAG*/,
1254 SmallVectorImpl<SDValue> &/*InVals*/) const {
1255 llvm_unreachable("Not Implemented");
1258 struct ArgListEntry {
1269 ArgListEntry() : isSExt(false), isZExt(false), isInReg(false),
1270 isSRet(false), isNest(false), isByVal(false), Alignment(0) { }
1272 typedef std::vector<ArgListEntry> ArgListTy;
1274 /// CallLoweringInfo - This structure contains all information that is
1275 /// necessary for lowering calls. It is passed to TLI::LowerCallTo when the
1276 /// SelectionDAG builder needs to lower a call, and targets will see this
1277 /// struct in their LowerCall implementation.
1278 struct CallLoweringInfo {
1285 bool DoesNotReturn : 1;
1286 bool IsReturnValueUsed : 1;
1288 // IsTailCall should be modified by implementations of
1289 // TargetLowering::LowerCall that perform tail call conversions.
1292 unsigned NumFixedArgs;
1293 CallingConv::ID CallConv;
1298 ImmutableCallSite *CS;
1299 SmallVector<ISD::OutputArg, 32> Outs;
1300 SmallVector<SDValue, 32> OutVals;
1301 SmallVector<ISD::InputArg, 32> Ins;
1304 /// CallLoweringInfo - Constructs a call lowering context based on the
1305 /// ImmutableCallSite \p cs.
1306 CallLoweringInfo(SDValue chain, Type *retTy,
1307 FunctionType *FTy, bool isTailCall, SDValue callee,
1308 ArgListTy &args, SelectionDAG &dag, DebugLoc dl,
1309 ImmutableCallSite &cs)
1310 : Chain(chain), RetTy(retTy), RetSExt(cs.paramHasAttr(0, Attribute::SExt)),
1311 RetZExt(cs.paramHasAttr(0, Attribute::ZExt)), IsVarArg(FTy->isVarArg()),
1312 IsInReg(cs.paramHasAttr(0, Attribute::InReg)),
1313 DoesNotReturn(cs.doesNotReturn()),
1314 IsReturnValueUsed(!cs.getInstruction()->use_empty()),
1315 IsTailCall(isTailCall), NumFixedArgs(FTy->getNumParams()),
1316 CallConv(cs.getCallingConv()), Callee(callee), Args(args), DAG(dag),
1319 /// CallLoweringInfo - Constructs a call lowering context based on the
1320 /// provided call information.
1321 CallLoweringInfo(SDValue chain, Type *retTy, bool retSExt, bool retZExt,
1322 bool isVarArg, bool isInReg, unsigned numFixedArgs,
1323 CallingConv::ID callConv, bool isTailCall,
1324 bool doesNotReturn, bool isReturnValueUsed, SDValue callee,
1325 ArgListTy &args, SelectionDAG &dag, DebugLoc dl)
1326 : Chain(chain), RetTy(retTy), RetSExt(retSExt), RetZExt(retZExt),
1327 IsVarArg(isVarArg), IsInReg(isInReg), DoesNotReturn(doesNotReturn),
1328 IsReturnValueUsed(isReturnValueUsed), IsTailCall(isTailCall),
1329 NumFixedArgs(numFixedArgs), CallConv(callConv), Callee(callee),
1330 Args(args), DAG(dag), DL(dl), CS(NULL) {}
1333 /// LowerCallTo - This function lowers an abstract call to a function into an
1334 /// actual call. This returns a pair of operands. The first element is the
1335 /// return value for the function (if RetTy is not VoidTy). The second
1336 /// element is the outgoing token chain. It calls LowerCall to do the actual
1338 std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
1340 /// LowerCall - This hook must be implemented to lower calls into the
1341 /// the specified DAG. The outgoing arguments to the call are described
1342 /// by the Outs array, and the values to be returned by the call are
1343 /// described by the Ins array. The implementation should fill in the
1344 /// InVals array with legal-type return values from the call, and return
1345 /// the resulting token chain value.
1347 LowerCall(CallLoweringInfo &/*CLI*/,
1348 SmallVectorImpl<SDValue> &/*InVals*/) const {
1349 llvm_unreachable("Not Implemented");
1352 /// HandleByVal - Target-specific cleanup for formal ByVal parameters.
1353 virtual void HandleByVal(CCState *, unsigned &) const {}
1355 /// CanLowerReturn - This hook should be implemented to check whether the
1356 /// return values described by the Outs array can fit into the return
1357 /// registers. If false is returned, an sret-demotion is performed.
1359 virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
1360 MachineFunction &/*MF*/, bool /*isVarArg*/,
1361 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
1362 LLVMContext &/*Context*/) const
1364 // Return true by default to get preexisting behavior.
1368 /// LowerReturn - This hook must be implemented to lower outgoing
1369 /// return values, described by the Outs array, into the specified
1370 /// DAG. The implementation should return the resulting token chain
1374 LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
1376 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
1377 const SmallVectorImpl<SDValue> &/*OutVals*/,
1378 DebugLoc /*dl*/, SelectionDAG &/*DAG*/) const {
1379 llvm_unreachable("Not Implemented");
1382 /// isUsedByReturnOnly - Return true if result of the specified node is used
1383 /// by a return node only. It also compute and return the input chain for the
1385 /// This is used to determine whether it is possible
1386 /// to codegen a libcall as tail call at legalization time.
1387 virtual bool isUsedByReturnOnly(SDNode *, SDValue &Chain) const {
1391 /// mayBeEmittedAsTailCall - Return true if the target may be able emit the
1392 /// call instruction as a tail call. This is used by optimization passes to
1393 /// determine if it's profitable to duplicate return instructions to enable
1394 /// tailcall optimization.
1395 virtual bool mayBeEmittedAsTailCall(CallInst *) const {
1399 /// getTypeForExtArgOrReturn - Return the type that should be used to zero or
1400 /// sign extend a zeroext/signext integer argument or return value.
1401 /// FIXME: Most C calling convention requires the return type to be promoted,
1402 /// but this is not true all the time, e.g. i1 on x86-64. It is also not
1403 /// necessary for non-C calling conventions. The frontend should handle this
1404 /// and include all of the necessary information.
1405 virtual EVT getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1406 ISD::NodeType /*ExtendKind*/) const {
1407 EVT MinVT = getRegisterType(Context, MVT::i32);
1408 return VT.bitsLT(MinVT) ? MinVT : VT;
1411 /// LowerOperationWrapper - This callback is invoked by the type legalizer
1412 /// to legalize nodes with an illegal operand type but legal result types.
1413 /// It replaces the LowerOperation callback in the type Legalizer.
1414 /// The reason we can not do away with LowerOperation entirely is that
1415 /// LegalizeDAG isn't yet ready to use this callback.
1416 /// TODO: Consider merging with ReplaceNodeResults.
1418 /// The target places new result values for the node in Results (their number
1419 /// and types must exactly match those of the original return values of
1420 /// the node), or leaves Results empty, which indicates that the node is not
1421 /// to be custom lowered after all.
1422 /// The default implementation calls LowerOperation.
1423 virtual void LowerOperationWrapper(SDNode *N,
1424 SmallVectorImpl<SDValue> &Results,
1425 SelectionDAG &DAG) const;
1427 /// LowerOperation - This callback is invoked for operations that are
1428 /// unsupported by the target, which are registered to use 'custom' lowering,
1429 /// and whose defined values are all legal.
1430 /// If the target has no operations that require custom lowering, it need not
1431 /// implement this. The default implementation of this aborts.
1432 virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
1434 /// ReplaceNodeResults - This callback is invoked when a node result type is
1435 /// illegal for the target, and the operation was registered to use 'custom'
1436 /// lowering for that result type. The target places new result values for
1437 /// the node in Results (their number and types must exactly match those of
1438 /// the original return values of the node), or leaves Results empty, which
1439 /// indicates that the node is not to be custom lowered after all.
1441 /// If the target has no operations that require custom lowering, it need not
1442 /// implement this. The default implementation aborts.
1443 virtual void ReplaceNodeResults(SDNode * /*N*/,
1444 SmallVectorImpl<SDValue> &/*Results*/,
1445 SelectionDAG &/*DAG*/) const {
1446 llvm_unreachable("ReplaceNodeResults not implemented for this target!");
1449 /// getTargetNodeName() - This method returns the name of a target specific
1451 virtual const char *getTargetNodeName(unsigned Opcode) const;
1453 /// createFastISel - This method returns a target specific FastISel object,
1454 /// or null if the target does not support "fast" ISel.
1455 virtual FastISel *createFastISel(FunctionLoweringInfo &,
1456 const TargetLibraryInfo *) const {
1460 //===--------------------------------------------------------------------===//
1461 // Inline Asm Support hooks
1464 /// ExpandInlineAsm - This hook allows the target to expand an inline asm
1465 /// call to be explicit llvm code if it wants to. This is useful for
1466 /// turning simple inline asms into LLVM intrinsics, which gives the
1467 /// compiler more information about the behavior of the code.
1468 virtual bool ExpandInlineAsm(CallInst *) const {
1472 enum ConstraintType {
1473 C_Register, // Constraint represents specific register(s).
1474 C_RegisterClass, // Constraint represents any of register(s) in class.
1475 C_Memory, // Memory constraint.
1476 C_Other, // Something else.
1477 C_Unknown // Unsupported constraint.
1480 enum ConstraintWeight {
1482 CW_Invalid = -1, // No match.
1483 CW_Okay = 0, // Acceptable.
1484 CW_Good = 1, // Good weight.
1485 CW_Better = 2, // Better weight.
1486 CW_Best = 3, // Best weight.
1488 // Well-known weights.
1489 CW_SpecificReg = CW_Okay, // Specific register operands.
1490 CW_Register = CW_Good, // Register operands.
1491 CW_Memory = CW_Better, // Memory operands.
1492 CW_Constant = CW_Best, // Constant operand.
1493 CW_Default = CW_Okay // Default or don't know type.
1496 /// AsmOperandInfo - This contains information for each constraint that we are
1498 struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
1499 /// ConstraintCode - This contains the actual string for the code, like "m".
1500 /// TargetLowering picks the 'best' code from ConstraintInfo::Codes that
1501 /// most closely matches the operand.
1502 std::string ConstraintCode;
1504 /// ConstraintType - Information about the constraint code, e.g. Register,
1505 /// RegisterClass, Memory, Other, Unknown.
1506 TargetLowering::ConstraintType ConstraintType;
1508 /// CallOperandval - If this is the result output operand or a
1509 /// clobber, this is null, otherwise it is the incoming operand to the
1510 /// CallInst. This gets modified as the asm is processed.
1511 Value *CallOperandVal;
1513 /// ConstraintVT - The ValueType for the operand value.
1516 /// isMatchingInputConstraint - Return true of this is an input operand that
1517 /// is a matching constraint like "4".
1518 bool isMatchingInputConstraint() const;
1520 /// getMatchedOperand - If this is an input matching constraint, this method
1521 /// returns the output operand it matches.
1522 unsigned getMatchedOperand() const;
1524 /// Copy constructor for copying from an AsmOperandInfo.
1525 AsmOperandInfo(const AsmOperandInfo &info)
1526 : InlineAsm::ConstraintInfo(info),
1527 ConstraintCode(info.ConstraintCode),
1528 ConstraintType(info.ConstraintType),
1529 CallOperandVal(info.CallOperandVal),
1530 ConstraintVT(info.ConstraintVT) {
1533 /// Copy constructor for copying from a ConstraintInfo.
1534 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
1535 : InlineAsm::ConstraintInfo(info),
1536 ConstraintType(TargetLowering::C_Unknown),
1537 CallOperandVal(0), ConstraintVT(MVT::Other) {
1541 typedef std::vector<AsmOperandInfo> AsmOperandInfoVector;
1543 /// ParseConstraints - Split up the constraint string from the inline
1544 /// assembly value into the specific constraints and their prefixes,
1545 /// and also tie in the associated operand values.
1546 /// If this returns an empty vector, and if the constraint string itself
1547 /// isn't empty, there was an error parsing.
1548 virtual AsmOperandInfoVector ParseConstraints(ImmutableCallSite CS) const;
1550 /// Examine constraint type and operand type and determine a weight value.
1551 /// The operand object must already have been set up with the operand type.
1552 virtual ConstraintWeight getMultipleConstraintMatchWeight(
1553 AsmOperandInfo &info, int maIndex) const;
1555 /// Examine constraint string and operand type and determine a weight value.
1556 /// The operand object must already have been set up with the operand type.
1557 virtual ConstraintWeight getSingleConstraintMatchWeight(
1558 AsmOperandInfo &info, const char *constraint) const;
1560 /// ComputeConstraintToUse - Determines the constraint code and constraint
1561 /// type to use for the specific AsmOperandInfo, setting
1562 /// OpInfo.ConstraintCode and OpInfo.ConstraintType. If the actual operand
1563 /// being passed in is available, it can be passed in as Op, otherwise an
1564 /// empty SDValue can be passed.
1565 virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
1567 SelectionDAG *DAG = 0) const;
1569 /// getConstraintType - Given a constraint, return the type of constraint it
1570 /// is for this target.
1571 virtual ConstraintType getConstraintType(const std::string &Constraint) const;
1573 /// getRegForInlineAsmConstraint - Given a physical register constraint (e.g.
1574 /// {edx}), return the register number and the register class for the
1577 /// Given a register class constraint, like 'r', if this corresponds directly
1578 /// to an LLVM register class, return a register of 0 and the register class
1581 /// This should only be used for C_Register constraints. On error,
1582 /// this returns a register number of 0 and a null register class pointer..
1583 virtual std::pair<unsigned, const TargetRegisterClass*>
1584 getRegForInlineAsmConstraint(const std::string &Constraint,
1587 /// LowerXConstraint - try to replace an X constraint, which matches anything,
1588 /// with another that has more specific requirements based on the type of the
1589 /// corresponding operand. This returns null if there is no replacement to
1591 virtual const char *LowerXConstraint(EVT ConstraintVT) const;
1593 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
1594 /// vector. If it is invalid, don't add anything to Ops.
1595 virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
1596 std::vector<SDValue> &Ops,
1597 SelectionDAG &DAG) const;
1599 //===--------------------------------------------------------------------===//
1600 // Instruction Emitting Hooks
1603 // EmitInstrWithCustomInserter - This method should be implemented by targets
1604 // that mark instructions with the 'usesCustomInserter' flag. These
1605 // instructions are special in various ways, which require special support to
1606 // insert. The specified MachineInstr is created but not inserted into any
1607 // basic blocks, and this method is called to expand it into a sequence of
1608 // instructions, potentially also creating new basic blocks and control flow.
1609 virtual MachineBasicBlock *
1610 EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const;
1612 /// AdjustInstrPostInstrSelection - This method should be implemented by
1613 /// targets that mark instructions with the 'hasPostISelHook' flag. These
1614 /// instructions must be adjusted after instruction selection by target hooks.
1615 /// e.g. To fill in optional defs for ARM 's' setting instructions.
1617 AdjustInstrPostInstrSelection(MachineInstr *MI, SDNode *Node) const;
1619 //===--------------------------------------------------------------------===//
1620 // Addressing mode description hooks (used by LSR etc).
1623 /// AddrMode - This represents an addressing mode of:
1624 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
1625 /// If BaseGV is null, there is no BaseGV.
1626 /// If BaseOffs is zero, there is no base offset.
1627 /// If HasBaseReg is false, there is no base register.
1628 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
1632 GlobalValue *BaseGV;
1636 AddrMode() : BaseGV(0), BaseOffs(0), HasBaseReg(false), Scale(0) {}
1639 /// GetAddrModeArguments - CodeGenPrepare sinks address calculations into the
1640 /// same BB as Load/Store instructions reading the address. This allows as
1641 /// much computation as possible to be done in the address mode for that
1642 /// operand. This hook lets targets also pass back when this should be done
1643 /// on intrinsics which load/store.
1644 virtual bool GetAddrModeArguments(IntrinsicInst *I,
1645 SmallVectorImpl<Value*> &Ops,
1646 Type *&AccessTy) const {
1650 /// isLegalAddressingMode - Return true if the addressing mode represented by
1651 /// AM is legal for this target, for a load/store of the specified type.
1652 /// The type may be VoidTy, in which case only return true if the addressing
1653 /// mode is legal for a load/store of any legal type.
1654 /// TODO: Handle pre/postinc as well.
1655 virtual bool isLegalAddressingMode(const AddrMode &AM, Type *Ty) const;
1657 /// isLegalICmpImmediate - Return true if the specified immediate is legal
1658 /// icmp immediate, that is the target has icmp instructions which can compare
1659 /// a register against the immediate without having to materialize the
1660 /// immediate into a register.
1661 virtual bool isLegalICmpImmediate(int64_t) const {
1665 /// isLegalAddImmediate - Return true if the specified immediate is legal
1666 /// add immediate, that is the target has add instructions which can add
1667 /// a register with the immediate without having to materialize the
1668 /// immediate into a register.
1669 virtual bool isLegalAddImmediate(int64_t) const {
1673 /// isTruncateFree - Return true if it's free to truncate a value of
1674 /// type Ty1 to type Ty2. e.g. On x86 it's free to truncate a i32 value in
1675 /// register EAX to i16 by referencing its sub-register AX.
1676 virtual bool isTruncateFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1680 virtual bool isTruncateFree(EVT /*VT1*/, EVT /*VT2*/) const {
1684 /// isZExtFree - Return true if any actual instruction that defines a
1685 /// value of type Ty1 implicitly zero-extends the value to Ty2 in the result
1686 /// register. This does not necessarily include registers defined in
1687 /// unknown ways, such as incoming arguments, or copies from unknown
1688 /// virtual registers. Also, if isTruncateFree(Ty2, Ty1) is true, this
1689 /// does not necessarily apply to truncate instructions. e.g. on x86-64,
1690 /// all instructions that define 32-bit values implicit zero-extend the
1691 /// result out to 64 bits.
1692 virtual bool isZExtFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1696 virtual bool isZExtFree(EVT /*VT1*/, EVT /*VT2*/) const {
1700 /// isFNegFree - Return true if an fneg operation is free to the point where
1701 /// it is never worthwhile to replace it with a bitwise operation.
1702 virtual bool isFNegFree(EVT) const {
1706 /// isFAbsFree - Return true if an fneg operation is free to the point where
1707 /// it is never worthwhile to replace it with a bitwise operation.
1708 virtual bool isFAbsFree(EVT) const {
1712 /// isFMAFasterThanMulAndAdd - Return true if an FMA operation is faster than
1713 /// a pair of mul and add instructions. fmuladd intrinsics will be expanded to
1714 /// FMAs when this method returns true (and FMAs are legal), otherwise fmuladd
1715 /// is expanded to mul + add.
1716 virtual bool isFMAFasterThanMulAndAdd(EVT) const {
1720 /// isNarrowingProfitable - Return true if it's profitable to narrow
1721 /// operations of type VT1 to VT2. e.g. on x86, it's profitable to narrow
1722 /// from i32 to i8 but not from i32 to i16.
1723 virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
1727 //===--------------------------------------------------------------------===//
1728 // Div utility functions
1730 SDValue BuildExactSDIV(SDValue Op1, SDValue Op2, DebugLoc dl,
1731 SelectionDAG &DAG) const;
1732 SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
1733 std::vector<SDNode*>* Created) const;
1734 SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
1735 std::vector<SDNode*>* Created) const;
1738 //===--------------------------------------------------------------------===//
1739 // Runtime Library hooks
1742 /// setLibcallName - Rename the default libcall routine name for the specified
1744 void setLibcallName(RTLIB::Libcall Call, const char *Name) {
1745 LibcallRoutineNames[Call] = Name;
1748 /// getLibcallName - Get the libcall routine name for the specified libcall.
1750 const char *getLibcallName(RTLIB::Libcall Call) const {
1751 return LibcallRoutineNames[Call];
1754 /// setCmpLibcallCC - Override the default CondCode to be used to test the
1755 /// result of the comparison libcall against zero.
1756 void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
1757 CmpLibcallCCs[Call] = CC;
1760 /// getCmpLibcallCC - Get the CondCode that's to be used to test the result of
1761 /// the comparison libcall against zero.
1762 ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
1763 return CmpLibcallCCs[Call];
1766 /// setLibcallCallingConv - Set the CallingConv that should be used for the
1767 /// specified libcall.
1768 void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
1769 LibcallCallingConvs[Call] = CC;
1772 /// getLibcallCallingConv - Get the CallingConv that should be used for the
1773 /// specified libcall.
1774 CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
1775 return LibcallCallingConvs[Call];
1779 const TargetMachine &TM;
1780 const TargetData *TD;
1781 const TargetLoweringObjectFile &TLOF;
1783 /// PointerTy - The type to use for pointers, usually i32 or i64.
1787 /// IsLittleEndian - True if this is a little endian target.
1789 bool IsLittleEndian;
1791 /// SelectIsExpensive - Tells the code generator not to expand operations
1792 /// into sequences that use the select operations if possible.
1793 bool SelectIsExpensive;
1795 /// IntDivIsCheap - Tells the code generator not to expand integer divides by
1796 /// constants into a sequence of muls, adds, and shifts. This is a hack until
1797 /// a real cost model is in place. If we ever optimize for size, this will be
1798 /// set to true unconditionally.
1801 /// BypassSlowDivTypes - Tells the code generator to bypass slow divide or
1802 /// remainder instructions. For example, SlowDivBypass[i32,u8] tells the code
1803 /// generator to bypass 32-bit signed integer div/rem with an 8-bit unsigned
1804 /// integer div/rem when the operands are positive and less than 256.
1805 DenseMap <Type *, Type *> BypassSlowDivTypes;
1807 /// Pow2DivIsCheap - Tells the code generator that it shouldn't generate
1808 /// srl/add/sra for a signed divide by power of two, and let the target handle
1810 bool Pow2DivIsCheap;
1812 /// JumpIsExpensive - Tells the code generator that it shouldn't generate
1813 /// extra flow control instructions and should attempt to combine flow
1814 /// control instructions via predication.
1815 bool JumpIsExpensive;
1817 /// UseUnderscoreSetJmp - This target prefers to use _setjmp to implement
1818 /// llvm.setjmp. Defaults to false.
1819 bool UseUnderscoreSetJmp;
1821 /// UseUnderscoreLongJmp - This target prefers to use _longjmp to implement
1822 /// llvm.longjmp. Defaults to false.
1823 bool UseUnderscoreLongJmp;
1825 /// SupportJumpTables - Whether the target can generate code for jumptables.
1826 /// If it's not true, then each jumptable must be lowered into if-then-else's.
1827 bool SupportJumpTables;
1829 /// BooleanContents - Information about the contents of the high-bits in
1830 /// boolean values held in a type wider than i1. See getBooleanContents.
1831 BooleanContent BooleanContents;
1832 /// BooleanVectorContents - Information about the contents of the high-bits
1833 /// in boolean vector values when the element type is wider than i1. See
1834 /// getBooleanContents.
1835 BooleanContent BooleanVectorContents;
1837 /// SchedPreferenceInfo - The target scheduling preference: shortest possible
1838 /// total cycles or lowest register usage.
1839 Sched::Preference SchedPreferenceInfo;
1841 /// JumpBufSize - The size, in bytes, of the target's jmp_buf buffers
1842 unsigned JumpBufSize;
1844 /// JumpBufAlignment - The alignment, in bytes, of the target's jmp_buf
1846 unsigned JumpBufAlignment;
1848 /// MinStackArgumentAlignment - The minimum alignment that any argument
1849 /// on the stack needs to have.
1851 unsigned MinStackArgumentAlignment;
1853 /// MinFunctionAlignment - The minimum function alignment (used when
1854 /// optimizing for size, and to prevent explicitly provided alignment
1855 /// from leading to incorrect code).
1857 unsigned MinFunctionAlignment;
1859 /// PrefFunctionAlignment - The preferred function alignment (used when
1860 /// alignment unspecified and optimizing for speed).
1862 unsigned PrefFunctionAlignment;
1864 /// PrefLoopAlignment - The preferred loop alignment.
1866 unsigned PrefLoopAlignment;
1868 /// ShouldFoldAtomicFences - Whether fencing MEMBARRIER instructions should
1869 /// be folded into the enclosed atomic intrinsic instruction by the
1871 bool ShouldFoldAtomicFences;
1873 /// InsertFencesForAtomic - Whether the DAG builder should automatically
1874 /// insert fences and reduce ordering for atomics. (This will be set for
1875 /// for most architectures with weak memory ordering.)
1876 bool InsertFencesForAtomic;
1878 /// StackPointerRegisterToSaveRestore - If set to a physical register, this
1879 /// specifies the register that llvm.savestack/llvm.restorestack should save
1881 unsigned StackPointerRegisterToSaveRestore;
1883 /// ExceptionPointerRegister - If set to a physical register, this specifies
1884 /// the register that receives the exception address on entry to a landing
1886 unsigned ExceptionPointerRegister;
1888 /// ExceptionSelectorRegister - If set to a physical register, this specifies
1889 /// the register that receives the exception typeid on entry to a landing
1891 unsigned ExceptionSelectorRegister;
1893 /// RegClassForVT - This indicates the default register class to use for
1894 /// each ValueType the target supports natively.
1895 const TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
1896 unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
1897 EVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
1899 /// RepRegClassForVT - This indicates the "representative" register class to
1900 /// use for each ValueType the target supports natively. This information is
1901 /// used by the scheduler to track register pressure. By default, the
1902 /// representative register class is the largest legal super-reg register
1903 /// class of the register class of the specified type. e.g. On x86, i8, i16,
1904 /// and i32's representative class would be GR32.
1905 const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
1907 /// RepRegClassCostForVT - This indicates the "cost" of the "representative"
1908 /// register class for each ValueType. The cost is used by the scheduler to
1909 /// approximate register pressure.
1910 uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
1912 /// TransformToType - For any value types we are promoting or expanding, this
1913 /// contains the value type that we are changing to. For Expanded types, this
1914 /// contains one step of the expand (e.g. i64 -> i32), even if there are
1915 /// multiple steps required (e.g. i64 -> i16). For types natively supported
1916 /// by the system, this holds the same type (e.g. i32 -> i32).
1917 EVT TransformToType[MVT::LAST_VALUETYPE];
1919 /// OpActions - For each operation and each value type, keep a LegalizeAction
1920 /// that indicates how instruction selection should deal with the operation.
1921 /// Most operations are Legal (aka, supported natively by the target), but
1922 /// operations that are not should be described. Note that operations on
1923 /// non-legal value types are not described here.
1924 uint8_t OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END];
1926 /// LoadExtActions - For each load extension type and each value type,
1927 /// keep a LegalizeAction that indicates how instruction selection should deal
1928 /// with a load of a specific value type and extension type.
1929 uint8_t LoadExtActions[MVT::LAST_VALUETYPE][ISD::LAST_LOADEXT_TYPE];
1931 /// TruncStoreActions - For each value type pair keep a LegalizeAction that
1932 /// indicates whether a truncating store of a specific value type and
1933 /// truncating type is legal.
1934 uint8_t TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
1936 /// IndexedModeActions - For each indexed mode and each value type,
1937 /// keep a pair of LegalizeAction that indicates how instruction
1938 /// selection should deal with the load / store. The first dimension is the
1939 /// value_type for the reference. The second dimension represents the various
1940 /// modes for load store.
1941 uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
1943 /// CondCodeActions - For each condition code (ISD::CondCode) keep a
1944 /// LegalizeAction that indicates how instruction selection should
1945 /// deal with the condition code.
1946 /// Because each CC action takes up 2 bits, we need to have the array size
1947 /// be large enough to fit all of the value types. This can be done by
1948 /// dividing the MVT::LAST_VALUETYPE by 32 and adding one.
1949 uint64_t CondCodeActions[ISD::SETCC_INVALID][(MVT::LAST_VALUETYPE / 32) + 1];
1951 ValueTypeActionImpl ValueTypeActions;
1953 typedef std::pair<LegalizeTypeAction, EVT> LegalizeKind;
1956 getTypeConversion(LLVMContext &Context, EVT VT) const {
1957 // If this is a simple type, use the ComputeRegisterProp mechanism.
1958 if (VT.isSimple()) {
1959 assert((unsigned)VT.getSimpleVT().SimpleTy <
1960 array_lengthof(TransformToType));
1961 EVT NVT = TransformToType[VT.getSimpleVT().SimpleTy];
1962 LegalizeTypeAction LA = ValueTypeActions.getTypeAction(VT.getSimpleVT());
1965 (!(NVT.isSimple() && LA != TypeLegal) ||
1966 ValueTypeActions.getTypeAction(NVT.getSimpleVT()) != TypePromoteInteger)
1967 && "Promote may not follow Expand or Promote");
1969 return LegalizeKind(LA, NVT);
1972 // Handle Extended Scalar Types.
1973 if (!VT.isVector()) {
1974 assert(VT.isInteger() && "Float types must be simple");
1975 unsigned BitSize = VT.getSizeInBits();
1976 // First promote to a power-of-two size, then expand if necessary.
1977 if (BitSize < 8 || !isPowerOf2_32(BitSize)) {
1978 EVT NVT = VT.getRoundIntegerType(Context);
1979 assert(NVT != VT && "Unable to round integer VT");
1980 LegalizeKind NextStep = getTypeConversion(Context, NVT);
1981 // Avoid multi-step promotion.
1982 if (NextStep.first == TypePromoteInteger) return NextStep;
1983 // Return rounded integer type.
1984 return LegalizeKind(TypePromoteInteger, NVT);
1987 return LegalizeKind(TypeExpandInteger,
1988 EVT::getIntegerVT(Context, VT.getSizeInBits()/2));
1991 // Handle vector types.
1992 unsigned NumElts = VT.getVectorNumElements();
1993 EVT EltVT = VT.getVectorElementType();
1995 // Vectors with only one element are always scalarized.
1997 return LegalizeKind(TypeScalarizeVector, EltVT);
1999 // Try to widen vector elements until a legal type is found.
2000 if (EltVT.isInteger()) {
2001 // Vectors with a number of elements that is not a power of two are always
2002 // widened, for example <3 x float> -> <4 x float>.
2003 if (!VT.isPow2VectorType()) {
2004 NumElts = (unsigned)NextPowerOf2(NumElts);
2005 EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts);
2006 return LegalizeKind(TypeWidenVector, NVT);
2009 // Examine the element type.
2010 LegalizeKind LK = getTypeConversion(Context, EltVT);
2012 // If type is to be expanded, split the vector.
2013 // <4 x i140> -> <2 x i140>
2014 if (LK.first == TypeExpandInteger)
2015 return LegalizeKind(TypeSplitVector,
2016 EVT::getVectorVT(Context, EltVT, NumElts / 2));
2018 // Promote the integer element types until a legal vector type is found
2019 // or until the element integer type is too big. If a legal type was not
2020 // found, fallback to the usual mechanism of widening/splitting the
2023 // Increase the bitwidth of the element to the next pow-of-two
2024 // (which is greater than 8 bits).
2025 EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits()
2026 ).getRoundIntegerType(Context);
2028 // Stop trying when getting a non-simple element type.
2029 // Note that vector elements may be greater than legal vector element
2030 // types. Example: X86 XMM registers hold 64bit element on 32bit systems.
2031 if (!EltVT.isSimple()) break;
2033 // Build a new vector type and check if it is legal.
2034 MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
2035 // Found a legal promoted vector type.
2036 if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal)
2037 return LegalizeKind(TypePromoteInteger,
2038 EVT::getVectorVT(Context, EltVT, NumElts));
2042 // Try to widen the vector until a legal type is found.
2043 // If there is no wider legal type, split the vector.
2045 // Round up to the next power of 2.
2046 NumElts = (unsigned)NextPowerOf2(NumElts);
2048 // If there is no simple vector type with this many elements then there
2049 // cannot be a larger legal vector type. Note that this assumes that
2050 // there are no skipped intermediate vector types in the simple types.
2051 if (!EltVT.isSimple()) break;
2052 MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
2053 if (LargerVector == MVT()) break;
2055 // If this type is legal then widen the vector.
2056 if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal)
2057 return LegalizeKind(TypeWidenVector, LargerVector);
2060 // Widen odd vectors to next power of two.
2061 if (!VT.isPow2VectorType()) {
2062 EVT NVT = VT.getPow2VectorType(Context);
2063 return LegalizeKind(TypeWidenVector, NVT);
2066 // Vectors with illegal element types are expanded.
2067 EVT NVT = EVT::getVectorVT(Context, EltVT, VT.getVectorNumElements() / 2);
2068 return LegalizeKind(TypeSplitVector, NVT);
2071 std::vector<std::pair<EVT, const TargetRegisterClass*> > AvailableRegClasses;
2073 /// TargetDAGCombineArray - Targets can specify ISD nodes that they would
2074 /// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(),
2075 /// which sets a bit in this array.
2077 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
2079 /// PromoteToType - For operations that must be promoted to a specific type,
2080 /// this holds the destination type. This map should be sparse, so don't hold
2083 /// Targets add entries to this map with AddPromotedToType(..), clients access
2084 /// this with getTypeToPromoteTo(..).
2085 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
2088 /// LibcallRoutineNames - Stores the name each libcall.
2090 const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
2092 /// CmpLibcallCCs - The ISD::CondCode that should be used to test the result
2093 /// of each of the comparison libcall against zero.
2094 ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
2096 /// LibcallCallingConvs - Stores the CallingConv that should be used for each
2098 CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
2101 /// When lowering \@llvm.memset this field specifies the maximum number of
2102 /// store operations that may be substituted for the call to memset. Targets
2103 /// must set this value based on the cost threshold for that target. Targets
2104 /// should assume that the memset will be done using as many of the largest
2105 /// store operations first, followed by smaller ones, if necessary, per
2106 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
2107 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
2108 /// store. This only applies to setting a constant array of a constant size.
2109 /// @brief Specify maximum number of store instructions per memset call.
2110 unsigned maxStoresPerMemset;
2112 /// Maximum number of stores operations that may be substituted for the call
2113 /// to memset, used for functions with OptSize attribute.
2114 unsigned maxStoresPerMemsetOptSize;
2116 /// When lowering \@llvm.memcpy this field specifies the maximum number of
2117 /// store operations that may be substituted for a call to memcpy. Targets
2118 /// must set this value based on the cost threshold for that target. Targets
2119 /// should assume that the memcpy will be done using as many of the largest
2120 /// store operations first, followed by smaller ones, if necessary, per
2121 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
2122 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
2123 /// and one 1-byte store. This only applies to copying a constant array of
2125 /// @brief Specify maximum bytes of store instructions per memcpy call.
2126 unsigned maxStoresPerMemcpy;
2128 /// Maximum number of store operations that may be substituted for a call
2129 /// to memcpy, used for functions with OptSize attribute.
2130 unsigned maxStoresPerMemcpyOptSize;
2132 /// When lowering \@llvm.memmove this field specifies the maximum number of
2133 /// store instructions that may be substituted for a call to memmove. Targets
2134 /// must set this value based on the cost threshold for that target. Targets
2135 /// should assume that the memmove will be done using as many of the largest
2136 /// store operations first, followed by smaller ones, if necessary, per
2137 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
2138 /// with 8-bit alignment would result in nine 1-byte stores. This only
2139 /// applies to copying a constant array of constant size.
2140 /// @brief Specify maximum bytes of store instructions per memmove call.
2141 unsigned maxStoresPerMemmove;
2143 /// Maximum number of store instructions that may be substituted for a call
2144 /// to memmove, used for functions with OpSize attribute.
2145 unsigned maxStoresPerMemmoveOptSize;
2147 /// This field specifies whether the target can benefit from code placement
2149 bool benefitFromCodePlacementOpt;
2151 /// predictableSelectIsExpensive - Tells the code generator that select is
2152 /// more expensive than a branch if the branch is usually predicted right.
2153 bool predictableSelectIsExpensive;
2156 /// isLegalRC - Return true if the value types that can be represented by the
2157 /// specified register class are all legal.
2158 bool isLegalRC(const TargetRegisterClass *RC) const;
2161 /// GetReturnInfo - Given an LLVM IR type and return type attributes,
2162 /// compute the return value EVTs and flags, and optionally also
2163 /// the offsets, if the return value is being lowered to memory.
2164 void GetReturnInfo(Type* ReturnType, Attributes attr,
2165 SmallVectorImpl<ISD::OutputArg> &Outs,
2166 const TargetLowering &TLI);
2168 } // end llvm namespace