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