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