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