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