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