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