TargetLowering.h revision e00a8a2a2e11a37fd1ddf2504bd22d225d0994d0
1//===-- llvm/Target/TargetLowering.h - Target Lowering Info -----*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// 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/Constants.h"
26#include "llvm/InlineAsm.h"
27#include "llvm/CodeGen/SelectionDAGNodes.h"
28#include "llvm/CodeGen/RuntimeLibcalls.h"
29#include "llvm/ADT/APFloat.h"
30#include "llvm/ADT/STLExtras.h"
31#include <map>
32#include <vector>
33
34namespace llvm {
35  class Function;
36  class FastISel;
37  class MachineBasicBlock;
38  class MachineFunction;
39  class MachineFrameInfo;
40  class MachineInstr;
41  class SDNode;
42  class SDValue;
43  class SelectionDAG;
44  class TargetData;
45  class TargetMachine;
46  class TargetRegisterClass;
47  class TargetSubtarget;
48  class Value;
49  class VectorType;
50
51//===----------------------------------------------------------------------===//
52/// TargetLowering - This class defines information used to lower LLVM code to
53/// legal SelectionDAG operators that the target instruction selector can accept
54/// natively.
55///
56/// This class also defines callbacks that targets must implement to lower
57/// target-specific constructs to SelectionDAG operators.
58///
59class TargetLowering {
60public:
61  /// LegalizeAction - This enum indicates whether operations are valid for a
62  /// target, and if not, what action should be used to make them valid.
63  enum LegalizeAction {
64    Legal,      // The target natively supports this operation.
65    Promote,    // This operation should be executed in a larger type.
66    Expand,     // Try to expand this to other ops, otherwise use a libcall.
67    Custom      // Use the LowerOperation hook to implement custom lowering.
68  };
69
70  enum OutOfRangeShiftAmount {
71    Undefined,  // Oversized shift amounts are undefined (default).
72    Mask,       // Shift amounts are auto masked (anded) to value size.
73    Extend      // Oversized shift pulls in zeros or sign bits.
74  };
75
76  enum SetCCResultValue {
77    UndefinedSetCCResult,          // SetCC returns a garbage/unknown extend.
78    ZeroOrOneSetCCResult,          // SetCC returns a zero extended result.
79    ZeroOrNegativeOneSetCCResult   // SetCC returns a sign extended result.
80  };
81
82  enum SchedPreference {
83    SchedulingForLatency,          // Scheduling for shortest total latency.
84    SchedulingForRegPressure       // Scheduling for lowest register pressure.
85  };
86
87  explicit TargetLowering(TargetMachine &TM);
88  virtual ~TargetLowering();
89
90  TargetMachine &getTargetMachine() const { return TM; }
91  const TargetData *getTargetData() const { return TD; }
92
93  bool isBigEndian() const { return !IsLittleEndian; }
94  bool isLittleEndian() const { return IsLittleEndian; }
95  MVT getPointerTy() const { return PointerTy; }
96  MVT getShiftAmountTy() const { return ShiftAmountTy; }
97  OutOfRangeShiftAmount getShiftAmountFlavor() const {return ShiftAmtHandling; }
98
99  /// usesGlobalOffsetTable - Return true if this target uses a GOT for PIC
100  /// codegen.
101  bool usesGlobalOffsetTable() const { return UsesGlobalOffsetTable; }
102
103  /// isSelectExpensive - Return true if the select operation is expensive for
104  /// this target.
105  bool isSelectExpensive() const { return SelectIsExpensive; }
106
107  /// isIntDivCheap() - Return true if integer divide is usually cheaper than
108  /// a sequence of several shifts, adds, and multiplies for this target.
109  bool isIntDivCheap() const { return IntDivIsCheap; }
110
111  /// isPow2DivCheap() - Return true if pow2 div is cheaper than a chain of
112  /// srl/add/sra.
113  bool isPow2DivCheap() const { return Pow2DivIsCheap; }
114
115  /// getSetCCResultType - Return the ValueType of the result of setcc
116  /// operations.
117  virtual MVT getSetCCResultType(const SDValue &) const;
118
119  /// getSetCCResultContents - For targets without boolean registers, this flag
120  /// returns information about the contents of the high-bits in the setcc
121  /// result register.
122  SetCCResultValue getSetCCResultContents() const { return SetCCResultContents;}
123
124  /// getSchedulingPreference - Return target scheduling preference.
125  SchedPreference getSchedulingPreference() const {
126    return SchedPreferenceInfo;
127  }
128
129  /// getRegClassFor - Return the register class that should be used for the
130  /// specified value type.  This may only be called on legal types.
131  TargetRegisterClass *getRegClassFor(MVT VT) const {
132    assert((unsigned)VT.getSimpleVT() < array_lengthof(RegClassForVT));
133    TargetRegisterClass *RC = RegClassForVT[VT.getSimpleVT()];
134    assert(RC && "This value type is not natively supported!");
135    return RC;
136  }
137
138  /// isTypeLegal - Return true if the target has native support for the
139  /// specified value type.  This means that it has a register that directly
140  /// holds it without promotions or expansions.
141  bool isTypeLegal(MVT VT) const {
142    assert(!VT.isSimple() ||
143           (unsigned)VT.getSimpleVT() < array_lengthof(RegClassForVT));
144    return VT.isSimple() && RegClassForVT[VT.getSimpleVT()] != 0;
145  }
146
147  class ValueTypeActionImpl {
148    /// ValueTypeActions - This is a bitvector that contains two bits for each
149    /// value type, where the two bits correspond to the LegalizeAction enum.
150    /// This can be queried with "getTypeAction(VT)".
151    uint32_t ValueTypeActions[2];
152  public:
153    ValueTypeActionImpl() {
154      ValueTypeActions[0] = ValueTypeActions[1] = 0;
155    }
156    ValueTypeActionImpl(const ValueTypeActionImpl &RHS) {
157      ValueTypeActions[0] = RHS.ValueTypeActions[0];
158      ValueTypeActions[1] = RHS.ValueTypeActions[1];
159    }
160
161    LegalizeAction getTypeAction(MVT VT) const {
162      if (VT.isExtended()) {
163        if (VT.isVector()) return Expand;
164        if (VT.isInteger())
165          // First promote to a power-of-two size, then expand if necessary.
166          return VT == VT.getRoundIntegerType() ? Expand : Promote;
167        assert(0 && "Unsupported extended type!");
168        return Legal;
169      }
170      unsigned I = VT.getSimpleVT();
171      assert(I<4*array_lengthof(ValueTypeActions)*sizeof(ValueTypeActions[0]));
172      return (LegalizeAction)((ValueTypeActions[I>>4] >> ((2*I) & 31)) & 3);
173    }
174    void setTypeAction(MVT VT, LegalizeAction Action) {
175      unsigned I = VT.getSimpleVT();
176      assert(I<4*array_lengthof(ValueTypeActions)*sizeof(ValueTypeActions[0]));
177      ValueTypeActions[I>>4] |= Action << ((I*2) & 31);
178    }
179  };
180
181  const ValueTypeActionImpl &getValueTypeActions() const {
182    return ValueTypeActions;
183  }
184
185  /// getTypeAction - Return how we should legalize values of this type, either
186  /// it is already legal (return 'Legal') or we need to promote it to a larger
187  /// type (return 'Promote'), or we need to expand it into multiple registers
188  /// of smaller integer type (return 'Expand').  'Custom' is not an option.
189  LegalizeAction getTypeAction(MVT VT) const {
190    return ValueTypeActions.getTypeAction(VT);
191  }
192
193  /// getTypeToTransformTo - For types supported by the target, this is an
194  /// identity function.  For types that must be promoted to larger types, this
195  /// returns the larger type to promote to.  For integer types that are larger
196  /// than the largest integer register, this contains one step in the expansion
197  /// to get to the smaller register. For illegal floating point types, this
198  /// returns the integer type to transform to.
199  MVT getTypeToTransformTo(MVT VT) const {
200    if (VT.isSimple()) {
201      assert((unsigned)VT.getSimpleVT() < array_lengthof(TransformToType));
202      MVT NVT = TransformToType[VT.getSimpleVT()];
203      assert(getTypeAction(NVT) != Promote &&
204             "Promote may not follow Expand or Promote");
205      return NVT;
206    }
207
208    if (VT.isVector())
209      return MVT::getVectorVT(VT.getVectorElementType(),
210                              VT.getVectorNumElements() / 2);
211    if (VT.isInteger()) {
212      MVT NVT = VT.getRoundIntegerType();
213      if (NVT == VT)
214        // Size is a power of two - expand to half the size.
215        return MVT::getIntegerVT(VT.getSizeInBits() / 2);
216      else
217        // Promote to a power of two size, avoiding multi-step promotion.
218        return getTypeAction(NVT) == Promote ? getTypeToTransformTo(NVT) : NVT;
219    }
220    assert(0 && "Unsupported extended type!");
221    return MVT(); // Not reached
222  }
223
224  /// getTypeToExpandTo - For types supported by the target, this is an
225  /// identity function.  For types that must be expanded (i.e. integer types
226  /// that are larger than the largest integer register or illegal floating
227  /// point types), this returns the largest legal type it will be expanded to.
228  MVT getTypeToExpandTo(MVT VT) const {
229    assert(!VT.isVector());
230    while (true) {
231      switch (getTypeAction(VT)) {
232      case Legal:
233        return VT;
234      case Expand:
235        VT = getTypeToTransformTo(VT);
236        break;
237      default:
238        assert(false && "Type is not legal nor is it to be expanded!");
239        return VT;
240      }
241    }
242    return VT;
243  }
244
245  /// getVectorTypeBreakdown - Vector types are broken down into some number of
246  /// legal first class types.  For example, MVT::v8f32 maps to 2 MVT::v4f32
247  /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
248  /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
249  ///
250  /// This method returns the number of registers needed, and the VT for each
251  /// register.  It also returns the VT and quantity of the intermediate values
252  /// before they are promoted/expanded.
253  ///
254  unsigned getVectorTypeBreakdown(MVT VT,
255                                  MVT &IntermediateVT,
256                                  unsigned &NumIntermediates,
257                                  MVT &RegisterVT) const;
258
259  typedef std::vector<APFloat>::const_iterator legal_fpimm_iterator;
260  legal_fpimm_iterator legal_fpimm_begin() const {
261    return LegalFPImmediates.begin();
262  }
263  legal_fpimm_iterator legal_fpimm_end() const {
264    return LegalFPImmediates.end();
265  }
266
267  /// isShuffleMaskLegal - Targets can use this to indicate that they only
268  /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
269  /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
270  /// are assumed to be legal.
271  virtual bool isShuffleMaskLegal(SDValue Mask, MVT VT) const {
272    return true;
273  }
274
275  /// isVectorClearMaskLegal - Similar to isShuffleMaskLegal. This is
276  /// used by Targets can use this to indicate if there is a suitable
277  /// VECTOR_SHUFFLE that can be used to replace a VAND with a constant
278  /// pool entry.
279  virtual bool isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
280                                      MVT EVT,
281                                      SelectionDAG &DAG) const {
282    return false;
283  }
284
285  /// getOperationAction - Return how this operation should be treated: either
286  /// it is legal, needs to be promoted to a larger size, needs to be
287  /// expanded to some other code sequence, or the target has a custom expander
288  /// for it.
289  LegalizeAction getOperationAction(unsigned Op, MVT VT) const {
290    if (VT.isExtended()) return Expand;
291    assert(Op < array_lengthof(OpActions) &&
292           (unsigned)VT.getSimpleVT() < sizeof(OpActions[0])*4 &&
293           "Table isn't big enough!");
294    return (LegalizeAction)((OpActions[Op] >> (2*VT.getSimpleVT())) & 3);
295  }
296
297  /// isOperationLegal - Return true if the specified operation is legal on this
298  /// target.
299  bool isOperationLegal(unsigned Op, MVT VT) const {
300    return (VT == MVT::Other || isTypeLegal(VT)) &&
301      (getOperationAction(Op, VT) == Legal ||
302       getOperationAction(Op, VT) == Custom);
303  }
304
305  /// getLoadXAction - Return how this load with extension should be treated:
306  /// either it is legal, needs to be promoted to a larger size, needs to be
307  /// expanded to some other code sequence, or the target has a custom expander
308  /// for it.
309  LegalizeAction getLoadXAction(unsigned LType, MVT VT) const {
310    assert(LType < array_lengthof(LoadXActions) &&
311           (unsigned)VT.getSimpleVT() < sizeof(LoadXActions[0])*4 &&
312           "Table isn't big enough!");
313    return (LegalizeAction)((LoadXActions[LType] >> (2*VT.getSimpleVT())) & 3);
314  }
315
316  /// isLoadXLegal - Return true if the specified load with extension is legal
317  /// on this target.
318  bool isLoadXLegal(unsigned LType, MVT VT) const {
319    return VT.isSimple() &&
320      (getLoadXAction(LType, VT) == Legal ||
321       getLoadXAction(LType, VT) == Custom);
322  }
323
324  /// getTruncStoreAction - Return how this store with truncation should be
325  /// treated: either it is legal, needs to be promoted to a larger size, needs
326  /// to be expanded to some other code sequence, or the target has a custom
327  /// expander for it.
328  LegalizeAction getTruncStoreAction(MVT ValVT,
329                                     MVT MemVT) const {
330    assert((unsigned)ValVT.getSimpleVT() < array_lengthof(TruncStoreActions) &&
331           (unsigned)MemVT.getSimpleVT() < sizeof(TruncStoreActions[0])*4 &&
332           "Table isn't big enough!");
333    return (LegalizeAction)((TruncStoreActions[ValVT.getSimpleVT()] >>
334                             (2*MemVT.getSimpleVT())) & 3);
335  }
336
337  /// isTruncStoreLegal - Return true if the specified store with truncation is
338  /// legal on this target.
339  bool isTruncStoreLegal(MVT ValVT, MVT MemVT) const {
340    return isTypeLegal(ValVT) && MemVT.isSimple() &&
341      (getTruncStoreAction(ValVT, MemVT) == Legal ||
342       getTruncStoreAction(ValVT, MemVT) == Custom);
343  }
344
345  /// getIndexedLoadAction - Return how the indexed load should be treated:
346  /// either it is legal, needs to be promoted to a larger size, needs to be
347  /// expanded to some other code sequence, or the target has a custom expander
348  /// for it.
349  LegalizeAction
350  getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
351    assert(IdxMode < array_lengthof(IndexedModeActions[0]) &&
352           (unsigned)VT.getSimpleVT() < sizeof(IndexedModeActions[0][0])*4 &&
353           "Table isn't big enough!");
354    return (LegalizeAction)((IndexedModeActions[0][IdxMode] >>
355                             (2*VT.getSimpleVT())) & 3);
356  }
357
358  /// isIndexedLoadLegal - Return true if the specified indexed load is legal
359  /// on this target.
360  bool isIndexedLoadLegal(unsigned IdxMode, MVT VT) const {
361    return VT.isSimple() &&
362      (getIndexedLoadAction(IdxMode, VT) == Legal ||
363       getIndexedLoadAction(IdxMode, VT) == Custom);
364  }
365
366  /// getIndexedStoreAction - Return how the indexed store should be treated:
367  /// either it is legal, needs to be promoted to a larger size, needs to be
368  /// expanded to some other code sequence, or the target has a custom expander
369  /// for it.
370  LegalizeAction
371  getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
372    assert(IdxMode < array_lengthof(IndexedModeActions[1]) &&
373           (unsigned)VT.getSimpleVT() < sizeof(IndexedModeActions[1][0])*4 &&
374           "Table isn't big enough!");
375    return (LegalizeAction)((IndexedModeActions[1][IdxMode] >>
376                             (2*VT.getSimpleVT())) & 3);
377  }
378
379  /// isIndexedStoreLegal - Return true if the specified indexed load is legal
380  /// on this target.
381  bool isIndexedStoreLegal(unsigned IdxMode, MVT VT) const {
382    return VT.isSimple() &&
383      (getIndexedStoreAction(IdxMode, VT) == Legal ||
384       getIndexedStoreAction(IdxMode, VT) == Custom);
385  }
386
387  /// getConvertAction - Return how the conversion should be treated:
388  /// either it is legal, needs to be promoted to a larger size, needs to be
389  /// expanded to some other code sequence, or the target has a custom expander
390  /// for it.
391  LegalizeAction
392  getConvertAction(MVT FromVT, MVT ToVT) const {
393    assert((unsigned)FromVT.getSimpleVT() < array_lengthof(ConvertActions) &&
394           (unsigned)ToVT.getSimpleVT() < sizeof(ConvertActions[0])*4 &&
395           "Table isn't big enough!");
396    return (LegalizeAction)((ConvertActions[FromVT.getSimpleVT()] >>
397                             (2*ToVT.getSimpleVT())) & 3);
398  }
399
400  /// isConvertLegal - Return true if the specified conversion is legal
401  /// on this target.
402  bool isConvertLegal(MVT FromVT, MVT ToVT) const {
403    return isTypeLegal(FromVT) && isTypeLegal(ToVT) &&
404      (getConvertAction(FromVT, ToVT) == Legal ||
405       getConvertAction(FromVT, ToVT) == Custom);
406  }
407
408  /// getTypeToPromoteTo - If the action for this operation is to promote, this
409  /// method returns the ValueType to promote to.
410  MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
411    assert(getOperationAction(Op, VT) == Promote &&
412           "This operation isn't promoted!");
413
414    // See if this has an explicit type specified.
415    std::map<std::pair<unsigned, MVT::SimpleValueType>,
416             MVT::SimpleValueType>::const_iterator PTTI =
417      PromoteToType.find(std::make_pair(Op, VT.getSimpleVT()));
418    if (PTTI != PromoteToType.end()) return PTTI->second;
419
420    assert((VT.isInteger() || VT.isFloatingPoint()) &&
421           "Cannot autopromote this type, add it with AddPromotedToType.");
422
423    MVT NVT = VT;
424    do {
425      NVT = (MVT::SimpleValueType)(NVT.getSimpleVT()+1);
426      assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
427             "Didn't find type to promote to!");
428    } while (!isTypeLegal(NVT) ||
429              getOperationAction(Op, NVT) == Promote);
430    return NVT;
431  }
432
433  /// getValueType - Return the MVT corresponding to this LLVM type.
434  /// This is fixed by the LLVM operations except for the pointer size.  If
435  /// AllowUnknown is true, this will return MVT::Other for types with no MVT
436  /// counterpart (e.g. structs), otherwise it will assert.
437  MVT getValueType(const Type *Ty, bool AllowUnknown = false) const {
438    MVT VT = MVT::getMVT(Ty, AllowUnknown);
439    return VT == MVT::iPTR ? PointerTy : VT;
440  }
441
442  /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
443  /// function arguments in the caller parameter area.  This is the actual
444  /// alignment, not its logarithm.
445  virtual unsigned getByValTypeAlignment(const Type *Ty) const;
446
447  /// getRegisterType - Return the type of registers that this ValueType will
448  /// eventually require.
449  MVT getRegisterType(MVT VT) const {
450    if (VT.isSimple()) {
451      assert((unsigned)VT.getSimpleVT() < array_lengthof(RegisterTypeForVT));
452      return RegisterTypeForVT[VT.getSimpleVT()];
453    }
454    if (VT.isVector()) {
455      MVT VT1, RegisterVT;
456      unsigned NumIntermediates;
457      (void)getVectorTypeBreakdown(VT, VT1, NumIntermediates, RegisterVT);
458      return RegisterVT;
459    }
460    if (VT.isInteger()) {
461      return getRegisterType(getTypeToTransformTo(VT));
462    }
463    assert(0 && "Unsupported extended type!");
464    return MVT(); // Not reached
465  }
466
467  /// getNumRegisters - Return the number of registers that this ValueType will
468  /// eventually require.  This is one for any types promoted to live in larger
469  /// registers, but may be more than one for types (like i64) that are split
470  /// into pieces.  For types like i140, which are first promoted then expanded,
471  /// it is the number of registers needed to hold all the bits of the original
472  /// type.  For an i140 on a 32 bit machine this means 5 registers.
473  unsigned getNumRegisters(MVT VT) const {
474    if (VT.isSimple()) {
475      assert((unsigned)VT.getSimpleVT() < array_lengthof(NumRegistersForVT));
476      return NumRegistersForVT[VT.getSimpleVT()];
477    }
478    if (VT.isVector()) {
479      MVT VT1, VT2;
480      unsigned NumIntermediates;
481      return getVectorTypeBreakdown(VT, VT1, NumIntermediates, VT2);
482    }
483    if (VT.isInteger()) {
484      unsigned BitWidth = VT.getSizeInBits();
485      unsigned RegWidth = getRegisterType(VT).getSizeInBits();
486      return (BitWidth + RegWidth - 1) / RegWidth;
487    }
488    assert(0 && "Unsupported extended type!");
489    return 0; // Not reached
490  }
491
492  /// ShouldShrinkFPConstant - If true, then instruction selection should
493  /// seek to shrink the FP constant of the specified type to a smaller type
494  /// in order to save space and / or reduce runtime.
495  virtual bool ShouldShrinkFPConstant(MVT VT) const { return true; }
496
497  /// hasTargetDAGCombine - If true, the target has custom DAG combine
498  /// transformations that it can perform for the specified node.
499  bool hasTargetDAGCombine(ISD::NodeType NT) const {
500    assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
501    return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
502  }
503
504  /// This function returns the maximum number of store operations permitted
505  /// to replace a call to llvm.memset. The value is set by the target at the
506  /// performance threshold for such a replacement.
507  /// @brief Get maximum # of store operations permitted for llvm.memset
508  unsigned getMaxStoresPerMemset() const { return maxStoresPerMemset; }
509
510  /// This function returns the maximum number of store operations permitted
511  /// to replace a call to llvm.memcpy. The value is set by the target at the
512  /// performance threshold for such a replacement.
513  /// @brief Get maximum # of store operations permitted for llvm.memcpy
514  unsigned getMaxStoresPerMemcpy() const { return maxStoresPerMemcpy; }
515
516  /// This function returns the maximum number of store operations permitted
517  /// to replace a call to llvm.memmove. The value is set by the target at the
518  /// performance threshold for such a replacement.
519  /// @brief Get maximum # of store operations permitted for llvm.memmove
520  unsigned getMaxStoresPerMemmove() const { return maxStoresPerMemmove; }
521
522  /// This function returns true if the target allows unaligned memory accesses.
523  /// This is used, for example, in situations where an array copy/move/set is
524  /// converted to a sequence of store operations. It's use helps to ensure that
525  /// such replacements don't generate code that causes an alignment error
526  /// (trap) on the target machine.
527  /// @brief Determine if the target supports unaligned memory accesses.
528  bool allowsUnalignedMemoryAccesses() const {
529    return allowUnalignedMemoryAccesses;
530  }
531
532  /// getOptimalMemOpType - Returns the target specific optimal type for load
533  /// and store operations as a result of memset, memcpy, and memmove lowering.
534  /// It returns MVT::iAny if SelectionDAG should be responsible for
535  /// determining it.
536  virtual MVT getOptimalMemOpType(uint64_t Size, unsigned Align,
537                                  bool isSrcConst, bool isSrcStr) const {
538    return MVT::iAny;
539  }
540
541  /// usesUnderscoreSetJmp - Determine if we should use _setjmp or setjmp
542  /// to implement llvm.setjmp.
543  bool usesUnderscoreSetJmp() const {
544    return UseUnderscoreSetJmp;
545  }
546
547  /// usesUnderscoreLongJmp - Determine if we should use _longjmp or longjmp
548  /// to implement llvm.longjmp.
549  bool usesUnderscoreLongJmp() const {
550    return UseUnderscoreLongJmp;
551  }
552
553  /// getStackPointerRegisterToSaveRestore - If a physical register, this
554  /// specifies the register that llvm.savestack/llvm.restorestack should save
555  /// and restore.
556  unsigned getStackPointerRegisterToSaveRestore() const {
557    return StackPointerRegisterToSaveRestore;
558  }
559
560  /// getExceptionAddressRegister - If a physical register, this returns
561  /// the register that receives the exception address on entry to a landing
562  /// pad.
563  unsigned getExceptionAddressRegister() const {
564    return ExceptionPointerRegister;
565  }
566
567  /// getExceptionSelectorRegister - If a physical register, this returns
568  /// the register that receives the exception typeid on entry to a landing
569  /// pad.
570  unsigned getExceptionSelectorRegister() const {
571    return ExceptionSelectorRegister;
572  }
573
574  /// getJumpBufSize - returns the target's jmp_buf size in bytes (if never
575  /// set, the default is 200)
576  unsigned getJumpBufSize() const {
577    return JumpBufSize;
578  }
579
580  /// getJumpBufAlignment - returns the target's jmp_buf alignment in bytes
581  /// (if never set, the default is 0)
582  unsigned getJumpBufAlignment() const {
583    return JumpBufAlignment;
584  }
585
586  /// getIfCvtBlockLimit - returns the target specific if-conversion block size
587  /// limit. Any block whose size is greater should not be predicated.
588  unsigned getIfCvtBlockSizeLimit() const {
589    return IfCvtBlockSizeLimit;
590  }
591
592  /// getIfCvtDupBlockLimit - returns the target specific size limit for a
593  /// block to be considered for duplication. Any block whose size is greater
594  /// should not be duplicated to facilitate its predication.
595  unsigned getIfCvtDupBlockSizeLimit() const {
596    return IfCvtDupBlockSizeLimit;
597  }
598
599  /// getPrefLoopAlignment - return the preferred loop alignment.
600  ///
601  unsigned getPrefLoopAlignment() const {
602    return PrefLoopAlignment;
603  }
604
605  /// getPreIndexedAddressParts - returns true by value, base pointer and
606  /// offset pointer and addressing mode by reference if the node's address
607  /// can be legally represented as pre-indexed load / store address.
608  virtual bool getPreIndexedAddressParts(SDNode *N, SDValue &Base,
609                                         SDValue &Offset,
610                                         ISD::MemIndexedMode &AM,
611                                         SelectionDAG &DAG) {
612    return false;
613  }
614
615  /// getPostIndexedAddressParts - returns true by value, base pointer and
616  /// offset pointer and addressing mode by reference if this node can be
617  /// combined with a load / store to form a post-indexed load / store.
618  virtual bool getPostIndexedAddressParts(SDNode *N, SDNode *Op,
619                                          SDValue &Base, SDValue &Offset,
620                                          ISD::MemIndexedMode &AM,
621                                          SelectionDAG &DAG) {
622    return false;
623  }
624
625  /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
626  /// jumptable.
627  virtual SDValue getPICJumpTableRelocBase(SDValue Table,
628                                             SelectionDAG &DAG) const;
629
630  //===--------------------------------------------------------------------===//
631  // TargetLowering Optimization Methods
632  //
633
634  /// TargetLoweringOpt - A convenience struct that encapsulates a DAG, and two
635  /// SDValues for returning information from TargetLowering to its clients
636  /// that want to combine
637  struct TargetLoweringOpt {
638    SelectionDAG &DAG;
639    bool AfterLegalize;
640    SDValue Old;
641    SDValue New;
642
643    explicit TargetLoweringOpt(SelectionDAG &InDAG, bool afterLegalize)
644      : DAG(InDAG), AfterLegalize(afterLegalize) {}
645
646    bool CombineTo(SDValue O, SDValue N) {
647      Old = O;
648      New = N;
649      return true;
650    }
651
652    /// ShrinkDemandedConstant - Check to see if the specified operand of the
653    /// specified instruction is a constant integer.  If so, check to see if
654    /// there are any bits set in the constant that are not demanded.  If so,
655    /// shrink the constant and return true.
656    bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded);
657  };
658
659  /// SimplifyDemandedBits - Look at Op.  At this point, we know that only the
660  /// DemandedMask bits of the result of Op are ever used downstream.  If we can
661  /// use this information to simplify Op, create a new simplified DAG node and
662  /// return true, returning the original and new nodes in Old and New.
663  /// Otherwise, analyze the expression and return a mask of KnownOne and
664  /// KnownZero bits for the expression (used to simplify the caller).
665  /// The KnownZero/One bits may only be accurate for those bits in the
666  /// DemandedMask.
667  bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
668                            APInt &KnownZero, APInt &KnownOne,
669                            TargetLoweringOpt &TLO, unsigned Depth = 0) const;
670
671  /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
672  /// Mask are known to be either zero or one and return them in the
673  /// KnownZero/KnownOne bitsets.
674  virtual void computeMaskedBitsForTargetNode(const SDValue Op,
675                                              const APInt &Mask,
676                                              APInt &KnownZero,
677                                              APInt &KnownOne,
678                                              const SelectionDAG &DAG,
679                                              unsigned Depth = 0) const;
680
681  /// ComputeNumSignBitsForTargetNode - This method can be implemented by
682  /// targets that want to expose additional information about sign bits to the
683  /// DAG Combiner.
684  virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
685                                                   unsigned Depth = 0) const;
686
687  struct DAGCombinerInfo {
688    void *DC;  // The DAG Combiner object.
689    bool BeforeLegalize;
690    bool CalledByLegalizer;
691  public:
692    SelectionDAG &DAG;
693
694    DAGCombinerInfo(SelectionDAG &dag, bool bl, bool cl, void *dc)
695      : DC(dc), BeforeLegalize(bl), CalledByLegalizer(cl), DAG(dag) {}
696
697    bool isBeforeLegalize() const { return BeforeLegalize; }
698    bool isCalledByLegalizer() const { return CalledByLegalizer; }
699
700    void AddToWorklist(SDNode *N);
701    SDValue CombineTo(SDNode *N, const std::vector<SDValue> &To);
702    SDValue CombineTo(SDNode *N, SDValue Res);
703    SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1);
704  };
705
706  /// SimplifySetCC - Try to simplify a setcc built with the specified operands
707  /// and cc. If it is unable to simplify it, return a null SDValue.
708  SDValue SimplifySetCC(MVT VT, SDValue N0, SDValue N1,
709                          ISD::CondCode Cond, bool foldBooleans,
710                          DAGCombinerInfo &DCI) const;
711
712  /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
713  /// node is a GlobalAddress + offset.
714  virtual bool
715  isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) const;
716
717  /// isConsecutiveLoad - Return true if LD (which must be a LoadSDNode) is
718  /// loading 'Bytes' bytes from a location that is 'Dist' units away from the
719  /// location that the 'Base' load is loading from.
720  bool isConsecutiveLoad(SDNode *LD, SDNode *Base, unsigned Bytes, int Dist,
721                         const MachineFrameInfo *MFI) const;
722
723  /// PerformDAGCombine - This method will be invoked for all target nodes and
724  /// for any target-independent nodes that the target has registered with
725  /// invoke it for.
726  ///
727  /// The semantics are as follows:
728  /// Return Value:
729  ///   SDValue.Val == 0   - No change was made
730  ///   SDValue.Val == N   - N was replaced, is dead, and is already handled.
731  ///   otherwise            - N should be replaced by the returned Operand.
732  ///
733  /// In addition, methods provided by DAGCombinerInfo may be used to perform
734  /// more complex transformations.
735  ///
736  virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
737
738  //===--------------------------------------------------------------------===//
739  // TargetLowering Configuration Methods - These methods should be invoked by
740  // the derived class constructor to configure this object for the target.
741  //
742
743protected:
744  /// setUsesGlobalOffsetTable - Specify that this target does or doesn't use a
745  /// GOT for PC-relative code.
746  void setUsesGlobalOffsetTable(bool V) { UsesGlobalOffsetTable = V; }
747
748  /// setShiftAmountType - Describe the type that should be used for shift
749  /// amounts.  This type defaults to the pointer type.
750  void setShiftAmountType(MVT VT) { ShiftAmountTy = VT; }
751
752  /// setSetCCResultContents - Specify how the target extends the result of a
753  /// setcc operation in a register.
754  void setSetCCResultContents(SetCCResultValue Ty) { SetCCResultContents = Ty; }
755
756  /// setSchedulingPreference - Specify the target scheduling preference.
757  void setSchedulingPreference(SchedPreference Pref) {
758    SchedPreferenceInfo = Pref;
759  }
760
761  /// setShiftAmountFlavor - Describe how the target handles out of range shift
762  /// amounts.
763  void setShiftAmountFlavor(OutOfRangeShiftAmount OORSA) {
764    ShiftAmtHandling = OORSA;
765  }
766
767  /// setUseUnderscoreSetJmp - Indicate whether this target prefers to
768  /// use _setjmp to implement llvm.setjmp or the non _ version.
769  /// Defaults to false.
770  void setUseUnderscoreSetJmp(bool Val) {
771    UseUnderscoreSetJmp = Val;
772  }
773
774  /// setUseUnderscoreLongJmp - Indicate whether this target prefers to
775  /// use _longjmp to implement llvm.longjmp or the non _ version.
776  /// Defaults to false.
777  void setUseUnderscoreLongJmp(bool Val) {
778    UseUnderscoreLongJmp = Val;
779  }
780
781  /// setStackPointerRegisterToSaveRestore - If set to a physical register, this
782  /// specifies the register that llvm.savestack/llvm.restorestack should save
783  /// and restore.
784  void setStackPointerRegisterToSaveRestore(unsigned R) {
785    StackPointerRegisterToSaveRestore = R;
786  }
787
788  /// setExceptionPointerRegister - If set to a physical register, this sets
789  /// the register that receives the exception address on entry to a landing
790  /// pad.
791  void setExceptionPointerRegister(unsigned R) {
792    ExceptionPointerRegister = R;
793  }
794
795  /// setExceptionSelectorRegister - If set to a physical register, this sets
796  /// the register that receives the exception typeid on entry to a landing
797  /// pad.
798  void setExceptionSelectorRegister(unsigned R) {
799    ExceptionSelectorRegister = R;
800  }
801
802  /// SelectIsExpensive - Tells the code generator not to expand operations
803  /// into sequences that use the select operations if possible.
804  void setSelectIsExpensive() { SelectIsExpensive = true; }
805
806  /// setIntDivIsCheap - Tells the code generator that integer divide is
807  /// expensive, and if possible, should be replaced by an alternate sequence
808  /// of instructions not containing an integer divide.
809  void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
810
811  /// setPow2DivIsCheap - Tells the code generator that it shouldn't generate
812  /// srl/add/sra for a signed divide by power of two, and let the target handle
813  /// it.
814  void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
815
816  /// addRegisterClass - Add the specified register class as an available
817  /// regclass for the specified value type.  This indicates the selector can
818  /// handle values of that class natively.
819  void addRegisterClass(MVT VT, TargetRegisterClass *RC) {
820    assert((unsigned)VT.getSimpleVT() < array_lengthof(RegClassForVT));
821    AvailableRegClasses.push_back(std::make_pair(VT, RC));
822    RegClassForVT[VT.getSimpleVT()] = RC;
823  }
824
825  /// computeRegisterProperties - Once all of the register classes are added,
826  /// this allows us to compute derived properties we expose.
827  void computeRegisterProperties();
828
829  /// setOperationAction - Indicate that the specified operation does not work
830  /// with the specified type and indicate what to do about it.
831  void setOperationAction(unsigned Op, MVT VT,
832                          LegalizeAction Action) {
833    assert((unsigned)VT.getSimpleVT() < sizeof(OpActions[0])*4 &&
834           Op < array_lengthof(OpActions) && "Table isn't big enough!");
835    OpActions[Op] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
836    OpActions[Op] |= (uint64_t)Action << VT.getSimpleVT()*2;
837  }
838
839  /// setLoadXAction - Indicate that the specified load with extension does not
840  /// work with the with specified type and indicate what to do about it.
841  void setLoadXAction(unsigned ExtType, MVT VT,
842                      LegalizeAction Action) {
843    assert((unsigned)VT.getSimpleVT() < sizeof(LoadXActions[0])*4 &&
844           ExtType < array_lengthof(LoadXActions) &&
845           "Table isn't big enough!");
846    LoadXActions[ExtType] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
847    LoadXActions[ExtType] |= (uint64_t)Action << VT.getSimpleVT()*2;
848  }
849
850  /// setTruncStoreAction - Indicate that the specified truncating store does
851  /// not work with the with specified type and indicate what to do about it.
852  void setTruncStoreAction(MVT ValVT, MVT MemVT,
853                           LegalizeAction Action) {
854    assert((unsigned)ValVT.getSimpleVT() < array_lengthof(TruncStoreActions) &&
855           (unsigned)MemVT.getSimpleVT() < sizeof(TruncStoreActions[0])*4 &&
856           "Table isn't big enough!");
857    TruncStoreActions[ValVT.getSimpleVT()] &= ~(uint64_t(3UL) <<
858                                                MemVT.getSimpleVT()*2);
859    TruncStoreActions[ValVT.getSimpleVT()] |= (uint64_t)Action <<
860      MemVT.getSimpleVT()*2;
861  }
862
863  /// setIndexedLoadAction - Indicate that the specified indexed load does or
864  /// does not work with the with specified type and indicate what to do abort
865  /// it. NOTE: All indexed mode loads are initialized to Expand in
866  /// TargetLowering.cpp
867  void setIndexedLoadAction(unsigned IdxMode, MVT VT,
868                            LegalizeAction Action) {
869    assert((unsigned)VT.getSimpleVT() < sizeof(IndexedModeActions[0])*4 &&
870           IdxMode < array_lengthof(IndexedModeActions[0]) &&
871           "Table isn't big enough!");
872    IndexedModeActions[0][IdxMode] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
873    IndexedModeActions[0][IdxMode] |= (uint64_t)Action << VT.getSimpleVT()*2;
874  }
875
876  /// setIndexedStoreAction - Indicate that the specified indexed store does or
877  /// does not work with the with specified type and indicate what to do about
878  /// it. NOTE: All indexed mode stores are initialized to Expand in
879  /// TargetLowering.cpp
880  void setIndexedStoreAction(unsigned IdxMode, MVT VT,
881                             LegalizeAction Action) {
882    assert((unsigned)VT.getSimpleVT() < sizeof(IndexedModeActions[1][0])*4 &&
883           IdxMode < array_lengthof(IndexedModeActions[1]) &&
884           "Table isn't big enough!");
885    IndexedModeActions[1][IdxMode] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
886    IndexedModeActions[1][IdxMode] |= (uint64_t)Action << VT.getSimpleVT()*2;
887  }
888
889  /// setConvertAction - Indicate that the specified conversion does or does
890  /// not work with the with specified type and indicate what to do about it.
891  void setConvertAction(MVT FromVT, MVT ToVT,
892                        LegalizeAction Action) {
893    assert((unsigned)FromVT.getSimpleVT() < array_lengthof(ConvertActions) &&
894           (unsigned)ToVT.getSimpleVT() < sizeof(ConvertActions[0])*4 &&
895           "Table isn't big enough!");
896    ConvertActions[FromVT.getSimpleVT()] &= ~(uint64_t(3UL) <<
897                                              ToVT.getSimpleVT()*2);
898    ConvertActions[FromVT.getSimpleVT()] |= (uint64_t)Action <<
899      ToVT.getSimpleVT()*2;
900  }
901
902  /// AddPromotedToType - If Opc/OrigVT is specified as being promoted, the
903  /// promotion code defaults to trying a larger integer/fp until it can find
904  /// one that works.  If that default is insufficient, this method can be used
905  /// by the target to override the default.
906  void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
907    PromoteToType[std::make_pair(Opc, OrigVT.getSimpleVT())] =
908      DestVT.getSimpleVT();
909  }
910
911  /// addLegalFPImmediate - Indicate that this target can instruction select
912  /// the specified FP immediate natively.
913  void addLegalFPImmediate(const APFloat& Imm) {
914    LegalFPImmediates.push_back(Imm);
915  }
916
917  /// setTargetDAGCombine - Targets should invoke this method for each target
918  /// independent node that they want to provide a custom DAG combiner for by
919  /// implementing the PerformDAGCombine virtual method.
920  void setTargetDAGCombine(ISD::NodeType NT) {
921    assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
922    TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
923  }
924
925  /// setJumpBufSize - Set the target's required jmp_buf buffer size (in
926  /// bytes); default is 200
927  void setJumpBufSize(unsigned Size) {
928    JumpBufSize = Size;
929  }
930
931  /// setJumpBufAlignment - Set the target's required jmp_buf buffer
932  /// alignment (in bytes); default is 0
933  void setJumpBufAlignment(unsigned Align) {
934    JumpBufAlignment = Align;
935  }
936
937  /// setIfCvtBlockSizeLimit - Set the target's if-conversion block size
938  /// limit (in number of instructions); default is 2.
939  void setIfCvtBlockSizeLimit(unsigned Limit) {
940    IfCvtBlockSizeLimit = Limit;
941  }
942
943  /// setIfCvtDupBlockSizeLimit - Set the target's block size limit (in number
944  /// of instructions) to be considered for code duplication during
945  /// if-conversion; default is 2.
946  void setIfCvtDupBlockSizeLimit(unsigned Limit) {
947    IfCvtDupBlockSizeLimit = Limit;
948  }
949
950  /// setPrefLoopAlignment - Set the target's preferred loop alignment. Default
951  /// alignment is zero, it means the target does not care about loop alignment.
952  void setPrefLoopAlignment(unsigned Align) {
953    PrefLoopAlignment = Align;
954  }
955
956public:
957
958  virtual const TargetSubtarget *getSubtarget() {
959    assert(0 && "Not Implemented");
960    return NULL;    // this is here to silence compiler errors
961  }
962  //===--------------------------------------------------------------------===//
963  // Lowering methods - These methods must be implemented by targets so that
964  // the SelectionDAGLowering code knows how to lower these.
965  //
966
967  /// LowerArguments - This hook must be implemented to indicate how we should
968  /// lower the arguments for the specified function, into the specified DAG.
969  virtual void
970  LowerArguments(Function &F, SelectionDAG &DAG,
971                 SmallVectorImpl<SDValue>& ArgValues);
972
973  /// LowerCallTo - This hook lowers an abstract call to a function into an
974  /// actual call.  This returns a pair of operands.  The first element is the
975  /// return value for the function (if RetTy is not VoidTy).  The second
976  /// element is the outgoing token chain.
977  struct ArgListEntry {
978    SDValue Node;
979    const Type* Ty;
980    bool isSExt  : 1;
981    bool isZExt  : 1;
982    bool isInReg : 1;
983    bool isSRet  : 1;
984    bool isNest  : 1;
985    bool isByVal : 1;
986    uint16_t Alignment;
987
988    ArgListEntry() : isSExt(false), isZExt(false), isInReg(false),
989      isSRet(false), isNest(false), isByVal(false), Alignment(0) { }
990  };
991  typedef std::vector<ArgListEntry> ArgListTy;
992  virtual std::pair<SDValue, SDValue>
993  LowerCallTo(SDValue Chain, const Type *RetTy, bool RetSExt, bool RetZExt,
994              bool isVarArg, unsigned CallingConv, bool isTailCall,
995              SDValue Callee, ArgListTy &Args, SelectionDAG &DAG);
996
997
998  /// EmitTargetCodeForMemcpy - Emit target-specific code that performs a
999  /// memcpy. This can be used by targets to provide code sequences for cases
1000  /// that don't fit the target's parameters for simple loads/stores and can be
1001  /// more efficient than using a library call. This function can return a null
1002  /// SDValue if the target declines to use custom code and a different
1003  /// lowering strategy should be used.
1004  ///
1005  /// If AlwaysInline is true, the size is constant and the target should not
1006  /// emit any calls and is strongly encouraged to attempt to emit inline code
1007  /// even if it is beyond the usual threshold because this intrinsic is being
1008  /// expanded in a place where calls are not feasible (e.g. within the prologue
1009  /// for another call). If the target chooses to decline an AlwaysInline
1010  /// request here, legalize will resort to using simple loads and stores.
1011  virtual SDValue
1012  EmitTargetCodeForMemcpy(SelectionDAG &DAG,
1013                          SDValue Chain,
1014                          SDValue Op1, SDValue Op2,
1015                          SDValue Op3, unsigned Align,
1016                          bool AlwaysInline,
1017                          const Value *DstSV, uint64_t DstOff,
1018                          const Value *SrcSV, uint64_t SrcOff) {
1019    return SDValue();
1020  }
1021
1022  /// EmitTargetCodeForMemmove - Emit target-specific code that performs a
1023  /// memmove. This can be used by targets to provide code sequences for cases
1024  /// that don't fit the target's parameters for simple loads/stores and can be
1025  /// more efficient than using a library call. This function can return a null
1026  /// SDValue if the target declines to use custom code and a different
1027  /// lowering strategy should be used.
1028  virtual SDValue
1029  EmitTargetCodeForMemmove(SelectionDAG &DAG,
1030                           SDValue Chain,
1031                           SDValue Op1, SDValue Op2,
1032                           SDValue Op3, unsigned Align,
1033                           const Value *DstSV, uint64_t DstOff,
1034                           const Value *SrcSV, uint64_t SrcOff) {
1035    return SDValue();
1036  }
1037
1038  /// EmitTargetCodeForMemset - Emit target-specific code that performs a
1039  /// memset. This can be used by targets to provide code sequences for cases
1040  /// that don't fit the target's parameters for simple stores and can be more
1041  /// efficient than using a library call. This function can return a null
1042  /// SDValue if the target declines to use custom code and a different
1043  /// lowering strategy should be used.
1044  virtual SDValue
1045  EmitTargetCodeForMemset(SelectionDAG &DAG,
1046                          SDValue Chain,
1047                          SDValue Op1, SDValue Op2,
1048                          SDValue Op3, unsigned Align,
1049                          const Value *DstSV, uint64_t DstOff) {
1050    return SDValue();
1051  }
1052
1053  /// LowerOperation - This callback is invoked for operations that are
1054  /// unsupported by the target, which are registered to use 'custom' lowering,
1055  /// and whose defined values are all legal.
1056  /// If the target has no operations that require custom lowering, it need not
1057  /// implement this.  The default implementation of this aborts.
1058  virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG);
1059
1060  /// ReplaceNodeResults - This callback is invoked for operations that are
1061  /// unsupported by the target, which are registered to use 'custom' lowering,
1062  /// and whose result type is illegal.  This must return a node whose results
1063  /// precisely match the results of the input node.  This typically involves a
1064  /// MERGE_VALUES node and/or BUILD_PAIR.
1065  ///
1066  /// If the target has no operations that require custom lowering, it need not
1067  /// implement this.  The default implementation aborts.
1068  virtual SDNode *ReplaceNodeResults(SDNode *N, SelectionDAG &DAG) {
1069    assert(0 && "ReplaceNodeResults not implemented for this target!");
1070    return 0;
1071  }
1072
1073  /// IsEligibleForTailCallOptimization - Check whether the call is eligible for
1074  /// tail call optimization. Targets which want to do tail call optimization
1075  /// should override this function.
1076  virtual bool IsEligibleForTailCallOptimization(SDValue Call,
1077                                                 SDValue Ret,
1078                                                 SelectionDAG &DAG) const {
1079    return false;
1080  }
1081
1082  /// CheckTailCallReturnConstraints - Check whether CALL node immediatly
1083  /// preceeds the RET node and whether the return uses the result of the node
1084  /// or is a void return. This function can be used by the target to determine
1085  /// eligiblity of tail call optimization.
1086  static bool CheckTailCallReturnConstraints(SDValue Call, SDValue Ret) {
1087    unsigned NumOps = Ret.getNumOperands();
1088    if ((NumOps == 1 &&
1089       (Ret.getOperand(0) == SDValue(Call.Val,1) ||
1090        Ret.getOperand(0) == SDValue(Call.Val,0))) ||
1091      (NumOps > 1 &&
1092       Ret.getOperand(0) == SDValue(Call.Val,Call.Val->getNumValues()-1) &&
1093       Ret.getOperand(1) == SDValue(Call.Val,0)))
1094      return true;
1095    return false;
1096  }
1097
1098  /// GetPossiblePreceedingTailCall - Get preceeding TailCallNodeOpCode node if
1099  /// it exists skip possible ISD:TokenFactor.
1100  static SDValue GetPossiblePreceedingTailCall(SDValue Chain,
1101                                                 unsigned TailCallNodeOpCode) {
1102    if (Chain.getOpcode() == TailCallNodeOpCode) {
1103      return Chain;
1104    } else if (Chain.getOpcode() == ISD::TokenFactor) {
1105      if (Chain.getNumOperands() &&
1106          Chain.getOperand(0).getOpcode() == TailCallNodeOpCode)
1107        return Chain.getOperand(0);
1108    }
1109    return Chain;
1110  }
1111
1112  /// getTargetNodeName() - This method returns the name of a target specific
1113  /// DAG node.
1114  virtual const char *getTargetNodeName(unsigned Opcode) const;
1115
1116  /// createFastISel - This method returns a target specific FastISel object,
1117  /// or null if the target does not support "fast" ISel.
1118  virtual FastISel *createFastISel(MachineFunction &) { return 0; }
1119
1120  //===--------------------------------------------------------------------===//
1121  // Inline Asm Support hooks
1122  //
1123
1124  enum ConstraintType {
1125    C_Register,            // Constraint represents a single register.
1126    C_RegisterClass,       // Constraint represents one or more registers.
1127    C_Memory,              // Memory constraint.
1128    C_Other,               // Something else.
1129    C_Unknown              // Unsupported constraint.
1130  };
1131
1132  /// AsmOperandInfo - This contains information for each constraint that we are
1133  /// lowering.
1134  struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
1135    /// ConstraintCode - This contains the actual string for the code, like "m".
1136    std::string ConstraintCode;
1137
1138    /// ConstraintType - Information about the constraint code, e.g. Register,
1139    /// RegisterClass, Memory, Other, Unknown.
1140    TargetLowering::ConstraintType ConstraintType;
1141
1142    /// CallOperandval - If this is the result output operand or a
1143    /// clobber, this is null, otherwise it is the incoming operand to the
1144    /// CallInst.  This gets modified as the asm is processed.
1145    Value *CallOperandVal;
1146
1147    /// ConstraintVT - The ValueType for the operand value.
1148    MVT ConstraintVT;
1149
1150    AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
1151      : InlineAsm::ConstraintInfo(info),
1152        ConstraintType(TargetLowering::C_Unknown),
1153        CallOperandVal(0), ConstraintVT(MVT::Other) {
1154    }
1155  };
1156
1157  /// ComputeConstraintToUse - Determines the constraint code and constraint
1158  /// type to use for the specific AsmOperandInfo, setting
1159  /// OpInfo.ConstraintCode and OpInfo.ConstraintType.  If the actual operand
1160  /// being passed in is available, it can be passed in as Op, otherwise an
1161  /// empty SDValue can be passed.
1162  virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
1163                                      SDValue Op,
1164                                      SelectionDAG *DAG = 0) const;
1165
1166  /// getConstraintType - Given a constraint, return the type of constraint it
1167  /// is for this target.
1168  virtual ConstraintType getConstraintType(const std::string &Constraint) const;
1169
1170  /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
1171  /// return a list of registers that can be used to satisfy the constraint.
1172  /// This should only be used for C_RegisterClass constraints.
1173  virtual std::vector<unsigned>
1174  getRegClassForInlineAsmConstraint(const std::string &Constraint,
1175                                    MVT VT) const;
1176
1177  /// getRegForInlineAsmConstraint - Given a physical register constraint (e.g.
1178  /// {edx}), return the register number and the register class for the
1179  /// register.
1180  ///
1181  /// Given a register class constraint, like 'r', if this corresponds directly
1182  /// to an LLVM register class, return a register of 0 and the register class
1183  /// pointer.
1184  ///
1185  /// This should only be used for C_Register constraints.  On error,
1186  /// this returns a register number of 0 and a null register class pointer..
1187  virtual std::pair<unsigned, const TargetRegisterClass*>
1188    getRegForInlineAsmConstraint(const std::string &Constraint,
1189                                 MVT VT) const;
1190
1191  /// LowerXConstraint - try to replace an X constraint, which matches anything,
1192  /// with another that has more specific requirements based on the type of the
1193  /// corresponding operand.  This returns null if there is no replacement to
1194  /// make.
1195  virtual const char *LowerXConstraint(MVT ConstraintVT) const;
1196
1197  /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
1198  /// vector.  If it is invalid, don't add anything to Ops.
1199  virtual void LowerAsmOperandForConstraint(SDValue Op, char ConstraintLetter,
1200                                            std::vector<SDValue> &Ops,
1201                                            SelectionDAG &DAG) const;
1202
1203  //===--------------------------------------------------------------------===//
1204  // Scheduler hooks
1205  //
1206
1207  // EmitInstrWithCustomInserter - This method should be implemented by targets
1208  // that mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
1209  // instructions are special in various ways, which require special support to
1210  // insert.  The specified MachineInstr is created but not inserted into any
1211  // basic blocks, and the scheduler passes ownership of it to this method.
1212  virtual MachineBasicBlock *EmitInstrWithCustomInserter(MachineInstr *MI,
1213                                                        MachineBasicBlock *MBB);
1214
1215  //===--------------------------------------------------------------------===//
1216  // Addressing mode description hooks (used by LSR etc).
1217  //
1218
1219  /// AddrMode - This represents an addressing mode of:
1220  ///    BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
1221  /// If BaseGV is null,  there is no BaseGV.
1222  /// If BaseOffs is zero, there is no base offset.
1223  /// If HasBaseReg is false, there is no base register.
1224  /// If Scale is zero, there is no ScaleReg.  Scale of 1 indicates a reg with
1225  /// no scale.
1226  ///
1227  struct AddrMode {
1228    GlobalValue *BaseGV;
1229    int64_t      BaseOffs;
1230    bool         HasBaseReg;
1231    int64_t      Scale;
1232    AddrMode() : BaseGV(0), BaseOffs(0), HasBaseReg(false), Scale(0) {}
1233  };
1234
1235  /// isLegalAddressingMode - Return true if the addressing mode represented by
1236  /// AM is legal for this target, for a load/store of the specified type.
1237  /// TODO: Handle pre/postinc as well.
1238  virtual bool isLegalAddressingMode(const AddrMode &AM, const Type *Ty) const;
1239
1240  /// isTruncateFree - Return true if it's free to truncate a value of
1241  /// type Ty1 to type Ty2. e.g. On x86 it's free to truncate a i32 value in
1242  /// register EAX to i16 by referencing its sub-register AX.
1243  virtual bool isTruncateFree(const Type *Ty1, const Type *Ty2) const {
1244    return false;
1245  }
1246
1247  virtual bool isTruncateFree(MVT VT1, MVT VT2) const {
1248    return false;
1249  }
1250
1251  //===--------------------------------------------------------------------===//
1252  // Div utility functions
1253  //
1254  SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG,
1255                      std::vector<SDNode*>* Created) const;
1256  SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG,
1257                      std::vector<SDNode*>* Created) const;
1258
1259
1260  //===--------------------------------------------------------------------===//
1261  // Runtime Library hooks
1262  //
1263
1264  /// setLibcallName - Rename the default libcall routine name for the specified
1265  /// libcall.
1266  void setLibcallName(RTLIB::Libcall Call, const char *Name) {
1267    LibcallRoutineNames[Call] = Name;
1268  }
1269
1270  /// getLibcallName - Get the libcall routine name for the specified libcall.
1271  ///
1272  const char *getLibcallName(RTLIB::Libcall Call) const {
1273    return LibcallRoutineNames[Call];
1274  }
1275
1276  /// setCmpLibcallCC - Override the default CondCode to be used to test the
1277  /// result of the comparison libcall against zero.
1278  void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
1279    CmpLibcallCCs[Call] = CC;
1280  }
1281
1282  /// getCmpLibcallCC - Get the CondCode that's to be used to test the result of
1283  /// the comparison libcall against zero.
1284  ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
1285    return CmpLibcallCCs[Call];
1286  }
1287
1288private:
1289  TargetMachine &TM;
1290  const TargetData *TD;
1291
1292  /// PointerTy - The type to use for pointers, usually i32 or i64.
1293  ///
1294  MVT PointerTy;
1295
1296  /// IsLittleEndian - True if this is a little endian target.
1297  ///
1298  bool IsLittleEndian;
1299
1300  /// UsesGlobalOffsetTable - True if this target uses a GOT for PIC codegen.
1301  ///
1302  bool UsesGlobalOffsetTable;
1303
1304  /// SelectIsExpensive - Tells the code generator not to expand operations
1305  /// into sequences that use the select operations if possible.
1306  bool SelectIsExpensive;
1307
1308  /// IntDivIsCheap - Tells the code generator not to expand integer divides by
1309  /// constants into a sequence of muls, adds, and shifts.  This is a hack until
1310  /// a real cost model is in place.  If we ever optimize for size, this will be
1311  /// set to true unconditionally.
1312  bool IntDivIsCheap;
1313
1314  /// Pow2DivIsCheap - Tells the code generator that it shouldn't generate
1315  /// srl/add/sra for a signed divide by power of two, and let the target handle
1316  /// it.
1317  bool Pow2DivIsCheap;
1318
1319  /// UseUnderscoreSetJmp - This target prefers to use _setjmp to implement
1320  /// llvm.setjmp.  Defaults to false.
1321  bool UseUnderscoreSetJmp;
1322
1323  /// UseUnderscoreLongJmp - This target prefers to use _longjmp to implement
1324  /// llvm.longjmp.  Defaults to false.
1325  bool UseUnderscoreLongJmp;
1326
1327  /// ShiftAmountTy - The type to use for shift amounts, usually i8 or whatever
1328  /// PointerTy is.
1329  MVT ShiftAmountTy;
1330
1331  OutOfRangeShiftAmount ShiftAmtHandling;
1332
1333  /// SetCCResultContents - Information about the contents of the high-bits in
1334  /// the result of a setcc comparison operation.
1335  SetCCResultValue SetCCResultContents;
1336
1337  /// SchedPreferenceInfo - The target scheduling preference: shortest possible
1338  /// total cycles or lowest register usage.
1339  SchedPreference SchedPreferenceInfo;
1340
1341  /// JumpBufSize - The size, in bytes, of the target's jmp_buf buffers
1342  unsigned JumpBufSize;
1343
1344  /// JumpBufAlignment - The alignment, in bytes, of the target's jmp_buf
1345  /// buffers
1346  unsigned JumpBufAlignment;
1347
1348  /// IfCvtBlockSizeLimit - The maximum allowed size for a block to be
1349  /// if-converted.
1350  unsigned IfCvtBlockSizeLimit;
1351
1352  /// IfCvtDupBlockSizeLimit - The maximum allowed size for a block to be
1353  /// duplicated during if-conversion.
1354  unsigned IfCvtDupBlockSizeLimit;
1355
1356  /// PrefLoopAlignment - The perferred loop alignment.
1357  ///
1358  unsigned PrefLoopAlignment;
1359
1360  /// StackPointerRegisterToSaveRestore - If set to a physical register, this
1361  /// specifies the register that llvm.savestack/llvm.restorestack should save
1362  /// and restore.
1363  unsigned StackPointerRegisterToSaveRestore;
1364
1365  /// ExceptionPointerRegister - If set to a physical register, this specifies
1366  /// the register that receives the exception address on entry to a landing
1367  /// pad.
1368  unsigned ExceptionPointerRegister;
1369
1370  /// ExceptionSelectorRegister - If set to a physical register, this specifies
1371  /// the register that receives the exception typeid on entry to a landing
1372  /// pad.
1373  unsigned ExceptionSelectorRegister;
1374
1375  /// RegClassForVT - This indicates the default register class to use for
1376  /// each ValueType the target supports natively.
1377  TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
1378  unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
1379  MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
1380
1381  /// TransformToType - For any value types we are promoting or expanding, this
1382  /// contains the value type that we are changing to.  For Expanded types, this
1383  /// contains one step of the expand (e.g. i64 -> i32), even if there are
1384  /// multiple steps required (e.g. i64 -> i16).  For types natively supported
1385  /// by the system, this holds the same type (e.g. i32 -> i32).
1386  MVT TransformToType[MVT::LAST_VALUETYPE];
1387
1388  // Defines the capacity of the TargetLowering::OpActions table
1389  static const int OpActionsCapacity = 212;
1390
1391  /// OpActions - For each operation and each value type, keep a LegalizeAction
1392  /// that indicates how instruction selection should deal with the operation.
1393  /// Most operations are Legal (aka, supported natively by the target), but
1394  /// operations that are not should be described.  Note that operations on
1395  /// non-legal value types are not described here.
1396  uint64_t OpActions[OpActionsCapacity];
1397
1398  /// LoadXActions - For each load of load extension type and each value type,
1399  /// keep a LegalizeAction that indicates how instruction selection should deal
1400  /// with the load.
1401  uint64_t LoadXActions[ISD::LAST_LOADX_TYPE];
1402
1403  /// TruncStoreActions - For each truncating store, keep a LegalizeAction that
1404  /// indicates how instruction selection should deal with the store.
1405  uint64_t TruncStoreActions[MVT::LAST_VALUETYPE];
1406
1407  /// IndexedModeActions - For each indexed mode and each value type, keep a
1408  /// pair of LegalizeAction that indicates how instruction selection should
1409  /// deal with the load / store.
1410  uint64_t IndexedModeActions[2][ISD::LAST_INDEXED_MODE];
1411
1412  /// ConvertActions - For each conversion from source type to destination type,
1413  /// keep a LegalizeAction that indicates how instruction selection should
1414  /// deal with the conversion.
1415  /// Currently, this is used only for floating->floating conversions
1416  /// (FP_EXTEND and FP_ROUND).
1417  uint64_t ConvertActions[MVT::LAST_VALUETYPE];
1418
1419  ValueTypeActionImpl ValueTypeActions;
1420
1421  std::vector<APFloat> LegalFPImmediates;
1422
1423  std::vector<std::pair<MVT, TargetRegisterClass*> > AvailableRegClasses;
1424
1425  /// TargetDAGCombineArray - Targets can specify ISD nodes that they would
1426  /// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(),
1427  /// which sets a bit in this array.
1428  unsigned char
1429  TargetDAGCombineArray[OpActionsCapacity/(sizeof(unsigned char)*8)];
1430
1431  /// PromoteToType - For operations that must be promoted to a specific type,
1432  /// this holds the destination type.  This map should be sparse, so don't hold
1433  /// it as an array.
1434  ///
1435  /// Targets add entries to this map with AddPromotedToType(..), clients access
1436  /// this with getTypeToPromoteTo(..).
1437  std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
1438    PromoteToType;
1439
1440  /// LibcallRoutineNames - Stores the name each libcall.
1441  ///
1442  const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
1443
1444  /// CmpLibcallCCs - The ISD::CondCode that should be used to test the result
1445  /// of each of the comparison libcall against zero.
1446  ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
1447
1448protected:
1449  /// When lowering @llvm.memset this field specifies the maximum number of
1450  /// store operations that may be substituted for the call to memset. Targets
1451  /// must set this value based on the cost threshold for that target. Targets
1452  /// should assume that the memset will be done using as many of the largest
1453  /// store operations first, followed by smaller ones, if necessary, per
1454  /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
1455  /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
1456  /// store.  This only applies to setting a constant array of a constant size.
1457  /// @brief Specify maximum number of store instructions per memset call.
1458  unsigned maxStoresPerMemset;
1459
1460  /// When lowering @llvm.memcpy this field specifies the maximum number of
1461  /// store operations that may be substituted for a call to memcpy. Targets
1462  /// must set this value based on the cost threshold for that target. Targets
1463  /// should assume that the memcpy will be done using as many of the largest
1464  /// store operations first, followed by smaller ones, if necessary, per
1465  /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
1466  /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
1467  /// and one 1-byte store. This only applies to copying a constant array of
1468  /// constant size.
1469  /// @brief Specify maximum bytes of store instructions per memcpy call.
1470  unsigned maxStoresPerMemcpy;
1471
1472  /// When lowering @llvm.memmove this field specifies the maximum number of
1473  /// store instructions that may be substituted for a call to memmove. Targets
1474  /// must set this value based on the cost threshold for that target. Targets
1475  /// should assume that the memmove will be done using as many of the largest
1476  /// store operations first, followed by smaller ones, if necessary, per
1477  /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
1478  /// with 8-bit alignment would result in nine 1-byte stores.  This only
1479  /// applies to copying a constant array of constant size.
1480  /// @brief Specify maximum bytes of store instructions per memmove call.
1481  unsigned maxStoresPerMemmove;
1482
1483  /// This field specifies whether the target machine permits unaligned memory
1484  /// accesses.  This is used, for example, to determine the size of store
1485  /// operations when copying small arrays and other similar tasks.
1486  /// @brief Indicate whether the target permits unaligned memory accesses.
1487  bool allowUnalignedMemoryAccesses;
1488};
1489} // end llvm namespace
1490
1491#endif
1492