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