TargetLowering.h revision 425b76c2314ff7ee7ad507011bdda1988ae481ef
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/// \file
11/// This file describes how to lower LLVM code to machine code.  This has two
12/// main components:
13///
14///  1. Which ValueTypes are natively supported by the target.
15///  2. Which operations are supported for supported ValueTypes.
16///  3. Cost thresholds for alternative implementations of certain operations.
17///
18/// In addition it has a few other components, like information about FP
19/// immediates.
20///
21//===----------------------------------------------------------------------===//
22
23#ifndef LLVM_TARGET_TARGETLOWERING_H
24#define LLVM_TARGET_TARGETLOWERING_H
25
26#include "llvm/ADT/DenseMap.h"
27#include "llvm/CodeGen/DAGCombine.h"
28#include "llvm/CodeGen/RuntimeLibcalls.h"
29#include "llvm/CodeGen/SelectionDAGNodes.h"
30#include "llvm/IR/Attributes.h"
31#include "llvm/IR/CallingConv.h"
32#include "llvm/IR/InlineAsm.h"
33#include "llvm/Support/CallSite.h"
34#include "llvm/Target/TargetCallingConv.h"
35#include "llvm/Target/TargetMachine.h"
36#include <climits>
37#include <map>
38#include <vector>
39
40namespace llvm {
41  class CallInst;
42  class CCState;
43  class FastISel;
44  class FunctionLoweringInfo;
45  class ImmutableCallSite;
46  class IntrinsicInst;
47  class MachineBasicBlock;
48  class MachineFunction;
49  class MachineInstr;
50  class MachineJumpTableInfo;
51  class MCContext;
52  class MCExpr;
53  template<typename T> class SmallVectorImpl;
54  class DataLayout;
55  class TargetRegisterClass;
56  class TargetLibraryInfo;
57  class TargetLoweringObjectFile;
58  class Value;
59
60  namespace Sched {
61    enum Preference {
62      None,             // No preference
63      Source,           // Follow source order.
64      RegPressure,      // Scheduling for lowest register pressure.
65      Hybrid,           // Scheduling for both latency and register pressure.
66      ILP,              // Scheduling for ILP in low register pressure mode.
67      VLIW              // Scheduling for VLIW targets.
68    };
69  }
70
71/// This base class for TargetLowering contains the SelectionDAG-independent
72/// parts that can be used from the rest of CodeGen.
73class TargetLoweringBase {
74  TargetLoweringBase(const TargetLoweringBase&) LLVM_DELETED_FUNCTION;
75  void operator=(const TargetLoweringBase&) LLVM_DELETED_FUNCTION;
76
77public:
78  /// This enum indicates whether operations are valid for a target, and if not,
79  /// what action should be used to make them valid.
80  enum LegalizeAction {
81    Legal,      // The target natively supports this operation.
82    Promote,    // This operation should be executed in a larger type.
83    Expand,     // Try to expand this to other ops, otherwise use a libcall.
84    Custom      // Use the LowerOperation hook to implement custom lowering.
85  };
86
87  /// This enum indicates whether a types are legal for a target, and if not,
88  /// what action should be used to make them valid.
89  enum LegalizeTypeAction {
90    TypeLegal,           // The target natively supports this type.
91    TypePromoteInteger,  // Replace this integer with a larger one.
92    TypeExpandInteger,   // Split this integer into two of half the size.
93    TypeSoftenFloat,     // Convert this float to a same size integer type.
94    TypeExpandFloat,     // Split this float into two of half the size.
95    TypeScalarizeVector, // Replace this one-element vector with its element.
96    TypeSplitVector,     // Split this vector into two of half the size.
97    TypeWidenVector      // This vector should be widened into a larger vector.
98  };
99
100  /// LegalizeKind holds the legalization kind that needs to happen to EVT
101  /// in order to type-legalize it.
102  typedef std::pair<LegalizeTypeAction, EVT> LegalizeKind;
103
104  /// Enum that describes how the target represents true/false values.
105  enum BooleanContent {
106    UndefinedBooleanContent,    // Only bit 0 counts, the rest can hold garbage.
107    ZeroOrOneBooleanContent,        // All bits zero except for bit 0.
108    ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
109  };
110
111  /// Enum that describes what type of support for selects the target has.
112  enum SelectSupportKind {
113    ScalarValSelect,      // The target supports scalar selects (ex: cmov).
114    ScalarCondVectorVal,  // The target supports selects with a scalar condition
115                          // and vector values (ex: cmov).
116    VectorMaskSelect      // The target supports vector selects with a vector
117                          // mask (ex: x86 blends).
118  };
119
120  static ISD::NodeType getExtendForContent(BooleanContent Content) {
121    switch (Content) {
122    case UndefinedBooleanContent:
123      // Extend by adding rubbish bits.
124      return ISD::ANY_EXTEND;
125    case ZeroOrOneBooleanContent:
126      // Extend by adding zero bits.
127      return ISD::ZERO_EXTEND;
128    case ZeroOrNegativeOneBooleanContent:
129      // Extend by copying the sign bit.
130      return ISD::SIGN_EXTEND;
131    }
132    llvm_unreachable("Invalid content kind");
133  }
134
135  /// NOTE: The constructor takes ownership of TLOF.
136  explicit TargetLoweringBase(const TargetMachine &TM,
137                              const TargetLoweringObjectFile *TLOF);
138  virtual ~TargetLoweringBase();
139
140protected:
141  /// \brief Initialize all of the actions to default values.
142  void initActions();
143
144public:
145  const TargetMachine &getTargetMachine() const { return TM; }
146  const DataLayout *getDataLayout() const { return TD; }
147  const TargetLoweringObjectFile &getObjFileLowering() const { return TLOF; }
148
149  bool isBigEndian() const { return !IsLittleEndian; }
150  bool isLittleEndian() const { return IsLittleEndian; }
151  // Return the pointer type for the given address space, defaults to
152  // the pointer type from the data layout.
153  // FIXME: The default needs to be removed once all the code is updated.
154  virtual MVT getPointerTy(uint32_t /*AS*/ = 0) const { return PointerTy; }
155  virtual MVT getScalarShiftAmountTy(EVT LHSTy) const;
156
157  EVT getShiftAmountTy(EVT LHSTy) const;
158
159  /// Returns the type to be used for the index operand of:
160  /// ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
161  /// ISD::INSERT_SUBVECTOR, and ISD::EXTRACT_SUBVECTOR
162  virtual MVT getVectorIdxTy() const {
163    return getPointerTy();
164  }
165
166  /// Return true if the select operation is expensive for this target.
167  bool isSelectExpensive() const { return SelectIsExpensive; }
168
169  virtual bool isSelectSupported(SelectSupportKind /*kind*/) const {
170    return true;
171  }
172
173  /// Return true if a vector of the given type should be split
174  /// (TypeSplitVector) instead of promoted (TypePromoteInteger) during type
175  /// legalization.
176  virtual bool shouldSplitVectorElementType(EVT /*VT*/) const { return false; }
177
178  /// Return true if integer divide is usually cheaper than a sequence of
179  /// several shifts, adds, and multiplies for this target.
180  bool isIntDivCheap() const { return IntDivIsCheap; }
181
182  /// Returns true if target has indicated at least one type should be bypassed.
183  bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
184
185  /// Returns map of slow types for division or remainder with corresponding
186  /// fast types
187  const DenseMap<unsigned int, unsigned int> &getBypassSlowDivWidths() const {
188    return BypassSlowDivWidths;
189  }
190
191  /// Return true if pow2 div is cheaper than a chain of srl/add/sra.
192  bool isPow2DivCheap() const { return Pow2DivIsCheap; }
193
194  /// Return true if Flow Control is an expensive operation that should be
195  /// avoided.
196  bool isJumpExpensive() const { return JumpIsExpensive; }
197
198  /// Return true if selects are only cheaper than branches if the branch is
199  /// unlikely to be predicted right.
200  bool isPredictableSelectExpensive() const {
201    return PredictableSelectIsExpensive;
202  }
203
204  /// Return the ValueType of the result of SETCC operations.  Also used to
205  /// obtain the target's preferred type for the condition operand of SELECT and
206  /// BRCOND nodes.  In the case of BRCOND the argument passed is MVT::Other
207  /// since there are no other operands to get a type hint from.
208  virtual EVT getSetCCResultType(LLVMContext &Context, EVT VT) const;
209
210  /// Return the ValueType for comparison libcalls. Comparions libcalls include
211  /// floating point comparion calls, and Ordered/Unordered check calls on
212  /// floating point numbers.
213  virtual
214  MVT::SimpleValueType getCmpLibcallReturnType() const;
215
216  /// For targets without i1 registers, this gives the nature of the high-bits
217  /// of boolean values held in types wider than i1.
218  ///
219  /// "Boolean values" are special true/false values produced by nodes like
220  /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
221  /// Not to be confused with general values promoted from i1.  Some cpus
222  /// distinguish between vectors of boolean and scalars; the isVec parameter
223  /// selects between the two kinds.  For example on X86 a scalar boolean should
224  /// be zero extended from i1, while the elements of a vector of booleans
225  /// should be sign extended from i1.
226  BooleanContent getBooleanContents(bool isVec) const {
227    return isVec ? BooleanVectorContents : BooleanContents;
228  }
229
230  /// Return target scheduling preference.
231  Sched::Preference getSchedulingPreference() const {
232    return SchedPreferenceInfo;
233  }
234
235  /// Some scheduler, e.g. hybrid, can switch to different scheduling heuristics
236  /// for different nodes. This function returns the preference (or none) for
237  /// the given node.
238  virtual Sched::Preference getSchedulingPreference(SDNode *) const {
239    return Sched::None;
240  }
241
242  /// Return the register class that should be used for the specified value
243  /// type.
244  virtual const TargetRegisterClass *getRegClassFor(MVT VT) const {
245    const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
246    assert(RC && "This value type is not natively supported!");
247    return RC;
248  }
249
250  /// Return the 'representative' register class for the specified value
251  /// type.
252  ///
253  /// The 'representative' register class is the largest legal super-reg
254  /// register class for the register class of the value type.  For example, on
255  /// i386 the rep register class for i8, i16, and i32 are GR32; while the rep
256  /// register class is GR64 on x86_64.
257  virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
258    const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
259    return RC;
260  }
261
262  /// Return the cost of the 'representative' register class for the specified
263  /// value type.
264  virtual uint8_t getRepRegClassCostFor(MVT VT) const {
265    return RepRegClassCostForVT[VT.SimpleTy];
266  }
267
268  /// Return true if the target has native support for the specified value type.
269  /// This means that it has a register that directly holds it without
270  /// promotions or expansions.
271  bool isTypeLegal(EVT VT) const {
272    assert(!VT.isSimple() ||
273           (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
274    return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != 0;
275  }
276
277  class ValueTypeActionImpl {
278    /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
279    /// that indicates how instruction selection should deal with the type.
280    uint8_t ValueTypeActions[MVT::LAST_VALUETYPE];
281
282  public:
283    ValueTypeActionImpl() {
284      std::fill(ValueTypeActions, array_endof(ValueTypeActions), 0);
285    }
286
287    LegalizeTypeAction getTypeAction(MVT VT) const {
288      return (LegalizeTypeAction)ValueTypeActions[VT.SimpleTy];
289    }
290
291    void setTypeAction(MVT VT, LegalizeTypeAction Action) {
292      unsigned I = VT.SimpleTy;
293      ValueTypeActions[I] = Action;
294    }
295  };
296
297  const ValueTypeActionImpl &getValueTypeActions() const {
298    return ValueTypeActions;
299  }
300
301  /// Return how we should legalize values of this type, either it is already
302  /// legal (return 'Legal') or we need to promote it to a larger type (return
303  /// 'Promote'), or we need to expand it into multiple registers of smaller
304  /// integer type (return 'Expand').  'Custom' is not an option.
305  LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const {
306    return getTypeConversion(Context, VT).first;
307  }
308  LegalizeTypeAction getTypeAction(MVT VT) const {
309    return ValueTypeActions.getTypeAction(VT);
310  }
311
312  /// For types supported by the target, this is an identity function.  For
313  /// types that must be promoted to larger types, this returns the larger type
314  /// to promote to.  For integer types that are larger than the largest integer
315  /// register, this contains one step in the expansion to get to the smaller
316  /// register. For illegal floating point types, this returns the integer type
317  /// to transform to.
318  EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
319    return getTypeConversion(Context, VT).second;
320  }
321
322  /// For types supported by the target, this is an identity function.  For
323  /// types that must be expanded (i.e. integer types that are larger than the
324  /// largest integer register or illegal floating point types), this returns
325  /// the largest legal type it will be expanded to.
326  EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
327    assert(!VT.isVector());
328    while (true) {
329      switch (getTypeAction(Context, VT)) {
330      case TypeLegal:
331        return VT;
332      case TypeExpandInteger:
333        VT = getTypeToTransformTo(Context, VT);
334        break;
335      default:
336        llvm_unreachable("Type is not legal nor is it to be expanded!");
337      }
338    }
339  }
340
341  /// Vector types are broken down into some number of legal first class types.
342  /// For example, EVT::v8f32 maps to 2 EVT::v4f32 with Altivec or SSE1, or 8
343  /// promoted EVT::f64 values with the X86 FP stack.  Similarly, EVT::v2i64
344  /// turns into 4 EVT::i32 values with both PPC and X86.
345  ///
346  /// This method returns the number of registers needed, and the VT for each
347  /// register.  It also returns the VT and quantity of the intermediate values
348  /// before they are promoted/expanded.
349  unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
350                                  EVT &IntermediateVT,
351                                  unsigned &NumIntermediates,
352                                  MVT &RegisterVT) const;
353
354  struct IntrinsicInfo {
355    unsigned     opc;         // target opcode
356    EVT          memVT;       // memory VT
357    const Value* ptrVal;      // value representing memory location
358    int          offset;      // offset off of ptrVal
359    unsigned     align;       // alignment
360    bool         vol;         // is volatile?
361    bool         readMem;     // reads memory?
362    bool         writeMem;    // writes memory?
363  };
364
365  /// Given an intrinsic, checks if on the target the intrinsic will need to map
366  /// to a MemIntrinsicNode (touches memory). If this is the case, it returns
367  /// true and store the intrinsic information into the IntrinsicInfo that was
368  /// passed to the function.
369  virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
370                                  unsigned /*Intrinsic*/) const {
371    return false;
372  }
373
374  /// Returns true if the target can instruction select the specified FP
375  /// immediate natively. If false, the legalizer will materialize the FP
376  /// immediate as a load from a constant pool.
377  virtual bool isFPImmLegal(const APFloat &/*Imm*/, EVT /*VT*/) const {
378    return false;
379  }
380
381  /// Targets can use this to indicate that they only support *some*
382  /// VECTOR_SHUFFLE operations, those with specific masks.  By default, if a
383  /// target supports the VECTOR_SHUFFLE node, all mask values are assumed to be
384  /// legal.
385  virtual bool isShuffleMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
386                                  EVT /*VT*/) const {
387    return true;
388  }
389
390  /// Returns true if the operation can trap for the value type.
391  ///
392  /// VT must be a legal type. By default, we optimistically assume most
393  /// operations don't trap except for divide and remainder.
394  virtual bool canOpTrap(unsigned Op, EVT VT) const;
395
396  /// Similar to isShuffleMaskLegal. This is used by Targets can use this to
397  /// indicate if there is a suitable VECTOR_SHUFFLE that can be used to replace
398  /// a VAND with a constant pool entry.
399  virtual bool isVectorClearMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
400                                      EVT /*VT*/) const {
401    return false;
402  }
403
404  /// Return how this operation should be treated: either it is legal, needs to
405  /// be promoted to a larger size, needs to be expanded to some other code
406  /// sequence, or the target has a custom expander for it.
407  LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
408    if (VT.isExtended()) return Expand;
409    // If a target-specific SDNode requires legalization, require the target
410    // to provide custom legalization for it.
411    if (Op > array_lengthof(OpActions[0])) return Custom;
412    unsigned I = (unsigned) VT.getSimpleVT().SimpleTy;
413    return (LegalizeAction)OpActions[I][Op];
414  }
415
416  /// Return true if the specified operation is legal on this target or can be
417  /// made legal with custom lowering. This is used to help guide high-level
418  /// lowering decisions.
419  bool isOperationLegalOrCustom(unsigned Op, EVT VT) const {
420    return (VT == MVT::Other || isTypeLegal(VT)) &&
421      (getOperationAction(Op, VT) == Legal ||
422       getOperationAction(Op, VT) == Custom);
423  }
424
425  /// Return true if the specified operation is legal on this target or can be
426  /// made legal using promotion. This is used to help guide high-level lowering
427  /// decisions.
428  bool isOperationLegalOrPromote(unsigned Op, EVT VT) const {
429    return (VT == MVT::Other || isTypeLegal(VT)) &&
430      (getOperationAction(Op, VT) == Legal ||
431       getOperationAction(Op, VT) == Promote);
432  }
433
434  /// Return true if the specified operation is illegal on this target or
435  /// unlikely to be made legal with custom lowering. This is used to help guide
436  /// high-level lowering decisions.
437  bool isOperationExpand(unsigned Op, EVT VT) const {
438    return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
439  }
440
441  /// Return true if the specified operation is legal on this target.
442  bool isOperationLegal(unsigned Op, EVT VT) const {
443    return (VT == MVT::Other || isTypeLegal(VT)) &&
444           getOperationAction(Op, VT) == Legal;
445  }
446
447  /// Return how this load with extension should be treated: either it is legal,
448  /// needs to be promoted to a larger size, needs to be expanded to some other
449  /// code sequence, or the target has a custom expander for it.
450  LegalizeAction getLoadExtAction(unsigned ExtType, MVT VT) const {
451    assert(ExtType < ISD::LAST_LOADEXT_TYPE && VT < MVT::LAST_VALUETYPE &&
452           "Table isn't big enough!");
453    return (LegalizeAction)LoadExtActions[VT.SimpleTy][ExtType];
454  }
455
456  /// Return true if the specified load with extension is legal on this target.
457  bool isLoadExtLegal(unsigned ExtType, EVT VT) const {
458    return VT.isSimple() &&
459      getLoadExtAction(ExtType, VT.getSimpleVT()) == Legal;
460  }
461
462  /// Return how this store with truncation should be treated: either it is
463  /// legal, needs to be promoted to a larger size, needs to be expanded to some
464  /// other code sequence, or the target has a custom expander for it.
465  LegalizeAction getTruncStoreAction(MVT ValVT, MVT MemVT) const {
466    assert(ValVT < MVT::LAST_VALUETYPE && MemVT < MVT::LAST_VALUETYPE &&
467           "Table isn't big enough!");
468    return (LegalizeAction)TruncStoreActions[ValVT.SimpleTy]
469                                            [MemVT.SimpleTy];
470  }
471
472  /// Return true if the specified store with truncation is legal on this
473  /// target.
474  bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
475    return isTypeLegal(ValVT) && MemVT.isSimple() &&
476      getTruncStoreAction(ValVT.getSimpleVT(), MemVT.getSimpleVT()) == Legal;
477  }
478
479  /// Return how the indexed load should be treated: either it is legal, needs
480  /// to be promoted to a larger size, needs to be expanded to some other code
481  /// sequence, or the target has a custom expander for it.
482  LegalizeAction
483  getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
484    assert(IdxMode < ISD::LAST_INDEXED_MODE && VT < MVT::LAST_VALUETYPE &&
485           "Table isn't big enough!");
486    unsigned Ty = (unsigned)VT.SimpleTy;
487    return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] & 0xf0) >> 4);
488  }
489
490  /// Return true if the specified indexed load is legal on this target.
491  bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
492    return VT.isSimple() &&
493      (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
494       getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
495  }
496
497  /// Return how the indexed store should be treated: either it is legal, needs
498  /// to be promoted to a larger size, needs to be expanded to some other code
499  /// sequence, or the target has a custom expander for it.
500  LegalizeAction
501  getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
502    assert(IdxMode < ISD::LAST_INDEXED_MODE && VT < MVT::LAST_VALUETYPE &&
503           "Table isn't big enough!");
504    unsigned Ty = (unsigned)VT.SimpleTy;
505    return (LegalizeAction)(IndexedModeActions[Ty][IdxMode] & 0x0f);
506  }
507
508  /// Return true if the specified indexed load is legal on this target.
509  bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
510    return VT.isSimple() &&
511      (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
512       getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
513  }
514
515  /// Return how the condition code should be treated: either it is legal, needs
516  /// to be expanded to some other code sequence, or the target has a custom
517  /// expander for it.
518  LegalizeAction
519  getCondCodeAction(ISD::CondCode CC, MVT VT) const {
520    assert((unsigned)CC < array_lengthof(CondCodeActions) &&
521           (unsigned)VT.SimpleTy < sizeof(CondCodeActions[0])*4 &&
522           "Table isn't big enough!");
523    /// The lower 5 bits of the SimpleTy index into Nth 2bit set from the 64bit
524    /// value and the upper 27 bits index into the second dimension of the
525    /// array to select what 64bit value to use.
526    LegalizeAction Action = (LegalizeAction)
527      ((CondCodeActions[CC][VT.SimpleTy >> 5] >> (2*(VT.SimpleTy & 0x1F))) & 3);
528    assert(Action != Promote && "Can't promote condition code!");
529    return Action;
530  }
531
532  /// Return true if the specified condition code is legal on this target.
533  bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
534    return
535      getCondCodeAction(CC, VT) == Legal ||
536      getCondCodeAction(CC, VT) == Custom;
537  }
538
539
540  /// If the action for this operation is to promote, this method returns the
541  /// ValueType to promote to.
542  MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
543    assert(getOperationAction(Op, VT) == Promote &&
544           "This operation isn't promoted!");
545
546    // See if this has an explicit type specified.
547    std::map<std::pair<unsigned, MVT::SimpleValueType>,
548             MVT::SimpleValueType>::const_iterator PTTI =
549      PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
550    if (PTTI != PromoteToType.end()) return PTTI->second;
551
552    assert((VT.isInteger() || VT.isFloatingPoint()) &&
553           "Cannot autopromote this type, add it with AddPromotedToType.");
554
555    MVT NVT = VT;
556    do {
557      NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
558      assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
559             "Didn't find type to promote to!");
560    } while (!isTypeLegal(NVT) ||
561              getOperationAction(Op, NVT) == Promote);
562    return NVT;
563  }
564
565  /// Return the EVT corresponding to this LLVM type.  This is fixed by the LLVM
566  /// operations except for the pointer size.  If AllowUnknown is true, this
567  /// will return MVT::Other for types with no EVT counterpart (e.g. structs),
568  /// otherwise it will assert.
569  EVT getValueType(Type *Ty, bool AllowUnknown = false) const {
570    // Lower scalar pointers to native pointer types.
571    if (Ty->isPointerTy()) return PointerTy;
572
573    if (Ty->isVectorTy()) {
574      VectorType *VTy = cast<VectorType>(Ty);
575      Type *Elm = VTy->getElementType();
576      // Lower vectors of pointers to native pointer types.
577      if (Elm->isPointerTy())
578        Elm = EVT(PointerTy).getTypeForEVT(Ty->getContext());
579      return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
580                       VTy->getNumElements());
581    }
582    return EVT::getEVT(Ty, AllowUnknown);
583  }
584
585  /// Return the MVT corresponding to this LLVM type. See getValueType.
586  MVT getSimpleValueType(Type *Ty, bool AllowUnknown = false) const {
587    return getValueType(Ty, AllowUnknown).getSimpleVT();
588  }
589
590  /// Return the desired alignment for ByVal aggregate function arguments in the
591  /// caller parameter area.  This is the actual alignment, not its logarithm.
592  virtual unsigned getByValTypeAlignment(Type *Ty) const;
593
594  /// Return the type of registers that this ValueType will eventually require.
595  MVT getRegisterType(MVT VT) const {
596    assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
597    return RegisterTypeForVT[VT.SimpleTy];
598  }
599
600  /// Return the type of registers that this ValueType will eventually require.
601  MVT getRegisterType(LLVMContext &Context, EVT VT) const {
602    if (VT.isSimple()) {
603      assert((unsigned)VT.getSimpleVT().SimpleTy <
604                array_lengthof(RegisterTypeForVT));
605      return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
606    }
607    if (VT.isVector()) {
608      EVT VT1;
609      MVT RegisterVT;
610      unsigned NumIntermediates;
611      (void)getVectorTypeBreakdown(Context, VT, VT1,
612                                   NumIntermediates, RegisterVT);
613      return RegisterVT;
614    }
615    if (VT.isInteger()) {
616      return getRegisterType(Context, getTypeToTransformTo(Context, VT));
617    }
618    llvm_unreachable("Unsupported extended type!");
619  }
620
621  /// Return the number of registers that this ValueType will eventually
622  /// require.
623  ///
624  /// This is one for any types promoted to live in larger registers, but may be
625  /// more than one for types (like i64) that are split into pieces.  For types
626  /// like i140, which are first promoted then expanded, it is the number of
627  /// registers needed to hold all the bits of the original type.  For an i140
628  /// on a 32 bit machine this means 5 registers.
629  unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
630    if (VT.isSimple()) {
631      assert((unsigned)VT.getSimpleVT().SimpleTy <
632                array_lengthof(NumRegistersForVT));
633      return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
634    }
635    if (VT.isVector()) {
636      EVT VT1;
637      MVT VT2;
638      unsigned NumIntermediates;
639      return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
640    }
641    if (VT.isInteger()) {
642      unsigned BitWidth = VT.getSizeInBits();
643      unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
644      return (BitWidth + RegWidth - 1) / RegWidth;
645    }
646    llvm_unreachable("Unsupported extended type!");
647  }
648
649  /// If true, then instruction selection should seek to shrink the FP constant
650  /// of the specified type to a smaller type in order to save space and / or
651  /// reduce runtime.
652  virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
653
654  /// If true, the target has custom DAG combine transformations that it can
655  /// perform for the specified node.
656  bool hasTargetDAGCombine(ISD::NodeType NT) const {
657    assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
658    return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
659  }
660
661  /// \brief Get maximum # of store operations permitted for llvm.memset
662  ///
663  /// This function returns the maximum number of store operations permitted
664  /// to replace a call to llvm.memset. The value is set by the target at the
665  /// performance threshold for such a replacement. If OptSize is true,
666  /// return the limit for functions that have OptSize attribute.
667  unsigned getMaxStoresPerMemset(bool OptSize) const {
668    return OptSize ? MaxStoresPerMemsetOptSize : MaxStoresPerMemset;
669  }
670
671  /// \brief Get maximum # of store operations permitted for llvm.memcpy
672  ///
673  /// This function returns the maximum number of store operations permitted
674  /// to replace a call to llvm.memcpy. The value is set by the target at the
675  /// performance threshold for such a replacement. If OptSize is true,
676  /// return the limit for functions that have OptSize attribute.
677  unsigned getMaxStoresPerMemcpy(bool OptSize) const {
678    return OptSize ? MaxStoresPerMemcpyOptSize : MaxStoresPerMemcpy;
679  }
680
681  /// \brief Get maximum # of store operations permitted for llvm.memmove
682  ///
683  /// This function returns the maximum number of store operations permitted
684  /// to replace a call to llvm.memmove. The value is set by the target at the
685  /// performance threshold for such a replacement. If OptSize is true,
686  /// return the limit for functions that have OptSize attribute.
687  unsigned getMaxStoresPerMemmove(bool OptSize) const {
688    return OptSize ? MaxStoresPerMemmoveOptSize : MaxStoresPerMemmove;
689  }
690
691  /// \brief Determine if the target supports unaligned memory accesses.
692  ///
693  /// This function returns true if the target allows unaligned memory accesses.
694  /// of the specified type. If true, it also returns whether the unaligned
695  /// memory access is "fast" in the second argument by reference. This is used,
696  /// for example, in situations where an array copy/move/set is converted to a
697  /// sequence of store operations. It's use helps to ensure that such
698  /// replacements don't generate code that causes an alignment error (trap) on
699  /// the target machine.
700  virtual bool allowsUnalignedMemoryAccesses(EVT, bool * /*Fast*/ = 0) const {
701    return false;
702  }
703
704  /// Returns the target specific optimal type for load and store operations as
705  /// a result of memset, memcpy, and memmove lowering.
706  ///
707  /// If DstAlign is zero that means it's safe to destination alignment can
708  /// satisfy any constraint. Similarly if SrcAlign is zero it means there isn't
709  /// a need to check it against alignment requirement, probably because the
710  /// source does not need to be loaded. If 'IsMemset' is true, that means it's
711  /// expanding a memset. If 'ZeroMemset' is true, that means it's a memset of
712  /// zero. 'MemcpyStrSrc' indicates whether the memcpy source is constant so it
713  /// does not need to be loaded.  It returns EVT::Other if the type should be
714  /// determined using generic target-independent logic.
715  virtual EVT getOptimalMemOpType(uint64_t /*Size*/,
716                                  unsigned /*DstAlign*/, unsigned /*SrcAlign*/,
717                                  bool /*IsMemset*/,
718                                  bool /*ZeroMemset*/,
719                                  bool /*MemcpyStrSrc*/,
720                                  MachineFunction &/*MF*/) const {
721    return MVT::Other;
722  }
723
724  /// Returns true if it's safe to use load / store of the specified type to
725  /// expand memcpy / memset inline.
726  ///
727  /// This is mostly true for all types except for some special cases. For
728  /// example, on X86 targets without SSE2 f64 load / store are done with fldl /
729  /// fstpl which also does type conversion. Note the specified type doesn't
730  /// have to be legal as the hook is used before type legalization.
731  virtual bool isSafeMemOpType(MVT /*VT*/) const { return true; }
732
733  /// Determine if we should use _setjmp or setjmp to implement llvm.setjmp.
734  bool usesUnderscoreSetJmp() const {
735    return UseUnderscoreSetJmp;
736  }
737
738  /// Determine if we should use _longjmp or longjmp to implement llvm.longjmp.
739  bool usesUnderscoreLongJmp() const {
740    return UseUnderscoreLongJmp;
741  }
742
743  /// Return whether the target can generate code for jump tables.
744  bool supportJumpTables() const {
745    return SupportJumpTables;
746  }
747
748  /// Return integer threshold on number of blocks to use jump tables rather
749  /// than if sequence.
750  int getMinimumJumpTableEntries() const {
751    return MinimumJumpTableEntries;
752  }
753
754  /// If a physical register, this specifies the register that
755  /// llvm.savestack/llvm.restorestack should save and restore.
756  unsigned getStackPointerRegisterToSaveRestore() const {
757    return StackPointerRegisterToSaveRestore;
758  }
759
760  /// If a physical register, this returns the register that receives the
761  /// exception address on entry to a landing pad.
762  unsigned getExceptionPointerRegister() const {
763    return ExceptionPointerRegister;
764  }
765
766  /// If a physical register, this returns the register that receives the
767  /// exception typeid on entry to a landing pad.
768  unsigned getExceptionSelectorRegister() const {
769    return ExceptionSelectorRegister;
770  }
771
772  /// Returns the target's jmp_buf size in bytes (if never set, the default is
773  /// 200)
774  unsigned getJumpBufSize() const {
775    return JumpBufSize;
776  }
777
778  /// Returns the target's jmp_buf alignment in bytes (if never set, the default
779  /// is 0)
780  unsigned getJumpBufAlignment() const {
781    return JumpBufAlignment;
782  }
783
784  /// Return the minimum stack alignment of an argument.
785  unsigned getMinStackArgumentAlignment() const {
786    return MinStackArgumentAlignment;
787  }
788
789  /// Return the minimum function alignment.
790  unsigned getMinFunctionAlignment() const {
791    return MinFunctionAlignment;
792  }
793
794  /// Return the preferred function alignment.
795  unsigned getPrefFunctionAlignment() const {
796    return PrefFunctionAlignment;
797  }
798
799  /// Return the preferred loop alignment.
800  unsigned getPrefLoopAlignment() const {
801    return PrefLoopAlignment;
802  }
803
804  /// Return whether the DAG builder should automatically insert fences and
805  /// reduce ordering for atomics.
806  bool getInsertFencesForAtomic() const {
807    return InsertFencesForAtomic;
808  }
809
810  /// Return true if the target stores stack protector cookies at a fixed offset
811  /// in some non-standard address space, and populates the address space and
812  /// offset as appropriate.
813  virtual bool getStackCookieLocation(unsigned &/*AddressSpace*/,
814                                      unsigned &/*Offset*/) const {
815    return false;
816  }
817
818  /// Returns the maximal possible offset which can be used for loads / stores
819  /// from the global.
820  virtual unsigned getMaximalGlobalOffset() const {
821    return 0;
822  }
823
824  //===--------------------------------------------------------------------===//
825  /// \name Helpers for TargetTransformInfo implementations
826  /// @{
827
828  /// Get the ISD node that corresponds to the Instruction class opcode.
829  int InstructionOpcodeToISD(unsigned Opcode) const;
830
831  /// Estimate the cost of type-legalization and the legalized type.
832  std::pair<unsigned, MVT> getTypeLegalizationCost(Type *Ty) const;
833
834  /// @}
835
836  //===--------------------------------------------------------------------===//
837  // TargetLowering Configuration Methods - These methods should be invoked by
838  // the derived class constructor to configure this object for the target.
839  //
840
841  /// \brief Reset the operation actions based on target options.
842  virtual void resetOperationActions() {}
843
844protected:
845  /// Specify how the target extends the result of a boolean value from i1 to a
846  /// wider type.  See getBooleanContents.
847  void setBooleanContents(BooleanContent Ty) { BooleanContents = Ty; }
848
849  /// Specify how the target extends the result of a vector boolean value from a
850  /// vector of i1 to a wider type.  See getBooleanContents.
851  void setBooleanVectorContents(BooleanContent Ty) {
852    BooleanVectorContents = Ty;
853  }
854
855  /// Specify the target scheduling preference.
856  void setSchedulingPreference(Sched::Preference Pref) {
857    SchedPreferenceInfo = Pref;
858  }
859
860  /// Indicate whether this target prefers to use _setjmp to implement
861  /// llvm.setjmp or the non _ version.  Defaults to false.
862  void setUseUnderscoreSetJmp(bool Val) {
863    UseUnderscoreSetJmp = Val;
864  }
865
866  /// Indicate whether this target prefers to use _longjmp to implement
867  /// llvm.longjmp or the non _ version.  Defaults to false.
868  void setUseUnderscoreLongJmp(bool Val) {
869    UseUnderscoreLongJmp = Val;
870  }
871
872  /// Indicate whether the target can generate code for jump tables.
873  void setSupportJumpTables(bool Val) {
874    SupportJumpTables = Val;
875  }
876
877  /// Indicate the number of blocks to generate jump tables rather than if
878  /// sequence.
879  void setMinimumJumpTableEntries(int Val) {
880    MinimumJumpTableEntries = Val;
881  }
882
883  /// If set to a physical register, this specifies the register that
884  /// llvm.savestack/llvm.restorestack should save and restore.
885  void setStackPointerRegisterToSaveRestore(unsigned R) {
886    StackPointerRegisterToSaveRestore = R;
887  }
888
889  /// If set to a physical register, this sets the register that receives the
890  /// exception address on entry to a landing pad.
891  void setExceptionPointerRegister(unsigned R) {
892    ExceptionPointerRegister = R;
893  }
894
895  /// If set to a physical register, this sets the register that receives the
896  /// exception typeid on entry to a landing pad.
897  void setExceptionSelectorRegister(unsigned R) {
898    ExceptionSelectorRegister = R;
899  }
900
901  /// Tells the code generator not to expand operations into sequences that use
902  /// the select operations if possible.
903  void setSelectIsExpensive(bool isExpensive = true) {
904    SelectIsExpensive = isExpensive;
905  }
906
907  /// Tells the code generator not to expand sequence of operations into a
908  /// separate sequences that increases the amount of flow control.
909  void setJumpIsExpensive(bool isExpensive = true) {
910    JumpIsExpensive = isExpensive;
911  }
912
913  /// Tells the code generator that integer divide is expensive, and if
914  /// possible, should be replaced by an alternate sequence of instructions not
915  /// containing an integer divide.
916  void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
917
918  /// Tells the code generator which bitwidths to bypass.
919  void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
920    BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
921  }
922
923  /// Tells the code generator that it shouldn't generate srl/add/sra for a
924  /// signed divide by power of two, and let the target handle it.
925  void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
926
927  /// Add the specified register class as an available regclass for the
928  /// specified value type. This indicates the selector can handle values of
929  /// that class natively.
930  void addRegisterClass(MVT VT, const TargetRegisterClass *RC) {
931    assert((unsigned)VT.SimpleTy < array_lengthof(RegClassForVT));
932    AvailableRegClasses.push_back(std::make_pair(VT, RC));
933    RegClassForVT[VT.SimpleTy] = RC;
934  }
935
936  /// Remove all register classes.
937  void clearRegisterClasses() {
938    memset(RegClassForVT, 0,MVT::LAST_VALUETYPE * sizeof(TargetRegisterClass*));
939
940    AvailableRegClasses.clear();
941  }
942
943  /// \brief Remove all operation actions.
944  void clearOperationActions() {
945  }
946
947  /// Return the largest legal super-reg register class of the register class
948  /// for the specified type and its associated "cost".
949  virtual std::pair<const TargetRegisterClass*, uint8_t>
950  findRepresentativeClass(MVT VT) const;
951
952  /// Once all of the register classes are added, this allows us to compute
953  /// derived properties we expose.
954  void computeRegisterProperties();
955
956  /// Indicate that the specified operation does not work with the specified
957  /// type and indicate what to do about it.
958  void setOperationAction(unsigned Op, MVT VT,
959                          LegalizeAction Action) {
960    assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
961    OpActions[(unsigned)VT.SimpleTy][Op] = (uint8_t)Action;
962  }
963
964  /// Indicate that the specified load with extension does not work with the
965  /// specified type and indicate what to do about it.
966  void setLoadExtAction(unsigned ExtType, MVT VT,
967                        LegalizeAction Action) {
968    assert(ExtType < ISD::LAST_LOADEXT_TYPE && VT < MVT::LAST_VALUETYPE &&
969           "Table isn't big enough!");
970    LoadExtActions[VT.SimpleTy][ExtType] = (uint8_t)Action;
971  }
972
973  /// Indicate that the specified truncating store does not work with the
974  /// specified type and indicate what to do about it.
975  void setTruncStoreAction(MVT ValVT, MVT MemVT,
976                           LegalizeAction Action) {
977    assert(ValVT < MVT::LAST_VALUETYPE && MemVT < MVT::LAST_VALUETYPE &&
978           "Table isn't big enough!");
979    TruncStoreActions[ValVT.SimpleTy][MemVT.SimpleTy] = (uint8_t)Action;
980  }
981
982  /// Indicate that the specified indexed load does or does not work with the
983  /// specified type and indicate what to do abort it.
984  ///
985  /// NOTE: All indexed mode loads are initialized to Expand in
986  /// TargetLowering.cpp
987  void setIndexedLoadAction(unsigned IdxMode, MVT VT,
988                            LegalizeAction Action) {
989    assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
990           (unsigned)Action < 0xf && "Table isn't big enough!");
991    // Load action are kept in the upper half.
992    IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0xf0;
993    IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action) <<4;
994  }
995
996  /// Indicate that the specified indexed store does or does not work with the
997  /// specified type and indicate what to do about it.
998  ///
999  /// NOTE: All indexed mode stores are initialized to Expand in
1000  /// TargetLowering.cpp
1001  void setIndexedStoreAction(unsigned IdxMode, MVT VT,
1002                             LegalizeAction Action) {
1003    assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
1004           (unsigned)Action < 0xf && "Table isn't big enough!");
1005    // Store action are kept in the lower half.
1006    IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0x0f;
1007    IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action);
1008  }
1009
1010  /// Indicate that the specified condition code is or isn't supported on the
1011  /// target and indicate what to do about it.
1012  void setCondCodeAction(ISD::CondCode CC, MVT VT,
1013                         LegalizeAction Action) {
1014    assert(VT < MVT::LAST_VALUETYPE &&
1015           (unsigned)CC < array_lengthof(CondCodeActions) &&
1016           "Table isn't big enough!");
1017    /// The lower 5 bits of the SimpleTy index into Nth 2bit set from the 64bit
1018    /// value and the upper 27 bits index into the second dimension of the
1019    /// array to select what 64bit value to use.
1020    CondCodeActions[(unsigned)CC][VT.SimpleTy >> 5]
1021      &= ~(uint64_t(3UL)  << (VT.SimpleTy & 0x1F)*2);
1022    CondCodeActions[(unsigned)CC][VT.SimpleTy >> 5]
1023      |= (uint64_t)Action << (VT.SimpleTy & 0x1F)*2;
1024  }
1025
1026  /// If Opc/OrigVT is specified as being promoted, the promotion code defaults
1027  /// to trying a larger integer/fp until it can find one that works. If that
1028  /// default is insufficient, this method can be used by the target to override
1029  /// the default.
1030  void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1031    PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
1032  }
1033
1034  /// Targets should invoke this method for each target independent node that
1035  /// they want to provide a custom DAG combiner for by implementing the
1036  /// PerformDAGCombine virtual method.
1037  void setTargetDAGCombine(ISD::NodeType NT) {
1038    assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1039    TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
1040  }
1041
1042  /// Set the target's required jmp_buf buffer size (in bytes); default is 200
1043  void setJumpBufSize(unsigned Size) {
1044    JumpBufSize = Size;
1045  }
1046
1047  /// Set the target's required jmp_buf buffer alignment (in bytes); default is
1048  /// 0
1049  void setJumpBufAlignment(unsigned Align) {
1050    JumpBufAlignment = Align;
1051  }
1052
1053  /// Set the target's minimum function alignment (in log2(bytes))
1054  void setMinFunctionAlignment(unsigned Align) {
1055    MinFunctionAlignment = Align;
1056  }
1057
1058  /// Set the target's preferred function alignment.  This should be set if
1059  /// there is a performance benefit to higher-than-minimum alignment (in
1060  /// log2(bytes))
1061  void setPrefFunctionAlignment(unsigned Align) {
1062    PrefFunctionAlignment = Align;
1063  }
1064
1065  /// Set the target's preferred loop alignment. Default alignment is zero, it
1066  /// means the target does not care about loop alignment.  The alignment is
1067  /// specified in log2(bytes).
1068  void setPrefLoopAlignment(unsigned Align) {
1069    PrefLoopAlignment = Align;
1070  }
1071
1072  /// Set the minimum stack alignment of an argument (in log2(bytes)).
1073  void setMinStackArgumentAlignment(unsigned Align) {
1074    MinStackArgumentAlignment = Align;
1075  }
1076
1077  /// Set if the DAG builder should automatically insert fences and reduce the
1078  /// order of atomic memory operations to Monotonic.
1079  void setInsertFencesForAtomic(bool fence) {
1080    InsertFencesForAtomic = fence;
1081  }
1082
1083public:
1084  //===--------------------------------------------------------------------===//
1085  // Addressing mode description hooks (used by LSR etc).
1086  //
1087
1088  /// CodeGenPrepare sinks address calculations into the same BB as Load/Store
1089  /// instructions reading the address. This allows as much computation as
1090  /// possible to be done in the address mode for that operand. This hook lets
1091  /// targets also pass back when this should be done on intrinsics which
1092  /// load/store.
1093  virtual bool GetAddrModeArguments(IntrinsicInst * /*I*/,
1094                                    SmallVectorImpl<Value*> &/*Ops*/,
1095                                    Type *&/*AccessTy*/) const {
1096    return false;
1097  }
1098
1099  /// This represents an addressing mode of:
1100  ///    BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
1101  /// If BaseGV is null,  there is no BaseGV.
1102  /// If BaseOffs is zero, there is no base offset.
1103  /// If HasBaseReg is false, there is no base register.
1104  /// If Scale is zero, there is no ScaleReg.  Scale of 1 indicates a reg with
1105  /// no scale.
1106  struct AddrMode {
1107    GlobalValue *BaseGV;
1108    int64_t      BaseOffs;
1109    bool         HasBaseReg;
1110    int64_t      Scale;
1111    AddrMode() : BaseGV(0), BaseOffs(0), HasBaseReg(false), Scale(0) {}
1112  };
1113
1114  /// Return true if the addressing mode represented by AM is legal for this
1115  /// target, for a load/store of the specified type.
1116  ///
1117  /// The type may be VoidTy, in which case only return true if the addressing
1118  /// mode is legal for a load/store of any legal type.  TODO: Handle
1119  /// pre/postinc as well.
1120  virtual bool isLegalAddressingMode(const AddrMode &AM, Type *Ty) const;
1121
1122  /// \brief Return the cost of the scaling factor used in the addressing mode
1123  /// represented by AM for this target, for a load/store of the specified type.
1124  ///
1125  /// If the AM is supported, the return value must be >= 0.
1126  /// If the AM is not supported, it returns a negative value.
1127  /// TODO: Handle pre/postinc as well.
1128  virtual int getScalingFactorCost(const AddrMode &AM, Type *Ty) const {
1129    // Default: assume that any scaling factor used in a legal AM is free.
1130    if (isLegalAddressingMode(AM, Ty)) return 0;
1131    return -1;
1132  }
1133
1134  /// Return true if the specified immediate is legal icmp immediate, that is
1135  /// the target has icmp instructions which can compare a register against the
1136  /// immediate without having to materialize the immediate into a register.
1137  virtual bool isLegalICmpImmediate(int64_t) const {
1138    return true;
1139  }
1140
1141  /// Return true if the specified immediate is legal add immediate, that is the
1142  /// target has add instructions which can add a register with the immediate
1143  /// without having to materialize the immediate into a register.
1144  virtual bool isLegalAddImmediate(int64_t) const {
1145    return true;
1146  }
1147
1148  /// Return true if it's free to truncate a value of type Ty1 to type
1149  /// Ty2. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
1150  /// by referencing its sub-register AX.
1151  virtual bool isTruncateFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1152    return false;
1153  }
1154
1155  virtual bool isTruncateFree(EVT /*VT1*/, EVT /*VT2*/) const {
1156    return false;
1157  }
1158
1159  /// Return true if any actual instruction that defines a value of type Ty1
1160  /// implicitly zero-extends the value to Ty2 in the result register.
1161  ///
1162  /// This does not necessarily include registers defined in unknown ways, such
1163  /// as incoming arguments, or copies from unknown virtual registers. Also, if
1164  /// isTruncateFree(Ty2, Ty1) is true, this does not necessarily apply to
1165  /// truncate instructions. e.g. on x86-64, all instructions that define 32-bit
1166  /// values implicit zero-extend the result out to 64 bits.
1167  virtual bool isZExtFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1168    return false;
1169  }
1170
1171  virtual bool isZExtFree(EVT /*VT1*/, EVT /*VT2*/) const {
1172    return false;
1173  }
1174
1175  /// Return true if zero-extending the specific node Val to type VT2 is free
1176  /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
1177  /// because it's folded such as X86 zero-extending loads).
1178  virtual bool isZExtFree(SDValue Val, EVT VT2) const {
1179    return isZExtFree(Val.getValueType(), VT2);
1180  }
1181
1182  /// Return true if an fneg operation is free to the point where it is never
1183  /// worthwhile to replace it with a bitwise operation.
1184  virtual bool isFNegFree(EVT VT) const {
1185    assert(VT.isFloatingPoint());
1186    return false;
1187  }
1188
1189  /// Return true if an fabs operation is free to the point where it is never
1190  /// worthwhile to replace it with a bitwise operation.
1191  virtual bool isFAbsFree(EVT VT) const {
1192    assert(VT.isFloatingPoint());
1193    return false;
1194  }
1195
1196  /// Return true if an FMA operation is faster than a pair of fmul and fadd
1197  /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
1198  /// returns true, otherwise fmuladd is expanded to fmul + fadd.
1199  ///
1200  /// NOTE: This may be called before legalization on types for which FMAs are
1201  /// not legal, but should return true if those types will eventually legalize
1202  /// to types that support FMAs. After legalization, it will only be called on
1203  /// types that support FMAs (via Legal or Custom actions)
1204  virtual bool isFMAFasterThanFMulAndFAdd(EVT) const {
1205    return false;
1206  }
1207
1208  /// Return true if it's profitable to narrow operations of type VT1 to
1209  /// VT2. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
1210  /// i32 to i16.
1211  virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
1212    return false;
1213  }
1214
1215  //===--------------------------------------------------------------------===//
1216  // Runtime Library hooks
1217  //
1218
1219  /// Rename the default libcall routine name for the specified libcall.
1220  void setLibcallName(RTLIB::Libcall Call, const char *Name) {
1221    LibcallRoutineNames[Call] = Name;
1222  }
1223
1224  /// Get the libcall routine name for the specified libcall.
1225  const char *getLibcallName(RTLIB::Libcall Call) const {
1226    return LibcallRoutineNames[Call];
1227  }
1228
1229  /// Override the default CondCode to be used to test the result of the
1230  /// comparison libcall against zero.
1231  void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
1232    CmpLibcallCCs[Call] = CC;
1233  }
1234
1235  /// Get the CondCode that's to be used to test the result of the comparison
1236  /// libcall against zero.
1237  ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
1238    return CmpLibcallCCs[Call];
1239  }
1240
1241  /// Set the CallingConv that should be used for the specified libcall.
1242  void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
1243    LibcallCallingConvs[Call] = CC;
1244  }
1245
1246  /// Get the CallingConv that should be used for the specified libcall.
1247  CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
1248    return LibcallCallingConvs[Call];
1249  }
1250
1251private:
1252  const TargetMachine &TM;
1253  const DataLayout *TD;
1254  const TargetLoweringObjectFile &TLOF;
1255
1256  /// The type to use for pointers for the default address space, usually i32 or
1257  /// i64.
1258  MVT PointerTy;
1259
1260  /// True if this is a little endian target.
1261  bool IsLittleEndian;
1262
1263  /// Tells the code generator not to expand operations into sequences that use
1264  /// the select operations if possible.
1265  bool SelectIsExpensive;
1266
1267  /// Tells the code generator not to expand integer divides by constants into a
1268  /// sequence of muls, adds, and shifts.  This is a hack until a real cost
1269  /// model is in place.  If we ever optimize for size, this will be set to true
1270  /// unconditionally.
1271  bool IntDivIsCheap;
1272
1273  /// Tells the code generator to bypass slow divide or remainder
1274  /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
1275  /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
1276  /// div/rem when the operands are positive and less than 256.
1277  DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
1278
1279  /// Tells the code generator that it shouldn't generate srl/add/sra for a
1280  /// signed divide by power of two, and let the target handle it.
1281  bool Pow2DivIsCheap;
1282
1283  /// Tells the code generator that it shouldn't generate extra flow control
1284  /// instructions and should attempt to combine flow control instructions via
1285  /// predication.
1286  bool JumpIsExpensive;
1287
1288  /// This target prefers to use _setjmp to implement llvm.setjmp.
1289  ///
1290  /// Defaults to false.
1291  bool UseUnderscoreSetJmp;
1292
1293  /// This target prefers to use _longjmp to implement llvm.longjmp.
1294  ///
1295  /// Defaults to false.
1296  bool UseUnderscoreLongJmp;
1297
1298  /// Whether the target can generate code for jumptables.  If it's not true,
1299  /// then each jumptable must be lowered into if-then-else's.
1300  bool SupportJumpTables;
1301
1302  /// Number of blocks threshold to use jump tables.
1303  int MinimumJumpTableEntries;
1304
1305  /// Information about the contents of the high-bits in boolean values held in
1306  /// a type wider than i1. See getBooleanContents.
1307  BooleanContent BooleanContents;
1308
1309  /// Information about the contents of the high-bits in boolean vector values
1310  /// when the element type is wider than i1. See getBooleanContents.
1311  BooleanContent BooleanVectorContents;
1312
1313  /// The target scheduling preference: shortest possible total cycles or lowest
1314  /// register usage.
1315  Sched::Preference SchedPreferenceInfo;
1316
1317  /// The size, in bytes, of the target's jmp_buf buffers
1318  unsigned JumpBufSize;
1319
1320  /// The alignment, in bytes, of the target's jmp_buf buffers
1321  unsigned JumpBufAlignment;
1322
1323  /// The minimum alignment that any argument on the stack needs to have.
1324  unsigned MinStackArgumentAlignment;
1325
1326  /// The minimum function alignment (used when optimizing for size, and to
1327  /// prevent explicitly provided alignment from leading to incorrect code).
1328  unsigned MinFunctionAlignment;
1329
1330  /// The preferred function alignment (used when alignment unspecified and
1331  /// optimizing for speed).
1332  unsigned PrefFunctionAlignment;
1333
1334  /// The preferred loop alignment.
1335  unsigned PrefLoopAlignment;
1336
1337  /// Whether the DAG builder should automatically insert fences and reduce
1338  /// ordering for atomics.  (This will be set for for most architectures with
1339  /// weak memory ordering.)
1340  bool InsertFencesForAtomic;
1341
1342  /// If set to a physical register, this specifies the register that
1343  /// llvm.savestack/llvm.restorestack should save and restore.
1344  unsigned StackPointerRegisterToSaveRestore;
1345
1346  /// If set to a physical register, this specifies the register that receives
1347  /// the exception address on entry to a landing pad.
1348  unsigned ExceptionPointerRegister;
1349
1350  /// If set to a physical register, this specifies the register that receives
1351  /// the exception typeid on entry to a landing pad.
1352  unsigned ExceptionSelectorRegister;
1353
1354  /// This indicates the default register class to use for each ValueType the
1355  /// target supports natively.
1356  const TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
1357  unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
1358  MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
1359
1360  /// This indicates the "representative" register class to use for each
1361  /// ValueType the target supports natively. This information is used by the
1362  /// scheduler to track register pressure. By default, the representative
1363  /// register class is the largest legal super-reg register class of the
1364  /// register class of the specified type. e.g. On x86, i8, i16, and i32's
1365  /// representative class would be GR32.
1366  const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
1367
1368  /// This indicates the "cost" of the "representative" register class for each
1369  /// ValueType. The cost is used by the scheduler to approximate register
1370  /// pressure.
1371  uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
1372
1373  /// For any value types we are promoting or expanding, this contains the value
1374  /// type that we are changing to.  For Expanded types, this contains one step
1375  /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
1376  /// (e.g. i64 -> i16).  For types natively supported by the system, this holds
1377  /// the same type (e.g. i32 -> i32).
1378  MVT TransformToType[MVT::LAST_VALUETYPE];
1379
1380  /// For each operation and each value type, keep a LegalizeAction that
1381  /// indicates how instruction selection should deal with the operation.  Most
1382  /// operations are Legal (aka, supported natively by the target), but
1383  /// operations that are not should be described.  Note that operations on
1384  /// non-legal value types are not described here.
1385  uint8_t OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END];
1386
1387  /// For each load extension type and each value type, keep a LegalizeAction
1388  /// that indicates how instruction selection should deal with a load of a
1389  /// specific value type and extension type.
1390  uint8_t LoadExtActions[MVT::LAST_VALUETYPE][ISD::LAST_LOADEXT_TYPE];
1391
1392  /// For each value type pair keep a LegalizeAction that indicates whether a
1393  /// truncating store of a specific value type and truncating type is legal.
1394  uint8_t TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
1395
1396  /// For each indexed mode and each value type, keep a pair of LegalizeAction
1397  /// that indicates how instruction selection should deal with the load /
1398  /// store.
1399  ///
1400  /// The first dimension is the value_type for the reference. The second
1401  /// dimension represents the various modes for load store.
1402  uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
1403
1404  /// For each condition code (ISD::CondCode) keep a LegalizeAction that
1405  /// indicates how instruction selection should deal with the condition code.
1406  ///
1407  /// Because each CC action takes up 2 bits, we need to have the array size be
1408  /// large enough to fit all of the value types. This can be done by dividing
1409  /// the MVT::LAST_VALUETYPE by 32 and adding one.
1410  uint64_t CondCodeActions[ISD::SETCC_INVALID][(MVT::LAST_VALUETYPE / 32) + 1];
1411
1412  ValueTypeActionImpl ValueTypeActions;
1413
1414public:
1415  LegalizeKind
1416  getTypeConversion(LLVMContext &Context, EVT VT) const {
1417    // If this is a simple type, use the ComputeRegisterProp mechanism.
1418    if (VT.isSimple()) {
1419      MVT SVT = VT.getSimpleVT();
1420      assert((unsigned)SVT.SimpleTy < array_lengthof(TransformToType));
1421      MVT NVT = TransformToType[SVT.SimpleTy];
1422      LegalizeTypeAction LA = ValueTypeActions.getTypeAction(SVT);
1423
1424      assert(
1425        (LA == TypeLegal ||
1426         ValueTypeActions.getTypeAction(NVT) != TypePromoteInteger)
1427         && "Promote may not follow Expand or Promote");
1428
1429      if (LA == TypeSplitVector)
1430        return LegalizeKind(LA, EVT::getVectorVT(Context,
1431                                                 SVT.getVectorElementType(),
1432                                                 SVT.getVectorNumElements()/2));
1433      if (LA == TypeScalarizeVector)
1434        return LegalizeKind(LA, SVT.getVectorElementType());
1435      return LegalizeKind(LA, NVT);
1436    }
1437
1438    // Handle Extended Scalar Types.
1439    if (!VT.isVector()) {
1440      assert(VT.isInteger() && "Float types must be simple");
1441      unsigned BitSize = VT.getSizeInBits();
1442      // First promote to a power-of-two size, then expand if necessary.
1443      if (BitSize < 8 || !isPowerOf2_32(BitSize)) {
1444        EVT NVT = VT.getRoundIntegerType(Context);
1445        assert(NVT != VT && "Unable to round integer VT");
1446        LegalizeKind NextStep = getTypeConversion(Context, NVT);
1447        // Avoid multi-step promotion.
1448        if (NextStep.first == TypePromoteInteger) return NextStep;
1449        // Return rounded integer type.
1450        return LegalizeKind(TypePromoteInteger, NVT);
1451      }
1452
1453      return LegalizeKind(TypeExpandInteger,
1454                          EVT::getIntegerVT(Context, VT.getSizeInBits()/2));
1455    }
1456
1457    // Handle vector types.
1458    unsigned NumElts = VT.getVectorNumElements();
1459    EVT EltVT = VT.getVectorElementType();
1460
1461    // Vectors with only one element are always scalarized.
1462    if (NumElts == 1)
1463      return LegalizeKind(TypeScalarizeVector, EltVT);
1464
1465    // Try to widen vector elements until a legal type is found.
1466    if (EltVT.isInteger()) {
1467      // Vectors with a number of elements that is not a power of two are always
1468      // widened, for example <3 x float> -> <4 x float>.
1469      if (!VT.isPow2VectorType()) {
1470        NumElts = (unsigned)NextPowerOf2(NumElts);
1471        EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts);
1472        return LegalizeKind(TypeWidenVector, NVT);
1473      }
1474
1475      // Examine the element type.
1476      LegalizeKind LK = getTypeConversion(Context, EltVT);
1477
1478      // If type is to be expanded, split the vector.
1479      //  <4 x i140> -> <2 x i140>
1480      if (LK.first == TypeExpandInteger)
1481        return LegalizeKind(TypeSplitVector,
1482                            EVT::getVectorVT(Context, EltVT, NumElts / 2));
1483
1484      // Promote the integer element types until a legal vector type is found
1485      // or until the element integer type is too big. If a legal type was not
1486      // found, fallback to the usual mechanism of widening/splitting the
1487      // vector.
1488      EVT OldEltVT = EltVT;
1489      while (1) {
1490        // Increase the bitwidth of the element to the next pow-of-two
1491        // (which is greater than 8 bits).
1492        EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits()
1493                                 ).getRoundIntegerType(Context);
1494
1495        // Stop trying when getting a non-simple element type.
1496        // Note that vector elements may be greater than legal vector element
1497        // types. Example: X86 XMM registers hold 64bit element on 32bit systems.
1498        if (!EltVT.isSimple()) break;
1499
1500        // Build a new vector type and check if it is legal.
1501        MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1502        // Found a legal promoted vector type.
1503        if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal)
1504          return LegalizeKind(TypePromoteInteger,
1505                              EVT::getVectorVT(Context, EltVT, NumElts));
1506      }
1507
1508      // Reset the type to the unexpanded type if we did not find a legal vector
1509      // type with a promoted vector element type.
1510      EltVT = OldEltVT;
1511    }
1512
1513    // Try to widen the vector until a legal type is found.
1514    // If there is no wider legal type, split the vector.
1515    while (1) {
1516      // Round up to the next power of 2.
1517      NumElts = (unsigned)NextPowerOf2(NumElts);
1518
1519      // If there is no simple vector type with this many elements then there
1520      // cannot be a larger legal vector type.  Note that this assumes that
1521      // there are no skipped intermediate vector types in the simple types.
1522      if (!EltVT.isSimple()) break;
1523      MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1524      if (LargerVector == MVT()) break;
1525
1526      // If this type is legal then widen the vector.
1527      if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal)
1528        return LegalizeKind(TypeWidenVector, LargerVector);
1529    }
1530
1531    // Widen odd vectors to next power of two.
1532    if (!VT.isPow2VectorType()) {
1533      EVT NVT = VT.getPow2VectorType(Context);
1534      return LegalizeKind(TypeWidenVector, NVT);
1535    }
1536
1537    // Vectors with illegal element types are expanded.
1538    EVT NVT = EVT::getVectorVT(Context, EltVT, VT.getVectorNumElements() / 2);
1539    return LegalizeKind(TypeSplitVector, NVT);
1540  }
1541
1542private:
1543  std::vector<std::pair<MVT, const TargetRegisterClass*> > AvailableRegClasses;
1544
1545  /// Targets can specify ISD nodes that they would like PerformDAGCombine
1546  /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
1547  /// array.
1548  unsigned char
1549  TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
1550
1551  /// For operations that must be promoted to a specific type, this holds the
1552  /// destination type.  This map should be sparse, so don't hold it as an
1553  /// array.
1554  ///
1555  /// Targets add entries to this map with AddPromotedToType(..), clients access
1556  /// this with getTypeToPromoteTo(..).
1557  std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
1558    PromoteToType;
1559
1560  /// Stores the name each libcall.
1561  const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
1562
1563  /// The ISD::CondCode that should be used to test the result of each of the
1564  /// comparison libcall against zero.
1565  ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
1566
1567  /// Stores the CallingConv that should be used for each libcall.
1568  CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
1569
1570protected:
1571  /// \brief Specify maximum number of store instructions per memset call.
1572  ///
1573  /// When lowering \@llvm.memset this field specifies the maximum number of
1574  /// store operations that may be substituted for the call to memset. Targets
1575  /// must set this value based on the cost threshold for that target. Targets
1576  /// should assume that the memset will be done using as many of the largest
1577  /// store operations first, followed by smaller ones, if necessary, per
1578  /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
1579  /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
1580  /// store.  This only applies to setting a constant array of a constant size.
1581  unsigned MaxStoresPerMemset;
1582
1583  /// Maximum number of stores operations that may be substituted for the call
1584  /// to memset, used for functions with OptSize attribute.
1585  unsigned MaxStoresPerMemsetOptSize;
1586
1587  /// \brief Specify maximum bytes of store instructions per memcpy call.
1588  ///
1589  /// When lowering \@llvm.memcpy this field specifies the maximum number of
1590  /// store operations that may be substituted for a call to memcpy. Targets
1591  /// must set this value based on the cost threshold for that target. Targets
1592  /// should assume that the memcpy will be done using as many of the largest
1593  /// store operations first, followed by smaller ones, if necessary, per
1594  /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
1595  /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
1596  /// and one 1-byte store. This only applies to copying a constant array of
1597  /// constant size.
1598  unsigned MaxStoresPerMemcpy;
1599
1600  /// Maximum number of store operations that may be substituted for a call to
1601  /// memcpy, used for functions with OptSize attribute.
1602  unsigned MaxStoresPerMemcpyOptSize;
1603
1604  /// \brief Specify maximum bytes of store instructions per memmove call.
1605  ///
1606  /// When lowering \@llvm.memmove this field specifies the maximum number of
1607  /// store instructions that may be substituted for a call to memmove. Targets
1608  /// must set this value based on the cost threshold for that target. Targets
1609  /// should assume that the memmove will be done using as many of the largest
1610  /// store operations first, followed by smaller ones, if necessary, per
1611  /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
1612  /// with 8-bit alignment would result in nine 1-byte stores.  This only
1613  /// applies to copying a constant array of constant size.
1614  unsigned MaxStoresPerMemmove;
1615
1616  /// Maximum number of store instructions that may be substituted for a call to
1617  /// memmove, used for functions with OpSize attribute.
1618  unsigned MaxStoresPerMemmoveOptSize;
1619
1620  /// Tells the code generator that select is more expensive than a branch if
1621  /// the branch is usually predicted right.
1622  bool PredictableSelectIsExpensive;
1623
1624protected:
1625  /// Return true if the value types that can be represented by the specified
1626  /// register class are all legal.
1627  bool isLegalRC(const TargetRegisterClass *RC) const;
1628};
1629
1630/// This class defines information used to lower LLVM code to legal SelectionDAG
1631/// operators that the target instruction selector can accept natively.
1632///
1633/// This class also defines callbacks that targets must implement to lower
1634/// target-specific constructs to SelectionDAG operators.
1635class TargetLowering : public TargetLoweringBase {
1636  TargetLowering(const TargetLowering&) LLVM_DELETED_FUNCTION;
1637  void operator=(const TargetLowering&) LLVM_DELETED_FUNCTION;
1638
1639public:
1640  /// NOTE: The constructor takes ownership of TLOF.
1641  explicit TargetLowering(const TargetMachine &TM,
1642                          const TargetLoweringObjectFile *TLOF);
1643
1644  /// Returns true by value, base pointer and offset pointer and addressing mode
1645  /// by reference if the node's address can be legally represented as
1646  /// pre-indexed load / store address.
1647  virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
1648                                         SDValue &/*Offset*/,
1649                                         ISD::MemIndexedMode &/*AM*/,
1650                                         SelectionDAG &/*DAG*/) const {
1651    return false;
1652  }
1653
1654  /// Returns true by value, base pointer and offset pointer and addressing mode
1655  /// by reference if this node can be combined with a load / store to form a
1656  /// post-indexed load / store.
1657  virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
1658                                          SDValue &/*Base*/, SDValue &/*Offset*/,
1659                                          ISD::MemIndexedMode &/*AM*/,
1660                                          SelectionDAG &/*DAG*/) const {
1661    return false;
1662  }
1663
1664  /// Return the entry encoding for a jump table in the current function.  The
1665  /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
1666  virtual unsigned getJumpTableEncoding() const;
1667
1668  virtual const MCExpr *
1669  LowerCustomJumpTableEntry(const MachineJumpTableInfo * /*MJTI*/,
1670                            const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
1671                            MCContext &/*Ctx*/) const {
1672    llvm_unreachable("Need to implement this hook if target has custom JTIs");
1673  }
1674
1675  /// Returns relocation base for the given PIC jumptable.
1676  virtual SDValue getPICJumpTableRelocBase(SDValue Table,
1677                                           SelectionDAG &DAG) const;
1678
1679  /// This returns the relocation base for the given PIC jumptable, the same as
1680  /// getPICJumpTableRelocBase, but as an MCExpr.
1681  virtual const MCExpr *
1682  getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
1683                               unsigned JTI, MCContext &Ctx) const;
1684
1685  /// Return true if folding a constant offset with the given GlobalAddress is
1686  /// legal.  It is frequently not legal in PIC relocation models.
1687  virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
1688
1689  bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
1690                            SDValue &Chain) const;
1691
1692  void softenSetCCOperands(SelectionDAG &DAG, EVT VT,
1693                           SDValue &NewLHS, SDValue &NewRHS,
1694                           ISD::CondCode &CCCode, SDLoc DL) const;
1695
1696  SDValue makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT,
1697                      const SDValue *Ops, unsigned NumOps,
1698                      bool isSigned, SDLoc dl) const;
1699
1700  //===--------------------------------------------------------------------===//
1701  // TargetLowering Optimization Methods
1702  //
1703
1704  /// A convenience struct that encapsulates a DAG, and two SDValues for
1705  /// returning information from TargetLowering to its clients that want to
1706  /// combine.
1707  struct TargetLoweringOpt {
1708    SelectionDAG &DAG;
1709    bool LegalTys;
1710    bool LegalOps;
1711    SDValue Old;
1712    SDValue New;
1713
1714    explicit TargetLoweringOpt(SelectionDAG &InDAG,
1715                               bool LT, bool LO) :
1716      DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
1717
1718    bool LegalTypes() const { return LegalTys; }
1719    bool LegalOperations() const { return LegalOps; }
1720
1721    bool CombineTo(SDValue O, SDValue N) {
1722      Old = O;
1723      New = N;
1724      return true;
1725    }
1726
1727    /// Check to see if the specified operand of the specified instruction is a
1728    /// constant integer.  If so, check to see if there are any bits set in the
1729    /// constant that are not demanded.  If so, shrink the constant and return
1730    /// true.
1731    bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded);
1732
1733    /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.  This
1734    /// uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
1735    /// generalized for targets with other types of implicit widening casts.
1736    bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
1737                          SDLoc dl);
1738  };
1739
1740  /// Look at Op.  At this point, we know that only the DemandedMask bits of the
1741  /// result of Op are ever used downstream.  If we can use this information to
1742  /// simplify Op, create a new simplified DAG node and return true, returning
1743  /// the original and new nodes in Old and New.  Otherwise, analyze the
1744  /// expression and return a mask of KnownOne and KnownZero bits for the
1745  /// expression (used to simplify the caller).  The KnownZero/One bits may only
1746  /// be accurate for those bits in the DemandedMask.
1747  bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
1748                            APInt &KnownZero, APInt &KnownOne,
1749                            TargetLoweringOpt &TLO, unsigned Depth = 0) const;
1750
1751  /// Determine which of the bits specified in Mask are known to be either zero
1752  /// or one and return them in the KnownZero/KnownOne bitsets.
1753  virtual void computeMaskedBitsForTargetNode(const SDValue Op,
1754                                              APInt &KnownZero,
1755                                              APInt &KnownOne,
1756                                              const SelectionDAG &DAG,
1757                                              unsigned Depth = 0) const;
1758
1759  /// This method can be implemented by targets that want to expose additional
1760  /// information about sign bits to the DAG Combiner.
1761  virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
1762                                                   unsigned Depth = 0) const;
1763
1764  struct DAGCombinerInfo {
1765    void *DC;  // The DAG Combiner object.
1766    CombineLevel Level;
1767    bool CalledByLegalizer;
1768  public:
1769    SelectionDAG &DAG;
1770
1771    DAGCombinerInfo(SelectionDAG &dag, CombineLevel level,  bool cl, void *dc)
1772      : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
1773
1774    bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
1775    bool isBeforeLegalizeOps() const { return Level < AfterLegalizeVectorOps; }
1776    bool isAfterLegalizeVectorOps() const {
1777      return Level == AfterLegalizeDAG;
1778    }
1779    CombineLevel getDAGCombineLevel() { return Level; }
1780    bool isCalledByLegalizer() const { return CalledByLegalizer; }
1781
1782    void AddToWorklist(SDNode *N);
1783    void RemoveFromWorklist(SDNode *N);
1784    SDValue CombineTo(SDNode *N, const std::vector<SDValue> &To,
1785                      bool AddTo = true);
1786    SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
1787    SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
1788
1789    void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
1790  };
1791
1792  /// Try to simplify a setcc built with the specified operands and cc. If it is
1793  /// unable to simplify it, return a null SDValue.
1794  SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
1795                          ISD::CondCode Cond, bool foldBooleans,
1796                          DAGCombinerInfo &DCI, SDLoc dl) const;
1797
1798  /// Returns true (and the GlobalValue and the offset) if the node is a
1799  /// GlobalAddress + offset.
1800  virtual bool
1801  isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
1802
1803  /// This method will be invoked for all target nodes and for any
1804  /// target-independent nodes that the target has registered with invoke it
1805  /// for.
1806  ///
1807  /// The semantics are as follows:
1808  /// Return Value:
1809  ///   SDValue.Val == 0   - No change was made
1810  ///   SDValue.Val == N   - N was replaced, is dead, and is already handled.
1811  ///   otherwise          - N should be replaced by the returned Operand.
1812  ///
1813  /// In addition, methods provided by DAGCombinerInfo may be used to perform
1814  /// more complex transformations.
1815  ///
1816  virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
1817
1818  /// Return true if the target has native support for the specified value type
1819  /// and it is 'desirable' to use the type for the given node type. e.g. On x86
1820  /// i16 is legal, but undesirable since i16 instruction encodings are longer
1821  /// and some i16 instructions are slow.
1822  virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
1823    // By default, assume all legal types are desirable.
1824    return isTypeLegal(VT);
1825  }
1826
1827  /// Return true if it is profitable for dag combiner to transform a floating
1828  /// point op of specified opcode to a equivalent op of an integer
1829  /// type. e.g. f32 load -> i32 load can be profitable on ARM.
1830  virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
1831                                                 EVT /*VT*/) const {
1832    return false;
1833  }
1834
1835  /// This method query the target whether it is beneficial for dag combiner to
1836  /// promote the specified node. If true, it should return the desired
1837  /// promotion type by reference.
1838  virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
1839    return false;
1840  }
1841
1842  //===--------------------------------------------------------------------===//
1843  // Lowering methods - These methods must be implemented by targets so that
1844  // the SelectionDAGBuilder code knows how to lower these.
1845  //
1846
1847  /// This hook must be implemented to lower the incoming (formal) arguments,
1848  /// described by the Ins array, into the specified DAG. The implementation
1849  /// should fill in the InVals array with legal-type argument values, and
1850  /// return the resulting token chain value.
1851  ///
1852  virtual SDValue
1853    LowerFormalArguments(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
1854                         bool /*isVarArg*/,
1855                         const SmallVectorImpl<ISD::InputArg> &/*Ins*/,
1856                         SDLoc /*dl*/, SelectionDAG &/*DAG*/,
1857                         SmallVectorImpl<SDValue> &/*InVals*/) const {
1858    llvm_unreachable("Not Implemented");
1859  }
1860
1861  struct ArgListEntry {
1862    SDValue Node;
1863    Type* Ty;
1864    bool isSExt     : 1;
1865    bool isZExt     : 1;
1866    bool isInReg    : 1;
1867    bool isSRet     : 1;
1868    bool isNest     : 1;
1869    bool isByVal    : 1;
1870    bool isReturned : 1;
1871    uint16_t Alignment;
1872
1873    ArgListEntry() : isSExt(false), isZExt(false), isInReg(false),
1874      isSRet(false), isNest(false), isByVal(false), isReturned(false),
1875      Alignment(0) { }
1876  };
1877  typedef std::vector<ArgListEntry> ArgListTy;
1878
1879  /// This structure contains all information that is necessary for lowering
1880  /// calls. It is passed to TLI::LowerCallTo when the SelectionDAG builder
1881  /// needs to lower a call, and targets will see this struct in their LowerCall
1882  /// implementation.
1883  struct CallLoweringInfo {
1884    SDValue Chain;
1885    Type *RetTy;
1886    bool RetSExt           : 1;
1887    bool RetZExt           : 1;
1888    bool IsVarArg          : 1;
1889    bool IsInReg           : 1;
1890    bool DoesNotReturn     : 1;
1891    bool IsReturnValueUsed : 1;
1892
1893    // IsTailCall should be modified by implementations of
1894    // TargetLowering::LowerCall that perform tail call conversions.
1895    bool IsTailCall;
1896
1897    unsigned NumFixedArgs;
1898    CallingConv::ID CallConv;
1899    SDValue Callee;
1900    ArgListTy &Args;
1901    SelectionDAG &DAG;
1902    SDLoc DL;
1903    ImmutableCallSite *CS;
1904    SmallVector<ISD::OutputArg, 32> Outs;
1905    SmallVector<SDValue, 32> OutVals;
1906    SmallVector<ISD::InputArg, 32> Ins;
1907
1908
1909    /// Constructs a call lowering context based on the ImmutableCallSite \p cs.
1910    CallLoweringInfo(SDValue chain, Type *retTy,
1911                     FunctionType *FTy, bool isTailCall, SDValue callee,
1912                     ArgListTy &args, SelectionDAG &dag, SDLoc dl,
1913                     ImmutableCallSite &cs)
1914    : Chain(chain), RetTy(retTy), RetSExt(cs.paramHasAttr(0, Attribute::SExt)),
1915      RetZExt(cs.paramHasAttr(0, Attribute::ZExt)), IsVarArg(FTy->isVarArg()),
1916      IsInReg(cs.paramHasAttr(0, Attribute::InReg)),
1917      DoesNotReturn(cs.doesNotReturn()),
1918      IsReturnValueUsed(!cs.getInstruction()->use_empty()),
1919      IsTailCall(isTailCall), NumFixedArgs(FTy->getNumParams()),
1920      CallConv(cs.getCallingConv()), Callee(callee), Args(args), DAG(dag),
1921      DL(dl), CS(&cs) {}
1922
1923    /// Constructs a call lowering context based on the provided call
1924    /// information.
1925    CallLoweringInfo(SDValue chain, Type *retTy, bool retSExt, bool retZExt,
1926                     bool isVarArg, bool isInReg, unsigned numFixedArgs,
1927                     CallingConv::ID callConv, bool isTailCall,
1928                     bool doesNotReturn, bool isReturnValueUsed, SDValue callee,
1929                     ArgListTy &args, SelectionDAG &dag, SDLoc dl)
1930    : Chain(chain), RetTy(retTy), RetSExt(retSExt), RetZExt(retZExt),
1931      IsVarArg(isVarArg), IsInReg(isInReg), DoesNotReturn(doesNotReturn),
1932      IsReturnValueUsed(isReturnValueUsed), IsTailCall(isTailCall),
1933      NumFixedArgs(numFixedArgs), CallConv(callConv), Callee(callee),
1934      Args(args), DAG(dag), DL(dl), CS(NULL) {}
1935  };
1936
1937  /// This function lowers an abstract call to a function into an actual call.
1938  /// This returns a pair of operands.  The first element is the return value
1939  /// for the function (if RetTy is not VoidTy).  The second element is the
1940  /// outgoing token chain. It calls LowerCall to do the actual lowering.
1941  std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
1942
1943  /// This hook must be implemented to lower calls into the the specified
1944  /// DAG. The outgoing arguments to the call are described by the Outs array,
1945  /// and the values to be returned by the call are described by the Ins
1946  /// array. The implementation should fill in the InVals array with legal-type
1947  /// return values from the call, and return the resulting token chain value.
1948  virtual SDValue
1949    LowerCall(CallLoweringInfo &/*CLI*/,
1950              SmallVectorImpl<SDValue> &/*InVals*/) const {
1951    llvm_unreachable("Not Implemented");
1952  }
1953
1954  /// Target-specific cleanup for formal ByVal parameters.
1955  virtual void HandleByVal(CCState *, unsigned &, unsigned) const {}
1956
1957  /// This hook should be implemented to check whether the return values
1958  /// described by the Outs array can fit into the return registers.  If false
1959  /// is returned, an sret-demotion is performed.
1960  virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
1961                              MachineFunction &/*MF*/, bool /*isVarArg*/,
1962               const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
1963               LLVMContext &/*Context*/) const
1964  {
1965    // Return true by default to get preexisting behavior.
1966    return true;
1967  }
1968
1969  /// This hook must be implemented to lower outgoing return values, described
1970  /// by the Outs array, into the specified DAG. The implementation should
1971  /// return the resulting token chain value.
1972  virtual SDValue
1973    LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
1974                bool /*isVarArg*/,
1975                const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
1976                const SmallVectorImpl<SDValue> &/*OutVals*/,
1977                SDLoc /*dl*/, SelectionDAG &/*DAG*/) const {
1978    llvm_unreachable("Not Implemented");
1979  }
1980
1981  /// Return true if result of the specified node is used by a return node
1982  /// only. It also compute and return the input chain for the tail call.
1983  ///
1984  /// This is used to determine whether it is possible to codegen a libcall as
1985  /// tail call at legalization time.
1986  virtual bool isUsedByReturnOnly(SDNode *, SDValue &/*Chain*/) const {
1987    return false;
1988  }
1989
1990  /// Return true if the target may be able emit the call instruction as a tail
1991  /// call. This is used by optimization passes to determine if it's profitable
1992  /// to duplicate return instructions to enable tailcall optimization.
1993  virtual bool mayBeEmittedAsTailCall(CallInst *) const {
1994    return false;
1995  }
1996
1997  /// Return the type that should be used to zero or sign extend a
1998  /// zeroext/signext integer argument or return value.  FIXME: Most C calling
1999  /// convention requires the return type to be promoted, but this is not true
2000  /// all the time, e.g. i1 on x86-64. It is also not necessary for non-C
2001  /// calling conventions. The frontend should handle this and include all of
2002  /// the necessary information.
2003  virtual MVT getTypeForExtArgOrReturn(MVT VT,
2004                                       ISD::NodeType /*ExtendKind*/) const {
2005    MVT MinVT = getRegisterType(MVT::i32);
2006    return VT.bitsLT(MinVT) ? MinVT : VT;
2007  }
2008
2009  /// This callback is invoked by the type legalizer to legalize nodes with an
2010  /// illegal operand type but legal result types.  It replaces the
2011  /// LowerOperation callback in the type Legalizer.  The reason we can not do
2012  /// away with LowerOperation entirely is that LegalizeDAG isn't yet ready to
2013  /// use this callback.
2014  ///
2015  /// TODO: Consider merging with ReplaceNodeResults.
2016  ///
2017  /// The target places new result values for the node in Results (their number
2018  /// and types must exactly match those of the original return values of
2019  /// the node), or leaves Results empty, which indicates that the node is not
2020  /// to be custom lowered after all.
2021  /// The default implementation calls LowerOperation.
2022  virtual void LowerOperationWrapper(SDNode *N,
2023                                     SmallVectorImpl<SDValue> &Results,
2024                                     SelectionDAG &DAG) const;
2025
2026  /// This callback is invoked for operations that are unsupported by the
2027  /// target, which are registered to use 'custom' lowering, and whose defined
2028  /// values are all legal.  If the target has no operations that require custom
2029  /// lowering, it need not implement this.  The default implementation of this
2030  /// aborts.
2031  virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
2032
2033  /// This callback is invoked when a node result type is illegal for the
2034  /// target, and the operation was registered to use 'custom' lowering for that
2035  /// result type.  The target places new result values for the node in Results
2036  /// (their number and types must exactly match those of the original return
2037  /// values of the node), or leaves Results empty, which indicates that the
2038  /// node is not to be custom lowered after all.
2039  ///
2040  /// If the target has no operations that require custom lowering, it need not
2041  /// implement this.  The default implementation aborts.
2042  virtual void ReplaceNodeResults(SDNode * /*N*/,
2043                                  SmallVectorImpl<SDValue> &/*Results*/,
2044                                  SelectionDAG &/*DAG*/) const {
2045    llvm_unreachable("ReplaceNodeResults not implemented for this target!");
2046  }
2047
2048  /// This method returns the name of a target specific DAG node.
2049  virtual const char *getTargetNodeName(unsigned Opcode) const;
2050
2051  /// This method returns a target specific FastISel object, or null if the
2052  /// target does not support "fast" ISel.
2053  virtual FastISel *createFastISel(FunctionLoweringInfo &,
2054                                   const TargetLibraryInfo *) const {
2055    return 0;
2056  }
2057
2058  //===--------------------------------------------------------------------===//
2059  // Inline Asm Support hooks
2060  //
2061
2062  /// This hook allows the target to expand an inline asm call to be explicit
2063  /// llvm code if it wants to.  This is useful for turning simple inline asms
2064  /// into LLVM intrinsics, which gives the compiler more information about the
2065  /// behavior of the code.
2066  virtual bool ExpandInlineAsm(CallInst *) const {
2067    return false;
2068  }
2069
2070  enum ConstraintType {
2071    C_Register,            // Constraint represents specific register(s).
2072    C_RegisterClass,       // Constraint represents any of register(s) in class.
2073    C_Memory,              // Memory constraint.
2074    C_Other,               // Something else.
2075    C_Unknown              // Unsupported constraint.
2076  };
2077
2078  enum ConstraintWeight {
2079    // Generic weights.
2080    CW_Invalid  = -1,     // No match.
2081    CW_Okay     = 0,      // Acceptable.
2082    CW_Good     = 1,      // Good weight.
2083    CW_Better   = 2,      // Better weight.
2084    CW_Best     = 3,      // Best weight.
2085
2086    // Well-known weights.
2087    CW_SpecificReg  = CW_Okay,    // Specific register operands.
2088    CW_Register     = CW_Good,    // Register operands.
2089    CW_Memory       = CW_Better,  // Memory operands.
2090    CW_Constant     = CW_Best,    // Constant operand.
2091    CW_Default      = CW_Okay     // Default or don't know type.
2092  };
2093
2094  /// This contains information for each constraint that we are lowering.
2095  struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
2096    /// This contains the actual string for the code, like "m".  TargetLowering
2097    /// picks the 'best' code from ConstraintInfo::Codes that most closely
2098    /// matches the operand.
2099    std::string ConstraintCode;
2100
2101    /// Information about the constraint code, e.g. Register, RegisterClass,
2102    /// Memory, Other, Unknown.
2103    TargetLowering::ConstraintType ConstraintType;
2104
2105    /// If this is the result output operand or a clobber, this is null,
2106    /// otherwise it is the incoming operand to the CallInst.  This gets
2107    /// modified as the asm is processed.
2108    Value *CallOperandVal;
2109
2110    /// The ValueType for the operand value.
2111    MVT ConstraintVT;
2112
2113    /// Return true of this is an input operand that is a matching constraint
2114    /// like "4".
2115    bool isMatchingInputConstraint() const;
2116
2117    /// If this is an input matching constraint, this method returns the output
2118    /// operand it matches.
2119    unsigned getMatchedOperand() const;
2120
2121    /// Copy constructor for copying from an AsmOperandInfo.
2122    AsmOperandInfo(const AsmOperandInfo &info)
2123      : InlineAsm::ConstraintInfo(info),
2124        ConstraintCode(info.ConstraintCode),
2125        ConstraintType(info.ConstraintType),
2126        CallOperandVal(info.CallOperandVal),
2127        ConstraintVT(info.ConstraintVT) {
2128    }
2129
2130    /// Copy constructor for copying from a ConstraintInfo.
2131    AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
2132      : InlineAsm::ConstraintInfo(info),
2133        ConstraintType(TargetLowering::C_Unknown),
2134        CallOperandVal(0), ConstraintVT(MVT::Other) {
2135    }
2136  };
2137
2138  typedef std::vector<AsmOperandInfo> AsmOperandInfoVector;
2139
2140  /// Split up the constraint string from the inline assembly value into the
2141  /// specific constraints and their prefixes, and also tie in the associated
2142  /// operand values.  If this returns an empty vector, and if the constraint
2143  /// string itself isn't empty, there was an error parsing.
2144  virtual AsmOperandInfoVector ParseConstraints(ImmutableCallSite CS) const;
2145
2146  /// Examine constraint type and operand type and determine a weight value.
2147  /// The operand object must already have been set up with the operand type.
2148  virtual ConstraintWeight getMultipleConstraintMatchWeight(
2149      AsmOperandInfo &info, int maIndex) const;
2150
2151  /// Examine constraint string and operand type and determine a weight value.
2152  /// The operand object must already have been set up with the operand type.
2153  virtual ConstraintWeight getSingleConstraintMatchWeight(
2154      AsmOperandInfo &info, const char *constraint) const;
2155
2156  /// Determines the constraint code and constraint type to use for the specific
2157  /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
2158  /// If the actual operand being passed in is available, it can be passed in as
2159  /// Op, otherwise an empty SDValue can be passed.
2160  virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
2161                                      SDValue Op,
2162                                      SelectionDAG *DAG = 0) const;
2163
2164  /// Given a constraint, return the type of constraint it is for this target.
2165  virtual ConstraintType getConstraintType(const std::string &Constraint) const;
2166
2167  /// Given a physical register constraint (e.g.  {edx}), return the register
2168  /// number and the register class for the register.
2169  ///
2170  /// Given a register class constraint, like 'r', if this corresponds directly
2171  /// to an LLVM register class, return a register of 0 and the register class
2172  /// pointer.
2173  ///
2174  /// This should only be used for C_Register constraints.  On error, this
2175  /// returns a register number of 0 and a null register class pointer..
2176  virtual std::pair<unsigned, const TargetRegisterClass*>
2177    getRegForInlineAsmConstraint(const std::string &Constraint,
2178                                 MVT VT) const;
2179
2180  /// Try to replace an X constraint, which matches anything, with another that
2181  /// has more specific requirements based on the type of the corresponding
2182  /// operand.  This returns null if there is no replacement to make.
2183  virtual const char *LowerXConstraint(EVT ConstraintVT) const;
2184
2185  /// Lower the specified operand into the Ops vector.  If it is invalid, don't
2186  /// add anything to Ops.
2187  virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
2188                                            std::vector<SDValue> &Ops,
2189                                            SelectionDAG &DAG) const;
2190
2191  //===--------------------------------------------------------------------===//
2192  // Div utility functions
2193  //
2194  SDValue BuildExactSDIV(SDValue Op1, SDValue Op2, SDLoc dl,
2195                         SelectionDAG &DAG) const;
2196  SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
2197                      std::vector<SDNode*> *Created) const;
2198  SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
2199                      std::vector<SDNode*> *Created) const;
2200
2201  //===--------------------------------------------------------------------===//
2202  // Instruction Emitting Hooks
2203  //
2204
2205  // This method should be implemented by targets that mark instructions with
2206  // the 'usesCustomInserter' flag.  These instructions are special in various
2207  // ways, which require special support to insert.  The specified MachineInstr
2208  // is created but not inserted into any basic blocks, and this method is
2209  // called to expand it into a sequence of instructions, potentially also
2210  // creating new basic blocks and control flow.
2211  virtual MachineBasicBlock *
2212    EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const;
2213
2214  /// This method should be implemented by targets that mark instructions with
2215  /// the 'hasPostISelHook' flag. These instructions must be adjusted after
2216  /// instruction selection by target hooks.  e.g. To fill in optional defs for
2217  /// ARM 's' setting instructions.
2218  virtual void
2219  AdjustInstrPostInstrSelection(MachineInstr *MI, SDNode *Node) const;
2220};
2221
2222/// Given an LLVM IR type and return type attributes, compute the return value
2223/// EVTs and flags, and optionally also the offsets, if the return value is
2224/// being lowered to memory.
2225void GetReturnInfo(Type* ReturnType, AttributeSet attr,
2226                   SmallVectorImpl<ISD::OutputArg> &Outs,
2227                   const TargetLowering &TLI);
2228
2229} // end llvm namespace
2230
2231#endif
2232