TargetLowering.h revision 00cc494595ea848438012eec6c89b174305070d7
1//===-- llvm/Target/TargetLowering.h - Target Lowering Info -----*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file describes how to lower LLVM code to machine code.  This has two
11// main components:
12//
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.
16//
17// In addition it has a few other components, like information about FP
18// immediates.
19//
20//===----------------------------------------------------------------------===//
21
22#ifndef LLVM_TARGET_TARGETLOWERING_H
23#define LLVM_TARGET_TARGETLOWERING_H
24
25#include "llvm/Type.h"
26#include "llvm/CodeGen/SelectionDAGNodes.h"
27#include "llvm/CodeGen/ValueTypes.h"
28#include "llvm/Support/DataTypes.h"
29#include <vector>
30
31namespace llvm {
32  class Value;
33  class Function;
34  class TargetMachine;
35  class TargetData;
36  class TargetRegisterClass;
37  class SDNode;
38  class SDOperand;
39  class SelectionDAG;
40  class MachineBasicBlock;
41  class MachineInstr;
42
43//===----------------------------------------------------------------------===//
44/// TargetLowering - This class defines information used to lower LLVM code to
45/// legal SelectionDAG operators that the target instruction selector can accept
46/// natively.
47///
48/// This class also defines callbacks that targets must implement to lower
49/// target-specific constructs to SelectionDAG operators.
50///
51class TargetLowering {
52public:
53  /// LegalizeAction - This enum indicates whether operations are valid for a
54  /// target, and if not, what action should be used to make them valid.
55  enum LegalizeAction {
56    Legal,      // The target natively supports this operation.
57    Promote,    // This operation should be executed in a larger type.
58    Expand,     // Try to expand this to other ops, otherwise use a libcall.
59    Custom      // Use the LowerOperation hook to implement custom lowering.
60  };
61
62  enum OutOfRangeShiftAmount {
63    Undefined,  // Oversized shift amounts are undefined (default).
64    Mask,       // Shift amounts are auto masked (anded) to value size.
65    Extend      // Oversized shift pulls in zeros or sign bits.
66  };
67
68  enum SetCCResultValue {
69    UndefinedSetCCResult,          // SetCC returns a garbage/unknown extend.
70    ZeroOrOneSetCCResult,          // SetCC returns a zero extended result.
71    ZeroOrNegativeOneSetCCResult   // SetCC returns a sign extended result.
72  };
73
74  enum SchedPreference {
75    SchedulingForLatency,          // Scheduling for shortest total latency.
76    SchedulingForRegPressure       // Scheduling for lowest register pressure.
77  };
78
79  TargetLowering(TargetMachine &TM);
80  virtual ~TargetLowering();
81
82  TargetMachine &getTargetMachine() const { return TM; }
83  const TargetData &getTargetData() const { return TD; }
84
85  bool isLittleEndian() const { return IsLittleEndian; }
86  MVT::ValueType getPointerTy() const { return PointerTy; }
87  MVT::ValueType getShiftAmountTy() const { return ShiftAmountTy; }
88  OutOfRangeShiftAmount getShiftAmountFlavor() const {return ShiftAmtHandling; }
89
90  /// isSetCCExpensive - Return true if the setcc operation is expensive for
91  /// this target.
92  bool isSetCCExpensive() const { return SetCCIsExpensive; }
93
94  /// isIntDivCheap() - Return true if integer divide is usually cheaper than
95  /// a sequence of several shifts, adds, and multiplies for this target.
96  bool isIntDivCheap() const { return IntDivIsCheap; }
97
98  /// isPow2DivCheap() - Return true if pow2 div is cheaper than a chain of
99  /// srl/add/sra.
100  bool isPow2DivCheap() const { return Pow2DivIsCheap; }
101
102  /// getSetCCResultTy - Return the ValueType of the result of setcc operations.
103  ///
104  MVT::ValueType getSetCCResultTy() const { return SetCCResultTy; }
105
106  /// getSetCCResultContents - For targets without boolean registers, this flag
107  /// returns information about the contents of the high-bits in the setcc
108  /// result register.
109  SetCCResultValue getSetCCResultContents() const { return SetCCResultContents;}
110
111  /// getSchedulingPreference - Return target scheduling preference.
112  SchedPreference getSchedulingPreference() const {
113    return SchedPreferenceInfo;
114  }
115
116  /// getRegClassFor - Return the register class that should be used for the
117  /// specified value type.  This may only be called on legal types.
118  TargetRegisterClass *getRegClassFor(MVT::ValueType VT) const {
119    TargetRegisterClass *RC = RegClassForVT[VT];
120    assert(RC && "This value type is not natively supported!");
121    return RC;
122  }
123
124  /// isTypeLegal - Return true if the target has native support for the
125  /// specified value type.  This means that it has a register that directly
126  /// holds it without promotions or expansions.
127  bool isTypeLegal(MVT::ValueType VT) const {
128    return RegClassForVT[VT] != 0;
129  }
130
131  class ValueTypeActionImpl {
132    /// ValueTypeActions - This is a bitvector that contains two bits for each
133    /// value type, where the two bits correspond to the LegalizeAction enum.
134    /// This can be queried with "getTypeAction(VT)".
135    uint32_t ValueTypeActions[2];
136  public:
137    ValueTypeActionImpl() {
138      ValueTypeActions[0] = ValueTypeActions[1] = 0;
139    }
140    ValueTypeActionImpl(const ValueTypeActionImpl &RHS) {
141      ValueTypeActions[0] = RHS.ValueTypeActions[0];
142      ValueTypeActions[1] = RHS.ValueTypeActions[1];
143    }
144
145    LegalizeAction getTypeAction(MVT::ValueType VT) const {
146      return (LegalizeAction)((ValueTypeActions[VT>>4] >> ((2*VT) & 31)) & 3);
147    }
148    void setTypeAction(MVT::ValueType VT, LegalizeAction Action) {
149      assert(unsigned(VT >> 4) <
150             sizeof(ValueTypeActions)/sizeof(ValueTypeActions[0]));
151      ValueTypeActions[VT>>4] |= Action << ((VT*2) & 31);
152    }
153  };
154
155  const ValueTypeActionImpl &getValueTypeActions() const {
156    return ValueTypeActions;
157  }
158
159  /// getTypeAction - Return how we should legalize values of this type, either
160  /// it is already legal (return 'Legal') or we need to promote it to a larger
161  /// type (return 'Promote'), or we need to expand it into multiple registers
162  /// of smaller integer type (return 'Expand').  'Custom' is not an option.
163  LegalizeAction getTypeAction(MVT::ValueType VT) const {
164    return ValueTypeActions.getTypeAction(VT);
165  }
166
167  /// getTypeToTransformTo - For types supported by the target, this is an
168  /// identity function.  For types that must be promoted to larger types, this
169  /// returns the larger type to promote to.  For types that are larger than the
170  /// largest integer register, this contains one step in the expansion to get
171  /// to the smaller register.
172  MVT::ValueType getTypeToTransformTo(MVT::ValueType VT) const {
173    return TransformToType[VT];
174  }
175
176  /// getPackedTypeBreakdown - Packed types are broken down into some number of
177  /// legal scalar types.  For example, <8 x float> maps to 2 MVT::v2f32 values
178  /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
179  /// Similarly, <2 x long> turns into 4 MVT::i32 values with both PPC and X86.
180  ///
181  /// This method returns the number and type of the resultant breakdown.
182  ///
183  MVT::ValueType getPackedTypeBreakdown(const PackedType *PTy,
184                                        unsigned &NE) const;
185
186  typedef std::vector<double>::const_iterator legal_fpimm_iterator;
187  legal_fpimm_iterator legal_fpimm_begin() const {
188    return LegalFPImmediates.begin();
189  }
190  legal_fpimm_iterator legal_fpimm_end() const {
191    return LegalFPImmediates.end();
192  }
193
194  /// getOperationAction - Return how this operation should be treated: either
195  /// it is legal, needs to be promoted to a larger size, needs to be
196  /// expanded to some other code sequence, or the target has a custom expander
197  /// for it.
198  LegalizeAction getOperationAction(unsigned Op, MVT::ValueType VT) const {
199    return (LegalizeAction)((OpActions[Op] >> (2*VT)) & 3);
200  }
201
202  /// isOperationLegal - Return true if the specified operation is legal on this
203  /// target.
204  bool isOperationLegal(unsigned Op, MVT::ValueType VT) const {
205    return getOperationAction(Op, VT) == Legal ||
206           getOperationAction(Op, VT) == Custom;
207  }
208
209
210  /// isVectorShuffleLegal - Return true if a vector shuffle is legal with the
211  /// specified mask and type.  Targets can specify exactly which masks they
212  /// support and the code generator is tasked with not creating illegal masks.
213  bool isShuffleLegal(MVT::ValueType VT, SDOperand Mask) const {
214    return isOperationLegal(ISD::VECTOR_SHUFFLE, VT) &&
215           isShuffleMaskLegal(Mask, VT);
216  }
217
218  /// getTypeToPromoteTo - If the action for this operation is to promote, this
219  /// method returns the ValueType to promote to.
220  MVT::ValueType getTypeToPromoteTo(unsigned Op, MVT::ValueType VT) const {
221    assert(getOperationAction(Op, VT) == Promote &&
222           "This operation isn't promoted!");
223    MVT::ValueType NVT = VT;
224    do {
225      NVT = (MVT::ValueType)(NVT+1);
226      assert(MVT::isInteger(NVT) == MVT::isInteger(VT) && NVT != MVT::isVoid &&
227             "Didn't find type to promote to!");
228    } while (!isTypeLegal(NVT) ||
229              getOperationAction(Op, NVT) == Promote);
230    return NVT;
231  }
232
233  /// getValueType - Return the MVT::ValueType corresponding to this LLVM type.
234  /// This is fixed by the LLVM operations except for the pointer size.
235  MVT::ValueType getValueType(const Type *Ty) const {
236    switch (Ty->getTypeID()) {
237    default: assert(0 && "Unknown type!");
238    case Type::VoidTyID:    return MVT::isVoid;
239    case Type::BoolTyID:    return MVT::i1;
240    case Type::UByteTyID:
241    case Type::SByteTyID:   return MVT::i8;
242    case Type::ShortTyID:
243    case Type::UShortTyID:  return MVT::i16;
244    case Type::IntTyID:
245    case Type::UIntTyID:    return MVT::i32;
246    case Type::LongTyID:
247    case Type::ULongTyID:   return MVT::i64;
248    case Type::FloatTyID:   return MVT::f32;
249    case Type::DoubleTyID:  return MVT::f64;
250    case Type::PointerTyID: return PointerTy;
251    case Type::PackedTyID:  return MVT::Vector;
252    }
253  }
254
255  /// getNumElements - Return the number of registers that this ValueType will
256  /// eventually require.  This is always one for all non-integer types, is
257  /// one for any types promoted to live in larger registers, but may be more
258  /// than one for types (like i64) that are split into pieces.
259  unsigned getNumElements(MVT::ValueType VT) const {
260    return NumElementsForVT[VT];
261  }
262
263  /// hasTargetDAGCombine - If true, the target has custom DAG combine
264  /// transformations that it can perform for the specified node.
265  bool hasTargetDAGCombine(ISD::NodeType NT) const {
266    return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
267  }
268
269  /// This function returns the maximum number of store operations permitted
270  /// to replace a call to llvm.memset. The value is set by the target at the
271  /// performance threshold for such a replacement.
272  /// @brief Get maximum # of store operations permitted for llvm.memset
273  unsigned getMaxStoresPerMemset() const { return maxStoresPerMemset; }
274
275  /// This function returns the maximum number of store operations permitted
276  /// to replace a call to llvm.memcpy. The value is set by the target at the
277  /// performance threshold for such a replacement.
278  /// @brief Get maximum # of store operations permitted for llvm.memcpy
279  unsigned getMaxStoresPerMemcpy() const { return maxStoresPerMemcpy; }
280
281  /// This function returns the maximum number of store operations permitted
282  /// to replace a call to llvm.memmove. The value is set by the target at the
283  /// performance threshold for such a replacement.
284  /// @brief Get maximum # of store operations permitted for llvm.memmove
285  unsigned getMaxStoresPerMemmove() const { return maxStoresPerMemmove; }
286
287  /// This function returns true if the target allows unaligned memory accesses.
288  /// This is used, for example, in situations where an array copy/move/set is
289  /// converted to a sequence of store operations. It's use helps to ensure that
290  /// such replacements don't generate code that causes an alignment error
291  /// (trap) on the target machine.
292  /// @brief Determine if the target supports unaligned memory accesses.
293  bool allowsUnalignedMemoryAccesses() const {
294    return allowUnalignedMemoryAccesses;
295  }
296
297  /// usesUnderscoreSetJmpLongJmp - Determine if we should use _setjmp or setjmp
298  /// to implement llvm.setjmp.
299  bool usesUnderscoreSetJmpLongJmp() const {
300    return UseUnderscoreSetJmpLongJmp;
301  }
302
303  /// getStackPointerRegisterToSaveRestore - If a physical register, this
304  /// specifies the register that llvm.savestack/llvm.restorestack should save
305  /// and restore.
306  unsigned getStackPointerRegisterToSaveRestore() const {
307    return StackPointerRegisterToSaveRestore;
308  }
309
310  //===--------------------------------------------------------------------===//
311  // TargetLowering Optimization Methods
312  //
313
314  /// TargetLoweringOpt - A convenience struct that encapsulates a DAG, and two
315  /// SDOperands for returning information from TargetLowering to its clients
316  /// that want to combine
317  struct TargetLoweringOpt {
318    SelectionDAG &DAG;
319    SDOperand Old;
320    SDOperand New;
321
322    TargetLoweringOpt(SelectionDAG &InDAG) : DAG(InDAG) {}
323
324    bool CombineTo(SDOperand O, SDOperand N) {
325      Old = O;
326      New = N;
327      return true;
328    }
329
330    /// ShrinkDemandedConstant - Check to see if the specified operand of the
331    /// specified instruction is a constant integer.  If so, check to see if there
332    /// are any bits set in the constant that are not demanded.  If so, shrink the
333    /// constant and return true.
334    bool ShrinkDemandedConstant(SDOperand Op, uint64_t Demanded);
335  };
336
337  /// MaskedValueIsZero - Return true if 'Op & Mask' is known to be zero.  We
338  /// use this predicate to simplify operations downstream.  Op and Mask are
339  /// known to be the same type.
340  bool MaskedValueIsZero(SDOperand Op, uint64_t Mask, unsigned Depth = 0)
341    const;
342
343  /// ComputeMaskedBits - Determine which of the bits specified in Mask are
344  /// known to be either zero or one and return them in the KnownZero/KnownOne
345  /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
346  /// processing.  Targets can implement the computeMaskedBitsForTargetNode
347  /// method, to allow target nodes to be understood.
348  void ComputeMaskedBits(SDOperand Op, uint64_t Mask, uint64_t &KnownZero,
349                         uint64_t &KnownOne, unsigned Depth = 0) const;
350
351  /// SimplifyDemandedBits - Look at Op.  At this point, we know that only the
352  /// DemandedMask bits of the result of Op are ever used downstream.  If we can
353  /// use this information to simplify Op, create a new simplified DAG node and
354  /// return true, returning the original and new nodes in Old and New.
355  /// Otherwise, analyze the expression and return a mask of KnownOne and
356  /// KnownZero bits for the expression (used to simplify the caller).
357  /// The KnownZero/One bits may only be accurate for those bits in the
358  /// DemandedMask.
359  bool SimplifyDemandedBits(SDOperand Op, uint64_t DemandedMask,
360                            uint64_t &KnownZero, uint64_t &KnownOne,
361                            TargetLoweringOpt &TLO, unsigned Depth = 0) const;
362
363  /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
364  /// Mask are known to be either zero or one and return them in the
365  /// KnownZero/KnownOne bitsets.
366  virtual void computeMaskedBitsForTargetNode(const SDOperand Op,
367                                              uint64_t Mask,
368                                              uint64_t &KnownZero,
369                                              uint64_t &KnownOne,
370                                              unsigned Depth = 0) const;
371
372  struct DAGCombinerInfo {
373    void *DC;  // The DAG Combiner object.
374    bool BeforeLegalize;
375  public:
376    SelectionDAG &DAG;
377
378    DAGCombinerInfo(SelectionDAG &dag, bool bl, void *dc)
379      : DC(dc), BeforeLegalize(bl), DAG(dag) {}
380
381    bool isBeforeLegalize() const { return BeforeLegalize; }
382
383    void AddToWorklist(SDNode *N);
384    SDOperand CombineTo(SDNode *N, const std::vector<SDOperand> &To);
385    SDOperand CombineTo(SDNode *N, SDOperand Res);
386    SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1);
387  };
388
389  /// PerformDAGCombine - This method will be invoked for all target nodes and
390  /// for any target-independent nodes that the target has registered with
391  /// invoke it for.
392  ///
393  /// The semantics are as follows:
394  /// Return Value:
395  ///   SDOperand.Val == 0   - No change was made
396  ///   SDOperand.Val == N   - N was replaced, is dead, and is already handled.
397  ///   otherwise            - N should be replaced by the returned Operand.
398  ///
399  /// In addition, methods provided by DAGCombinerInfo may be used to perform
400  /// more complex transformations.
401  ///
402  virtual SDOperand PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
403
404  //===--------------------------------------------------------------------===//
405  // TargetLowering Configuration Methods - These methods should be invoked by
406  // the derived class constructor to configure this object for the target.
407  //
408
409protected:
410
411  /// setShiftAmountType - Describe the type that should be used for shift
412  /// amounts.  This type defaults to the pointer type.
413  void setShiftAmountType(MVT::ValueType VT) { ShiftAmountTy = VT; }
414
415  /// setSetCCResultType - Describe the type that shoudl be used as the result
416  /// of a setcc operation.  This defaults to the pointer type.
417  void setSetCCResultType(MVT::ValueType VT) { SetCCResultTy = VT; }
418
419  /// setSetCCResultContents - Specify how the target extends the result of a
420  /// setcc operation in a register.
421  void setSetCCResultContents(SetCCResultValue Ty) { SetCCResultContents = Ty; }
422
423  /// setSchedulingPreference - Specify the target scheduling preference.
424  void setSchedulingPreference(SchedPreference Pref) {
425    SchedPreferenceInfo = Pref;
426  }
427
428  /// setShiftAmountFlavor - Describe how the target handles out of range shift
429  /// amounts.
430  void setShiftAmountFlavor(OutOfRangeShiftAmount OORSA) {
431    ShiftAmtHandling = OORSA;
432  }
433
434  /// setUseUnderscoreSetJmpLongJmp - Indicate whether this target prefers to
435  /// use _setjmp and _longjmp to or implement llvm.setjmp/llvm.longjmp or
436  /// the non _ versions.  Defaults to false.
437  void setUseUnderscoreSetJmpLongJmp(bool Val) {
438    UseUnderscoreSetJmpLongJmp = Val;
439  }
440
441  /// setStackPointerRegisterToSaveRestore - If set to a physical register, this
442  /// specifies the register that llvm.savestack/llvm.restorestack should save
443  /// and restore.
444  void setStackPointerRegisterToSaveRestore(unsigned R) {
445    StackPointerRegisterToSaveRestore = R;
446  }
447
448  /// setSetCCIxExpensive - This is a short term hack for targets that codegen
449  /// setcc as a conditional branch.  This encourages the code generator to fold
450  /// setcc operations into other operations if possible.
451  void setSetCCIsExpensive() { SetCCIsExpensive = true; }
452
453  /// setIntDivIsCheap - Tells the code generator that integer divide is
454  /// expensive, and if possible, should be replaced by an alternate sequence
455  /// of instructions not containing an integer divide.
456  void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
457
458  /// setPow2DivIsCheap - Tells the code generator that it shouldn't generate
459  /// srl/add/sra for a signed divide by power of two, and let the target handle
460  /// it.
461  void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
462
463  /// addRegisterClass - Add the specified register class as an available
464  /// regclass for the specified value type.  This indicates the selector can
465  /// handle values of that class natively.
466  void addRegisterClass(MVT::ValueType VT, TargetRegisterClass *RC) {
467    AvailableRegClasses.push_back(std::make_pair(VT, RC));
468    RegClassForVT[VT] = RC;
469  }
470
471  /// computeRegisterProperties - Once all of the register classes are added,
472  /// this allows us to compute derived properties we expose.
473  void computeRegisterProperties();
474
475  /// setOperationAction - Indicate that the specified operation does not work
476  /// with the specified type and indicate what to do about it.
477  void setOperationAction(unsigned Op, MVT::ValueType VT,
478                          LegalizeAction Action) {
479    assert(VT < 32 && Op < sizeof(OpActions)/sizeof(OpActions[0]) &&
480           "Table isn't big enough!");
481    OpActions[Op] &= ~(3ULL << VT*2);
482    OpActions[Op] |= (uint64_t)Action << VT*2;
483  }
484
485  /// addLegalFPImmediate - Indicate that this target can instruction select
486  /// the specified FP immediate natively.
487  void addLegalFPImmediate(double Imm) {
488    LegalFPImmediates.push_back(Imm);
489  }
490
491  /// setTargetDAGCombine - Targets should invoke this method for each target
492  /// independent node that they want to provide a custom DAG combiner for by
493  /// implementing the PerformDAGCombine virtual method.
494  void setTargetDAGCombine(ISD::NodeType NT) {
495    TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
496  }
497
498  /// isShuffleMaskLegal - Targets can use this to indicate that they only
499  /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
500  /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
501  /// are assumed to be legal.
502  virtual bool isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
503    return true;
504  }
505
506public:
507
508  //===--------------------------------------------------------------------===//
509  // Lowering methods - These methods must be implemented by targets so that
510  // the SelectionDAGLowering code knows how to lower these.
511  //
512
513  /// LowerArguments - This hook must be implemented to indicate how we should
514  /// lower the arguments for the specified function, into the specified DAG.
515  virtual std::vector<SDOperand>
516  LowerArguments(Function &F, SelectionDAG &DAG) = 0;
517
518  /// LowerCallTo - This hook lowers an abstract call to a function into an
519  /// actual call.  This returns a pair of operands.  The first element is the
520  /// return value for the function (if RetTy is not VoidTy).  The second
521  /// element is the outgoing token chain.
522  typedef std::vector<std::pair<SDOperand, const Type*> > ArgListTy;
523  virtual std::pair<SDOperand, SDOperand>
524  LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
525              unsigned CallingConv, bool isTailCall, SDOperand Callee,
526              ArgListTy &Args, SelectionDAG &DAG) = 0;
527
528  /// LowerFrameReturnAddress - This hook lowers a call to llvm.returnaddress or
529  /// llvm.frameaddress (depending on the value of the first argument).  The
530  /// return values are the result pointer and the resultant token chain.  If
531  /// not implemented, both of these intrinsics will return null.
532  virtual std::pair<SDOperand, SDOperand>
533  LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain, unsigned Depth,
534                          SelectionDAG &DAG);
535
536  /// LowerOperation - This callback is invoked for operations that are
537  /// unsupported by the target, which are registered to use 'custom' lowering,
538  /// and whose defined values are all legal.
539  /// If the target has no operations that require custom lowering, it need not
540  /// implement this.  The default implementation of this aborts.
541  virtual SDOperand LowerOperation(SDOperand Op, SelectionDAG &DAG);
542
543  /// CustomPromoteOperation - This callback is invoked for operations that are
544  /// unsupported by the target, are registered to use 'custom' lowering, and
545  /// whose type needs to be promoted.
546  virtual SDOperand CustomPromoteOperation(SDOperand Op, SelectionDAG &DAG);
547
548  /// getTargetNodeName() - This method returns the name of a target specific
549  /// DAG node.
550  virtual const char *getTargetNodeName(unsigned Opcode) const;
551
552  //===--------------------------------------------------------------------===//
553  // Inline Asm Support hooks
554  //
555
556  enum ConstraintType {
557    C_Register,            // Constraint represents a single register.
558    C_RegisterClass,       // Constraint represents one or more registers.
559    C_Memory,              // Memory constraint.
560    C_Other,               // Something else.
561    C_Unknown              // Unsupported constraint.
562  };
563
564  /// getConstraintType - Given a constraint letter, return the type of
565  /// constraint it is for this target.
566  virtual ConstraintType getConstraintType(char ConstraintLetter) const;
567
568
569  /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
570  /// return a list of registers that can be used to satisfy the constraint.
571  /// This should only be used for C_RegisterClass constraints.
572  virtual std::vector<unsigned>
573  getRegClassForInlineAsmConstraint(const std::string &Constraint,
574                                    MVT::ValueType VT) const;
575
576  /// getRegForInlineAsmConstraint - Given a physical register constraint (e.g.
577  /// {edx}), return the register number and the register class for the
578  /// register.  This should only be used for C_Register constraints.  On error,
579  /// this returns a register number of 0.
580  virtual std::pair<unsigned, const TargetRegisterClass*>
581    getRegForInlineAsmConstraint(const std::string &Constraint,
582                                 MVT::ValueType VT) const;
583
584
585  /// isOperandValidForConstraint - Return true if the specified SDOperand is
586  /// valid for the specified target constraint letter.
587  virtual bool isOperandValidForConstraint(SDOperand Op, char ConstraintLetter);
588
589  //===--------------------------------------------------------------------===//
590  // Scheduler hooks
591  //
592
593  // InsertAtEndOfBasicBlock - This method should be implemented by targets that
594  // mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
595  // instructions are special in various ways, which require special support to
596  // insert.  The specified MachineInstr is created but not inserted into any
597  // basic blocks, and the scheduler passes ownership of it to this method.
598  virtual MachineBasicBlock *InsertAtEndOfBasicBlock(MachineInstr *MI,
599                                                     MachineBasicBlock *MBB);
600
601  //===--------------------------------------------------------------------===//
602  // Loop Strength Reduction hooks
603  //
604
605  /// isLegalAddressImmediate - Return true if the integer value or GlobalValue
606  /// can be used as the offset of the target addressing mode.
607  virtual bool isLegalAddressImmediate(int64_t V) const;
608  virtual bool isLegalAddressImmediate(GlobalValue *GV) const;
609
610  typedef std::vector<unsigned>::const_iterator legal_am_scale_iterator;
611  legal_am_scale_iterator legal_am_scale_begin() const {
612    return LegalAddressScales.begin();
613  }
614  legal_am_scale_iterator legal_am_scale_end() const {
615    return LegalAddressScales.end();
616  }
617
618protected:
619  /// addLegalAddressScale - Add a integer (> 1) value which can be used as
620  /// scale in the target addressing mode. Note: the ordering matters so the
621  /// least efficient ones should be entered first.
622  void addLegalAddressScale(unsigned Scale) {
623    LegalAddressScales.push_back(Scale);
624  }
625
626private:
627  std::vector<unsigned> LegalAddressScales;
628
629private:
630  TargetMachine &TM;
631  const TargetData &TD;
632
633  /// IsLittleEndian - True if this is a little endian target.
634  ///
635  bool IsLittleEndian;
636
637  /// PointerTy - The type to use for pointers, usually i32 or i64.
638  ///
639  MVT::ValueType PointerTy;
640
641  /// ShiftAmountTy - The type to use for shift amounts, usually i8 or whatever
642  /// PointerTy is.
643  MVT::ValueType ShiftAmountTy;
644
645  OutOfRangeShiftAmount ShiftAmtHandling;
646
647  /// SetCCIsExpensive - This is a short term hack for targets that codegen
648  /// setcc as a conditional branch.  This encourages the code generator to fold
649  /// setcc operations into other operations if possible.
650  bool SetCCIsExpensive;
651
652  /// IntDivIsCheap - Tells the code generator not to expand integer divides by
653  /// constants into a sequence of muls, adds, and shifts.  This is a hack until
654  /// a real cost model is in place.  If we ever optimize for size, this will be
655  /// set to true unconditionally.
656  bool IntDivIsCheap;
657
658  /// Pow2DivIsCheap - Tells the code generator that it shouldn't generate
659  /// srl/add/sra for a signed divide by power of two, and let the target handle
660  /// it.
661  bool Pow2DivIsCheap;
662
663  /// SetCCResultTy - The type that SetCC operations use.  This defaults to the
664  /// PointerTy.
665  MVT::ValueType SetCCResultTy;
666
667  /// SetCCResultContents - Information about the contents of the high-bits in
668  /// the result of a setcc comparison operation.
669  SetCCResultValue SetCCResultContents;
670
671  /// SchedPreferenceInfo - The target scheduling preference: shortest possible
672  /// total cycles or lowest register usage.
673  SchedPreference SchedPreferenceInfo;
674
675  /// UseUnderscoreSetJmpLongJmp - This target prefers to use _setjmp and
676  /// _longjmp to implement llvm.setjmp/llvm.longjmp.  Defaults to false.
677  bool UseUnderscoreSetJmpLongJmp;
678
679  /// StackPointerRegisterToSaveRestore - If set to a physical register, this
680  /// specifies the register that llvm.savestack/llvm.restorestack should save
681  /// and restore.
682  unsigned StackPointerRegisterToSaveRestore;
683
684  /// RegClassForVT - This indicates the default register class to use for
685  /// each ValueType the target supports natively.
686  TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
687  unsigned char NumElementsForVT[MVT::LAST_VALUETYPE];
688
689  /// TransformToType - For any value types we are promoting or expanding, this
690  /// contains the value type that we are changing to.  For Expanded types, this
691  /// contains one step of the expand (e.g. i64 -> i32), even if there are
692  /// multiple steps required (e.g. i64 -> i16).  For types natively supported
693  /// by the system, this holds the same type (e.g. i32 -> i32).
694  MVT::ValueType TransformToType[MVT::LAST_VALUETYPE];
695
696  /// OpActions - For each operation and each value type, keep a LegalizeAction
697  /// that indicates how instruction selection should deal with the operation.
698  /// Most operations are Legal (aka, supported natively by the target), but
699  /// operations that are not should be described.  Note that operations on
700  /// non-legal value types are not described here.
701  uint64_t OpActions[156];
702
703  ValueTypeActionImpl ValueTypeActions;
704
705  std::vector<double> LegalFPImmediates;
706
707  std::vector<std::pair<MVT::ValueType,
708                        TargetRegisterClass*> > AvailableRegClasses;
709
710  /// TargetDAGCombineArray - Targets can specify ISD nodes that they would
711  /// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(),
712  /// which sets a bit in this array.
713  unsigned char TargetDAGCombineArray[156/(sizeof(unsigned char)*8)];
714
715protected:
716  /// When lowering %llvm.memset this field specifies the maximum number of
717  /// store operations that may be substituted for the call to memset. Targets
718  /// must set this value based on the cost threshold for that target. Targets
719  /// should assume that the memset will be done using as many of the largest
720  /// store operations first, followed by smaller ones, if necessary, per
721  /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
722  /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
723  /// store.  This only applies to setting a constant array of a constant size.
724  /// @brief Specify maximum number of store instructions per memset call.
725  unsigned maxStoresPerMemset;
726
727  /// When lowering %llvm.memcpy this field specifies the maximum number of
728  /// store operations that may be substituted for a call to memcpy. Targets
729  /// must set this value based on the cost threshold for that target. Targets
730  /// should assume that the memcpy will be done using as many of the largest
731  /// store operations first, followed by smaller ones, if necessary, per
732  /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
733  /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
734  /// and one 1-byte store. This only applies to copying a constant array of
735  /// constant size.
736  /// @brief Specify maximum bytes of store instructions per memcpy call.
737  unsigned maxStoresPerMemcpy;
738
739  /// When lowering %llvm.memmove this field specifies the maximum number of
740  /// store instructions that may be substituted for a call to memmove. Targets
741  /// must set this value based on the cost threshold for that target. Targets
742  /// should assume that the memmove will be done using as many of the largest
743  /// store operations first, followed by smaller ones, if necessary, per
744  /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
745  /// with 8-bit alignment would result in nine 1-byte stores.  This only
746  /// applies to copying a constant array of constant size.
747  /// @brief Specify maximum bytes of store instructions per memmove call.
748  unsigned maxStoresPerMemmove;
749
750  /// This field specifies whether the target machine permits unaligned memory
751  /// accesses.  This is used, for example, to determine the size of store
752  /// operations when copying small arrays and other similar tasks.
753  /// @brief Indicate whether the target permits unaligned memory accesses.
754  bool allowUnalignedMemoryAccesses;
755};
756} // end llvm namespace
757
758#endif
759