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