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