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