Wrap MVT::ValueType in a struct to get type safety
[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/Constants.h"
26 #include "llvm/InlineAsm.h"
27 #include "llvm/CodeGen/SelectionDAGNodes.h"
28 #include "llvm/CodeGen/RuntimeLibcalls.h"
29 #include "llvm/ADT/APFloat.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include <map>
32 #include <vector>
33
34 namespace llvm {
35   class Function;
36   class MachineBasicBlock;
37   class MachineFrameInfo;
38   class MachineInstr;
39   class SDNode;
40   class SDOperand;
41   class SelectionDAG;
42   class TargetData;
43   class TargetMachine;
44   class TargetRegisterClass;
45   class TargetSubtarget;
46   class Value;
47   class VectorType;
48
49 //===----------------------------------------------------------------------===//
50 /// TargetLowering - This class defines information used to lower LLVM code to
51 /// legal SelectionDAG operators that the target instruction selector can accept
52 /// natively.
53 ///
54 /// This class also defines callbacks that targets must implement to lower
55 /// target-specific constructs to SelectionDAG operators.
56 ///
57 class TargetLowering {
58 public:
59   /// LegalizeAction - This enum indicates whether operations are valid for a
60   /// target, and if not, what action should be used to make them valid.
61   enum LegalizeAction {
62     Legal,      // The target natively supports this operation.
63     Promote,    // This operation should be executed in a larger type.
64     Expand,     // Try to expand this to other ops, otherwise use a libcall.
65     Custom      // Use the LowerOperation hook to implement custom lowering.
66   };
67
68   enum OutOfRangeShiftAmount {
69     Undefined,  // Oversized shift amounts are undefined (default).
70     Mask,       // Shift amounts are auto masked (anded) to value size.
71     Extend      // Oversized shift pulls in zeros or sign bits.
72   };
73
74   enum SetCCResultValue {
75     UndefinedSetCCResult,          // SetCC returns a garbage/unknown extend.
76     ZeroOrOneSetCCResult,          // SetCC returns a zero extended result.
77     ZeroOrNegativeOneSetCCResult   // SetCC returns a sign extended result.
78   };
79
80   enum SchedPreference {
81     SchedulingForLatency,          // Scheduling for shortest total latency.
82     SchedulingForRegPressure       // Scheduling for lowest register pressure.
83   };
84
85   explicit TargetLowering(TargetMachine &TM);
86   virtual ~TargetLowering();
87
88   TargetMachine &getTargetMachine() const { return TM; }
89   const TargetData *getTargetData() const { return TD; }
90
91   bool isBigEndian() const { return !IsLittleEndian; }
92   bool isLittleEndian() const { return IsLittleEndian; }
93   MVT getPointerTy() const { return PointerTy; }
94   MVT getShiftAmountTy() const { return ShiftAmountTy; }
95   OutOfRangeShiftAmount getShiftAmountFlavor() const {return ShiftAmtHandling; }
96
97   /// usesGlobalOffsetTable - Return true if this target uses a GOT for PIC
98   /// codegen.
99   bool usesGlobalOffsetTable() const { return UsesGlobalOffsetTable; }
100
101   /// isSelectExpensive - Return true if the select operation is expensive for
102   /// this target.
103   bool isSelectExpensive() const { return SelectIsExpensive; }
104   
105   /// isIntDivCheap() - Return true if integer divide is usually cheaper than
106   /// a sequence of several shifts, adds, and multiplies for this target.
107   bool isIntDivCheap() const { return IntDivIsCheap; }
108
109   /// isPow2DivCheap() - Return true if pow2 div is cheaper than a chain of
110   /// srl/add/sra.
111   bool isPow2DivCheap() const { return Pow2DivIsCheap; }
112
113   /// getSetCCResultType - Return the ValueType of the result of setcc
114   /// operations.
115   virtual MVT getSetCCResultType(const SDOperand &) const;
116
117   /// getSetCCResultContents - For targets without boolean registers, this flag
118   /// returns information about the contents of the high-bits in the setcc
119   /// result register.
120   SetCCResultValue getSetCCResultContents() const { return SetCCResultContents;}
121
122   /// getSchedulingPreference - Return target scheduling preference.
123   SchedPreference getSchedulingPreference() const {
124     return SchedPreferenceInfo;
125   }
126
127   /// getRegClassFor - Return the register class that should be used for the
128   /// specified value type.  This may only be called on legal types.
129   TargetRegisterClass *getRegClassFor(MVT VT) const {
130     assert((unsigned)VT.getSimpleVT() < array_lengthof(RegClassForVT));
131     TargetRegisterClass *RC = RegClassForVT[VT.getSimpleVT()];
132     assert(RC && "This value type is not natively supported!");
133     return RC;
134   }
135   
136   /// isTypeLegal - Return true if the target has native support for the
137   /// specified value type.  This means that it has a register that directly
138   /// holds it without promotions or expansions.
139   bool isTypeLegal(MVT VT) const {
140     assert(!VT.isSimple() ||
141            (unsigned)VT.getSimpleVT() < array_lengthof(RegClassForVT));
142     return VT.isSimple() && RegClassForVT[VT.getSimpleVT()] != 0;
143   }
144
145   class ValueTypeActionImpl {
146     /// ValueTypeActions - This is a bitvector that contains two bits for each
147     /// value type, where the two bits correspond to the LegalizeAction enum.
148     /// This can be queried with "getTypeAction(VT)".
149     uint32_t ValueTypeActions[2];
150   public:
151     ValueTypeActionImpl() {
152       ValueTypeActions[0] = ValueTypeActions[1] = 0;
153     }
154     ValueTypeActionImpl(const ValueTypeActionImpl &RHS) {
155       ValueTypeActions[0] = RHS.ValueTypeActions[0];
156       ValueTypeActions[1] = RHS.ValueTypeActions[1];
157     }
158     
159     LegalizeAction getTypeAction(MVT VT) const {
160       if (VT.isExtended()) {
161         if (VT.isVector()) return Expand;
162         if (VT.isInteger())
163           // First promote to a power-of-two size, then expand if necessary.
164           return VT == VT.getRoundIntegerType() ? Expand : Promote;
165         assert(0 && "Unsupported extended type!");
166         return Legal;
167       }
168       unsigned I = VT.getSimpleVT();
169       assert(I<4*array_lengthof(ValueTypeActions)*sizeof(ValueTypeActions[0]));
170       return (LegalizeAction)((ValueTypeActions[I>>4] >> ((2*I) & 31)) & 3);
171     }
172     void setTypeAction(MVT VT, LegalizeAction Action) {
173       unsigned I = VT.getSimpleVT();
174       assert(I<4*array_lengthof(ValueTypeActions)*sizeof(ValueTypeActions[0]));
175       ValueTypeActions[I>>4] |= Action << ((I*2) & 31);
176     }
177   };
178   
179   const ValueTypeActionImpl &getValueTypeActions() const {
180     return ValueTypeActions;
181   }
182   
183   /// getTypeAction - Return how we should legalize values of this type, either
184   /// it is already legal (return 'Legal') or we need to promote it to a larger
185   /// type (return 'Promote'), or we need to expand it into multiple registers
186   /// of smaller integer type (return 'Expand').  'Custom' is not an option.
187   LegalizeAction getTypeAction(MVT VT) const {
188     return ValueTypeActions.getTypeAction(VT);
189   }
190
191   /// getTypeToTransformTo - For types supported by the target, this is an
192   /// identity function.  For types that must be promoted to larger types, this
193   /// returns the larger type to promote to.  For integer types that are larger
194   /// than the largest integer register, this contains one step in the expansion
195   /// to get to the smaller register. For illegal floating point types, this
196   /// returns the integer type to transform to.
197   MVT getTypeToTransformTo(MVT VT) const {
198     if (VT.isSimple()) {
199       assert((unsigned)VT.getSimpleVT() < array_lengthof(TransformToType));
200       MVT NVT = TransformToType[VT.getSimpleVT()];
201       assert(getTypeAction(NVT) != Promote &&
202              "Promote may not follow Expand or Promote");
203       return NVT;
204     }
205
206     if (VT.isVector())
207       return MVT::getVectorVT(VT.getVectorElementType(),
208                               VT.getVectorNumElements() / 2);
209     if (VT.isInteger()) {
210       MVT NVT = VT.getRoundIntegerType();
211       if (NVT == VT)
212         // Size is a power of two - expand to half the size.
213         return MVT::getIntegerVT(VT.getSizeInBits() / 2);
214       else
215         // Promote to a power of two size, avoiding multi-step promotion.
216         return getTypeAction(NVT) == Promote ? getTypeToTransformTo(NVT) : NVT;
217     }
218     assert(0 && "Unsupported extended type!");
219     return MVT(); // Not reached
220   }
221
222   /// getTypeToExpandTo - For types supported by the target, this is an
223   /// identity function.  For types that must be expanded (i.e. integer types
224   /// that are larger than the largest integer register or illegal floating
225   /// point types), this returns the largest legal type it will be expanded to.
226   MVT getTypeToExpandTo(MVT VT) const {
227     assert(!VT.isVector());
228     while (true) {
229       switch (getTypeAction(VT)) {
230       case Legal:
231         return VT;
232       case Expand:
233         VT = getTypeToTransformTo(VT);
234         break;
235       default:
236         assert(false && "Type is not legal nor is it to be expanded!");
237         return VT;
238       }
239     }
240     return VT;
241   }
242
243   /// getVectorTypeBreakdown - Vector types are broken down into some number of
244   /// legal first class types.  For example, MVT::v8f32 maps to 2 MVT::v4f32
245   /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
246   /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
247   ///
248   /// This method returns the number of registers needed, and the VT for each
249   /// register.  It also returns the VT and quantity of the intermediate values
250   /// before they are promoted/expanded.
251   ///
252   unsigned getVectorTypeBreakdown(MVT VT,
253                                   MVT &IntermediateVT,
254                                   unsigned &NumIntermediates,
255                                   MVT &RegisterVT) const;
256   
257   typedef std::vector<APFloat>::const_iterator legal_fpimm_iterator;
258   legal_fpimm_iterator legal_fpimm_begin() const {
259     return LegalFPImmediates.begin();
260   }
261   legal_fpimm_iterator legal_fpimm_end() const {
262     return LegalFPImmediates.end();
263   }
264   
265   /// isShuffleMaskLegal - Targets can use this to indicate that they only
266   /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
267   /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
268   /// are assumed to be legal.
269   virtual bool isShuffleMaskLegal(SDOperand Mask, MVT VT) const {
270     return true;
271   }
272
273   /// isVectorClearMaskLegal - Similar to isShuffleMaskLegal. This is
274   /// used by Targets can use this to indicate if there is a suitable
275   /// VECTOR_SHUFFLE that can be used to replace a VAND with a constant
276   /// pool entry.
277   virtual bool isVectorClearMaskLegal(const std::vector<SDOperand> &BVOps,
278                                       MVT EVT,
279                                       SelectionDAG &DAG) const {
280     return false;
281   }
282
283   /// getOperationAction - Return how this operation should be treated: either
284   /// it is legal, needs to be promoted to a larger size, needs to be
285   /// expanded to some other code sequence, or the target has a custom expander
286   /// for it.
287   LegalizeAction getOperationAction(unsigned Op, MVT VT) const {
288     if (VT.isExtended()) return Expand;
289     assert(Op < array_lengthof(OpActions) &&
290            (unsigned)VT.getSimpleVT() < sizeof(OpActions[0])*4 &&
291            "Table isn't big enough!");
292     return (LegalizeAction)((OpActions[Op] >> (2*VT.getSimpleVT())) & 3);
293   }
294   
295   /// isOperationLegal - Return true if the specified operation is legal on this
296   /// target.
297   bool isOperationLegal(unsigned Op, MVT VT) const {
298     return getOperationAction(Op, VT) == Legal ||
299            getOperationAction(Op, VT) == Custom;
300   }
301   
302   /// getLoadXAction - Return how this load with extension should be treated:
303   /// either it is legal, needs to be promoted to a larger size, needs to be
304   /// expanded to some other code sequence, or the target has a custom expander
305   /// for it.
306   LegalizeAction getLoadXAction(unsigned LType, MVT VT) const {
307     assert(LType < array_lengthof(LoadXActions) &&
308            (unsigned)VT.getSimpleVT() < sizeof(LoadXActions[0])*4 &&
309            "Table isn't big enough!");
310     return (LegalizeAction)((LoadXActions[LType] >> (2*VT.getSimpleVT())) & 3);
311   }
312   
313   /// isLoadXLegal - Return true if the specified load with extension is legal
314   /// on this target.
315   bool isLoadXLegal(unsigned LType, MVT VT) const {
316     return VT.isSimple() &&
317       (getLoadXAction(LType, VT) == Legal ||
318        getLoadXAction(LType, VT) == Custom);
319   }
320   
321   /// getTruncStoreAction - Return how this store with truncation should be
322   /// treated: either it is legal, needs to be promoted to a larger size, needs
323   /// to be expanded to some other code sequence, or the target has a custom
324   /// expander for it.
325   LegalizeAction getTruncStoreAction(MVT ValVT,
326                                      MVT MemVT) const {
327     assert((unsigned)ValVT.getSimpleVT() < array_lengthof(TruncStoreActions) &&
328            (unsigned)MemVT.getSimpleVT() < sizeof(TruncStoreActions[0])*4 &&
329            "Table isn't big enough!");
330     return (LegalizeAction)((TruncStoreActions[ValVT.getSimpleVT()] >>
331                              (2*MemVT.getSimpleVT())) & 3);
332   }
333   
334   /// isTruncStoreLegal - Return true if the specified store with truncation is
335   /// legal on this target.
336   bool isTruncStoreLegal(MVT ValVT, MVT MemVT) const {
337     return MemVT.isSimple() &&
338       (getTruncStoreAction(ValVT, MemVT) == Legal ||
339        getTruncStoreAction(ValVT, MemVT) == Custom);
340   }
341
342   /// getIndexedLoadAction - Return how the indexed load should be treated:
343   /// either it is legal, needs to be promoted to a larger size, needs to be
344   /// expanded to some other code sequence, or the target has a custom expander
345   /// for it.
346   LegalizeAction
347   getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
348     assert(IdxMode < array_lengthof(IndexedModeActions[0]) &&
349            (unsigned)VT.getSimpleVT() < sizeof(IndexedModeActions[0][0])*4 &&
350            "Table isn't big enough!");
351     return (LegalizeAction)((IndexedModeActions[0][IdxMode] >>
352                              (2*VT.getSimpleVT())) & 3);
353   }
354
355   /// isIndexedLoadLegal - Return true if the specified indexed load is legal
356   /// on this target.
357   bool isIndexedLoadLegal(unsigned IdxMode, MVT VT) const {
358     return getIndexedLoadAction(IdxMode, VT) == Legal ||
359            getIndexedLoadAction(IdxMode, VT) == Custom;
360   }
361   
362   /// getIndexedStoreAction - Return how the indexed store should be treated:
363   /// either it is legal, needs to be promoted to a larger size, needs to be
364   /// expanded to some other code sequence, or the target has a custom expander
365   /// for it.
366   LegalizeAction
367   getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
368     assert(IdxMode < array_lengthof(IndexedModeActions[1]) &&
369            (unsigned)VT.getSimpleVT() < sizeof(IndexedModeActions[1][0])*4 &&
370            "Table isn't big enough!");
371     return (LegalizeAction)((IndexedModeActions[1][IdxMode] >>
372                              (2*VT.getSimpleVT())) & 3);
373   }  
374   
375   /// isIndexedStoreLegal - Return true if the specified indexed load is legal
376   /// on this target.
377   bool isIndexedStoreLegal(unsigned IdxMode, MVT VT) const {
378     return getIndexedStoreAction(IdxMode, VT) == Legal ||
379            getIndexedStoreAction(IdxMode, VT) == Custom;
380   }
381   
382   /// getConvertAction - Return how the conversion should be treated:
383   /// either it is legal, needs to be promoted to a larger size, needs to be
384   /// expanded to some other code sequence, or the target has a custom expander
385   /// for it.
386   LegalizeAction
387   getConvertAction(MVT FromVT, MVT ToVT) const {
388     assert((unsigned)FromVT.getSimpleVT() < array_lengthof(ConvertActions) &&
389            (unsigned)ToVT.getSimpleVT() < sizeof(ConvertActions[0])*4 &&
390            "Table isn't big enough!");
391     return (LegalizeAction)((ConvertActions[FromVT.getSimpleVT()] >>
392                              (2*ToVT.getSimpleVT())) & 3);
393   }
394
395   /// isConvertLegal - Return true if the specified conversion is legal
396   /// on this target.
397   bool isConvertLegal(MVT FromVT, MVT ToVT) const {
398     return getConvertAction(FromVT, ToVT) == Legal ||
399            getConvertAction(FromVT, ToVT) == Custom;
400   }
401
402   /// getTypeToPromoteTo - If the action for this operation is to promote, this
403   /// method returns the ValueType to promote to.
404   MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
405     assert(getOperationAction(Op, VT) == Promote &&
406            "This operation isn't promoted!");
407
408     // See if this has an explicit type specified.
409     std::map<std::pair<unsigned, MVT>,
410              MVT>::const_iterator PTTI =
411       PromoteToType.find(std::make_pair(Op, VT));
412     if (PTTI != PromoteToType.end()) return PTTI->second;
413
414     assert((VT.isInteger() || VT.isFloatingPoint()) &&
415            "Cannot autopromote this type, add it with AddPromotedToType.");
416     
417     MVT NVT = VT;
418     do {
419       NVT = (MVT::SimpleValueType)(NVT.getSimpleVT()+1);
420       assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
421              "Didn't find type to promote to!");
422     } while (!isTypeLegal(NVT) ||
423               getOperationAction(Op, NVT) == Promote);
424     return NVT;
425   }
426
427   /// getValueType - Return the MVT corresponding to this LLVM type.
428   /// This is fixed by the LLVM operations except for the pointer size.  If
429   /// AllowUnknown is true, this will return MVT::Other for types with no MVT
430   /// counterpart (e.g. structs), otherwise it will assert.
431   MVT getValueType(const Type *Ty, bool AllowUnknown = false) const {
432     MVT VT = MVT::getMVT(Ty, AllowUnknown);
433     return VT == MVT::iPTR ? PointerTy : VT;
434   }
435
436   /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
437   /// function arguments in the caller parameter area.  This is the actual
438   /// alignment, not its logarithm.
439   virtual unsigned getByValTypeAlignment(const Type *Ty) const;
440   
441   /// getRegisterType - Return the type of registers that this ValueType will
442   /// eventually require.
443   MVT getRegisterType(MVT VT) const {
444     if (VT.isSimple()) {
445       assert((unsigned)VT.getSimpleVT() < array_lengthof(RegisterTypeForVT));
446       return RegisterTypeForVT[VT.getSimpleVT()];
447     }
448     if (VT.isVector()) {
449       MVT VT1, RegisterVT;
450       unsigned NumIntermediates;
451       (void)getVectorTypeBreakdown(VT, VT1, NumIntermediates, RegisterVT);
452       return RegisterVT;
453     }
454     if (VT.isInteger()) {
455       return getRegisterType(getTypeToTransformTo(VT));
456     }
457     assert(0 && "Unsupported extended type!");
458     return MVT(); // Not reached
459   }
460
461   /// getNumRegisters - Return the number of registers that this ValueType will
462   /// eventually require.  This is one for any types promoted to live in larger
463   /// registers, but may be more than one for types (like i64) that are split
464   /// into pieces.  For types like i140, which are first promoted then expanded,
465   /// it is the number of registers needed to hold all the bits of the original
466   /// type.  For an i140 on a 32 bit machine this means 5 registers.
467   unsigned getNumRegisters(MVT VT) const {
468     if (VT.isSimple()) {
469       assert((unsigned)VT.getSimpleVT() < array_lengthof(NumRegistersForVT));
470       return NumRegistersForVT[VT.getSimpleVT()];
471     }
472     if (VT.isVector()) {
473       MVT VT1, VT2;
474       unsigned NumIntermediates;
475       return getVectorTypeBreakdown(VT, VT1, NumIntermediates, VT2);
476     }
477     if (VT.isInteger()) {
478       unsigned BitWidth = VT.getSizeInBits();
479       unsigned RegWidth = getRegisterType(VT).getSizeInBits();
480       return (BitWidth + RegWidth - 1) / RegWidth;
481     }
482     assert(0 && "Unsupported extended type!");
483     return 0; // Not reached
484   }
485
486   /// ShouldShrinkFPConstant - If true, then instruction selection should
487   /// seek to shrink the FP constant of the specified type to a smaller type
488   /// in order to save space and / or reduce runtime.
489   virtual bool ShouldShrinkFPConstant(MVT VT) const { return true; }
490
491   /// hasTargetDAGCombine - If true, the target has custom DAG combine
492   /// transformations that it can perform for the specified node.
493   bool hasTargetDAGCombine(ISD::NodeType NT) const {
494     assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
495     return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
496   }
497
498   /// This function returns the maximum number of store operations permitted
499   /// to replace a call to llvm.memset. The value is set by the target at the
500   /// performance threshold for such a replacement.
501   /// @brief Get maximum # of store operations permitted for llvm.memset
502   unsigned getMaxStoresPerMemset() const { return maxStoresPerMemset; }
503
504   /// This function returns the maximum number of store operations permitted
505   /// to replace a call to llvm.memcpy. The value is set by the target at the
506   /// performance threshold for such a replacement.
507   /// @brief Get maximum # of store operations permitted for llvm.memcpy
508   unsigned getMaxStoresPerMemcpy() const { return maxStoresPerMemcpy; }
509
510   /// This function returns the maximum number of store operations permitted
511   /// to replace a call to llvm.memmove. The value is set by the target at the
512   /// performance threshold for such a replacement.
513   /// @brief Get maximum # of store operations permitted for llvm.memmove
514   unsigned getMaxStoresPerMemmove() const { return maxStoresPerMemmove; }
515
516   /// This function returns true if the target allows unaligned memory accesses.
517   /// This is used, for example, in situations where an array copy/move/set is 
518   /// converted to a sequence of store operations. It's use helps to ensure that
519   /// such replacements don't generate code that causes an alignment error 
520   /// (trap) on the target machine. 
521   /// @brief Determine if the target supports unaligned memory accesses.
522   bool allowsUnalignedMemoryAccesses() const {
523     return allowUnalignedMemoryAccesses;
524   }
525
526   /// getOptimalMemOpType - Returns the target specific optimal type for load
527   /// and store operations as a result of memset, memcpy, and memmove lowering.
528   /// It returns MVT::iAny if SelectionDAG should be responsible for
529   /// determining it.
530   virtual MVT getOptimalMemOpType(uint64_t Size, unsigned Align,
531                                   bool isSrcConst, bool isSrcStr) const {
532     return MVT::iAny;
533   }
534   
535   /// usesUnderscoreSetJmp - Determine if we should use _setjmp or setjmp
536   /// to implement llvm.setjmp.
537   bool usesUnderscoreSetJmp() const {
538     return UseUnderscoreSetJmp;
539   }
540
541   /// usesUnderscoreLongJmp - Determine if we should use _longjmp or longjmp
542   /// to implement llvm.longjmp.
543   bool usesUnderscoreLongJmp() const {
544     return UseUnderscoreLongJmp;
545   }
546
547   /// getStackPointerRegisterToSaveRestore - If a physical register, this
548   /// specifies the register that llvm.savestack/llvm.restorestack should save
549   /// and restore.
550   unsigned getStackPointerRegisterToSaveRestore() const {
551     return StackPointerRegisterToSaveRestore;
552   }
553
554   /// getExceptionAddressRegister - If a physical register, this returns
555   /// the register that receives the exception address on entry to a landing
556   /// pad.
557   unsigned getExceptionAddressRegister() const {
558     return ExceptionPointerRegister;
559   }
560
561   /// getExceptionSelectorRegister - If a physical register, this returns
562   /// the register that receives the exception typeid on entry to a landing
563   /// pad.
564   unsigned getExceptionSelectorRegister() const {
565     return ExceptionSelectorRegister;
566   }
567
568   /// getJumpBufSize - returns the target's jmp_buf size in bytes (if never
569   /// set, the default is 200)
570   unsigned getJumpBufSize() const {
571     return JumpBufSize;
572   }
573
574   /// getJumpBufAlignment - returns the target's jmp_buf alignment in bytes
575   /// (if never set, the default is 0)
576   unsigned getJumpBufAlignment() const {
577     return JumpBufAlignment;
578   }
579
580   /// getIfCvtBlockLimit - returns the target specific if-conversion block size
581   /// limit. Any block whose size is greater should not be predicated.
582   unsigned getIfCvtBlockSizeLimit() const {
583     return IfCvtBlockSizeLimit;
584   }
585
586   /// getIfCvtDupBlockLimit - returns the target specific size limit for a
587   /// block to be considered for duplication. Any block whose size is greater
588   /// should not be duplicated to facilitate its predication.
589   unsigned getIfCvtDupBlockSizeLimit() const {
590     return IfCvtDupBlockSizeLimit;
591   }
592
593   /// getPrefLoopAlignment - return the preferred loop alignment.
594   ///
595   unsigned getPrefLoopAlignment() const {
596     return PrefLoopAlignment;
597   }
598   
599   /// getPreIndexedAddressParts - returns true by value, base pointer and
600   /// offset pointer and addressing mode by reference if the node's address
601   /// can be legally represented as pre-indexed load / store address.
602   virtual bool getPreIndexedAddressParts(SDNode *N, SDOperand &Base,
603                                          SDOperand &Offset,
604                                          ISD::MemIndexedMode &AM,
605                                          SelectionDAG &DAG) {
606     return false;
607   }
608   
609   /// getPostIndexedAddressParts - returns true by value, base pointer and
610   /// offset pointer and addressing mode by reference if this node can be
611   /// combined with a load / store to form a post-indexed load / store.
612   virtual bool getPostIndexedAddressParts(SDNode *N, SDNode *Op,
613                                           SDOperand &Base, SDOperand &Offset,
614                                           ISD::MemIndexedMode &AM,
615                                           SelectionDAG &DAG) {
616     return false;
617   }
618   
619   /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
620   /// jumptable.
621   virtual SDOperand getPICJumpTableRelocBase(SDOperand Table,
622                                              SelectionDAG &DAG) const;
623
624   //===--------------------------------------------------------------------===//
625   // TargetLowering Optimization Methods
626   //
627   
628   /// TargetLoweringOpt - A convenience struct that encapsulates a DAG, and two
629   /// SDOperands for returning information from TargetLowering to its clients
630   /// that want to combine 
631   struct TargetLoweringOpt {
632     SelectionDAG &DAG;
633     bool AfterLegalize;
634     SDOperand Old;
635     SDOperand New;
636
637     explicit TargetLoweringOpt(SelectionDAG &InDAG, bool afterLegalize)
638       : DAG(InDAG), AfterLegalize(afterLegalize) {}
639     
640     bool CombineTo(SDOperand O, SDOperand N) { 
641       Old = O; 
642       New = N; 
643       return true;
644     }
645     
646     /// ShrinkDemandedConstant - Check to see if the specified operand of the 
647     /// specified instruction is a constant integer.  If so, check to see if
648     /// there are any bits set in the constant that are not demanded.  If so,
649     /// shrink the constant and return true.
650     bool ShrinkDemandedConstant(SDOperand Op, const APInt &Demanded);
651   };
652                                                 
653   /// SimplifyDemandedBits - Look at Op.  At this point, we know that only the
654   /// DemandedMask bits of the result of Op are ever used downstream.  If we can
655   /// use this information to simplify Op, create a new simplified DAG node and
656   /// return true, returning the original and new nodes in Old and New. 
657   /// Otherwise, analyze the expression and return a mask of KnownOne and 
658   /// KnownZero bits for the expression (used to simplify the caller).  
659   /// The KnownZero/One bits may only be accurate for those bits in the 
660   /// DemandedMask.
661   bool SimplifyDemandedBits(SDOperand Op, const APInt &DemandedMask, 
662                             APInt &KnownZero, APInt &KnownOne,
663                             TargetLoweringOpt &TLO, unsigned Depth = 0) const;
664   
665   /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
666   /// Mask are known to be either zero or one and return them in the 
667   /// KnownZero/KnownOne bitsets.
668   virtual void computeMaskedBitsForTargetNode(const SDOperand Op,
669                                               const APInt &Mask,
670                                               APInt &KnownZero, 
671                                               APInt &KnownOne,
672                                               const SelectionDAG &DAG,
673                                               unsigned Depth = 0) const;
674
675   /// ComputeNumSignBitsForTargetNode - This method can be implemented by
676   /// targets that want to expose additional information about sign bits to the
677   /// DAG Combiner.
678   virtual unsigned ComputeNumSignBitsForTargetNode(SDOperand Op,
679                                                    unsigned Depth = 0) const;
680   
681   struct DAGCombinerInfo {
682     void *DC;  // The DAG Combiner object.
683     bool BeforeLegalize;
684     bool CalledByLegalizer;
685   public:
686     SelectionDAG &DAG;
687     
688     DAGCombinerInfo(SelectionDAG &dag, bool bl, bool cl, void *dc)
689       : DC(dc), BeforeLegalize(bl), CalledByLegalizer(cl), DAG(dag) {}
690     
691     bool isBeforeLegalize() const { return BeforeLegalize; }
692     bool isCalledByLegalizer() const { return CalledByLegalizer; }
693     
694     void AddToWorklist(SDNode *N);
695     SDOperand CombineTo(SDNode *N, const std::vector<SDOperand> &To);
696     SDOperand CombineTo(SDNode *N, SDOperand Res);
697     SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1);
698   };
699
700   /// SimplifySetCC - Try to simplify a setcc built with the specified operands 
701   /// and cc. If it is unable to simplify it, return a null SDOperand.
702   SDOperand SimplifySetCC(MVT VT, SDOperand N0, SDOperand N1,
703                           ISD::CondCode Cond, bool foldBooleans,
704                           DAGCombinerInfo &DCI) const;
705
706   /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
707   /// node is a GlobalAddress + offset.
708   virtual bool
709   isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) const;
710
711   /// isConsecutiveLoad - Return true if LD (which must be a LoadSDNode) is
712   /// loading 'Bytes' bytes from a location that is 'Dist' units away from the
713   /// location that the 'Base' load is loading from.
714   bool isConsecutiveLoad(SDNode *LD, SDNode *Base, unsigned Bytes, int Dist,
715                          const MachineFrameInfo *MFI) const;
716
717   /// PerformDAGCombine - This method will be invoked for all target nodes and
718   /// for any target-independent nodes that the target has registered with
719   /// invoke it for.
720   ///
721   /// The semantics are as follows:
722   /// Return Value:
723   ///   SDOperand.Val == 0   - No change was made
724   ///   SDOperand.Val == N   - N was replaced, is dead, and is already handled.
725   ///   otherwise            - N should be replaced by the returned Operand.
726   ///
727   /// In addition, methods provided by DAGCombinerInfo may be used to perform
728   /// more complex transformations.
729   ///
730   virtual SDOperand PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
731   
732   //===--------------------------------------------------------------------===//
733   // TargetLowering Configuration Methods - These methods should be invoked by
734   // the derived class constructor to configure this object for the target.
735   //
736
737 protected:
738   /// setUsesGlobalOffsetTable - Specify that this target does or doesn't use a
739   /// GOT for PC-relative code.
740   void setUsesGlobalOffsetTable(bool V) { UsesGlobalOffsetTable = V; }
741
742   /// setShiftAmountType - Describe the type that should be used for shift
743   /// amounts.  This type defaults to the pointer type.
744   void setShiftAmountType(MVT VT) { ShiftAmountTy = VT; }
745
746   /// setSetCCResultContents - Specify how the target extends the result of a
747   /// setcc operation in a register.
748   void setSetCCResultContents(SetCCResultValue Ty) { SetCCResultContents = Ty; }
749
750   /// setSchedulingPreference - Specify the target scheduling preference.
751   void setSchedulingPreference(SchedPreference Pref) {
752     SchedPreferenceInfo = Pref;
753   }
754
755   /// setShiftAmountFlavor - Describe how the target handles out of range shift
756   /// amounts.
757   void setShiftAmountFlavor(OutOfRangeShiftAmount OORSA) {
758     ShiftAmtHandling = OORSA;
759   }
760
761   /// setUseUnderscoreSetJmp - Indicate whether this target prefers to
762   /// use _setjmp to implement llvm.setjmp or the non _ version.
763   /// Defaults to false.
764   void setUseUnderscoreSetJmp(bool Val) {
765     UseUnderscoreSetJmp = Val;
766   }
767
768   /// setUseUnderscoreLongJmp - Indicate whether this target prefers to
769   /// use _longjmp to implement llvm.longjmp or the non _ version.
770   /// Defaults to false.
771   void setUseUnderscoreLongJmp(bool Val) {
772     UseUnderscoreLongJmp = Val;
773   }
774
775   /// setStackPointerRegisterToSaveRestore - If set to a physical register, this
776   /// specifies the register that llvm.savestack/llvm.restorestack should save
777   /// and restore.
778   void setStackPointerRegisterToSaveRestore(unsigned R) {
779     StackPointerRegisterToSaveRestore = R;
780   }
781   
782   /// setExceptionPointerRegister - If set to a physical register, this sets
783   /// the register that receives the exception address on entry to a landing
784   /// pad.
785   void setExceptionPointerRegister(unsigned R) {
786     ExceptionPointerRegister = R;
787   }
788
789   /// setExceptionSelectorRegister - If set to a physical register, this sets
790   /// the register that receives the exception typeid on entry to a landing
791   /// pad.
792   void setExceptionSelectorRegister(unsigned R) {
793     ExceptionSelectorRegister = R;
794   }
795
796   /// SelectIsExpensive - Tells the code generator not to expand operations
797   /// into sequences that use the select operations if possible.
798   void setSelectIsExpensive() { SelectIsExpensive = true; }
799
800   /// setIntDivIsCheap - Tells the code generator that integer divide is
801   /// expensive, and if possible, should be replaced by an alternate sequence
802   /// of instructions not containing an integer divide.
803   void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
804   
805   /// setPow2DivIsCheap - Tells the code generator that it shouldn't generate
806   /// srl/add/sra for a signed divide by power of two, and let the target handle
807   /// it.
808   void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
809   
810   /// addRegisterClass - Add the specified register class as an available
811   /// regclass for the specified value type.  This indicates the selector can
812   /// handle values of that class natively.
813   void addRegisterClass(MVT VT, TargetRegisterClass *RC) {
814     assert((unsigned)VT.getSimpleVT() < array_lengthof(RegClassForVT));
815     AvailableRegClasses.push_back(std::make_pair(VT, RC));
816     RegClassForVT[VT.getSimpleVT()] = RC;
817   }
818
819   /// computeRegisterProperties - Once all of the register classes are added,
820   /// this allows us to compute derived properties we expose.
821   void computeRegisterProperties();
822
823   /// setOperationAction - Indicate that the specified operation does not work
824   /// with the specified type and indicate what to do about it.
825   void setOperationAction(unsigned Op, MVT VT,
826                           LegalizeAction Action) {
827     assert((unsigned)VT.getSimpleVT() < sizeof(OpActions[0])*4 &&
828            Op < array_lengthof(OpActions) && "Table isn't big enough!");
829     OpActions[Op] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
830     OpActions[Op] |= (uint64_t)Action << VT.getSimpleVT()*2;
831   }
832   
833   /// setLoadXAction - Indicate that the specified load with extension does not
834   /// work with the with specified type and indicate what to do about it.
835   void setLoadXAction(unsigned ExtType, MVT VT,
836                       LegalizeAction Action) {
837     assert((unsigned)VT.getSimpleVT() < sizeof(LoadXActions[0])*4 &&
838            ExtType < array_lengthof(LoadXActions) &&
839            "Table isn't big enough!");
840     LoadXActions[ExtType] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
841     LoadXActions[ExtType] |= (uint64_t)Action << VT.getSimpleVT()*2;
842   }
843   
844   /// setTruncStoreAction - Indicate that the specified truncating store does
845   /// not work with the with specified type and indicate what to do about it.
846   void setTruncStoreAction(MVT ValVT, MVT MemVT,
847                            LegalizeAction Action) {
848     assert((unsigned)ValVT.getSimpleVT() < array_lengthof(TruncStoreActions) &&
849            (unsigned)MemVT.getSimpleVT() < sizeof(TruncStoreActions[0])*4 &&
850            "Table isn't big enough!");
851     TruncStoreActions[ValVT.getSimpleVT()] &= ~(uint64_t(3UL) <<
852                                                 MemVT.getSimpleVT()*2);
853     TruncStoreActions[ValVT.getSimpleVT()] |= (uint64_t)Action <<
854       MemVT.getSimpleVT()*2;
855   }
856
857   /// setIndexedLoadAction - Indicate that the specified indexed load does or
858   /// does not work with the with specified type and indicate what to do abort
859   /// it. NOTE: All indexed mode loads are initialized to Expand in
860   /// TargetLowering.cpp
861   void setIndexedLoadAction(unsigned IdxMode, MVT VT,
862                             LegalizeAction Action) {
863     assert((unsigned)VT.getSimpleVT() < sizeof(IndexedModeActions[0])*4 &&
864            IdxMode < array_lengthof(IndexedModeActions[0]) &&
865            "Table isn't big enough!");
866     IndexedModeActions[0][IdxMode] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
867     IndexedModeActions[0][IdxMode] |= (uint64_t)Action << VT.getSimpleVT()*2;
868   }
869   
870   /// setIndexedStoreAction - Indicate that the specified indexed store does or
871   /// does not work with the with specified type and indicate what to do about
872   /// it. NOTE: All indexed mode stores are initialized to Expand in
873   /// TargetLowering.cpp
874   void setIndexedStoreAction(unsigned IdxMode, MVT VT,
875                              LegalizeAction Action) {
876     assert((unsigned)VT.getSimpleVT() < sizeof(IndexedModeActions[1][0])*4 &&
877            IdxMode < array_lengthof(IndexedModeActions[1]) &&
878            "Table isn't big enough!");
879     IndexedModeActions[1][IdxMode] &= ~(uint64_t(3UL) << VT.getSimpleVT()*2);
880     IndexedModeActions[1][IdxMode] |= (uint64_t)Action << VT.getSimpleVT()*2;
881   }
882   
883   /// setConvertAction - Indicate that the specified conversion does or does
884   /// not work with the with specified type and indicate what to do about it.
885   void setConvertAction(MVT FromVT, MVT ToVT,
886                         LegalizeAction Action) {
887     assert((unsigned)FromVT.getSimpleVT() < array_lengthof(ConvertActions) &&
888            (unsigned)ToVT.getSimpleVT() < sizeof(ConvertActions[0])*4 &&
889            "Table isn't big enough!");
890     ConvertActions[FromVT.getSimpleVT()] &= ~(uint64_t(3UL) <<
891                                               ToVT.getSimpleVT()*2);
892     ConvertActions[FromVT.getSimpleVT()] |= (uint64_t)Action <<
893       ToVT.getSimpleVT()*2;
894   }
895
896   /// AddPromotedToType - If Opc/OrigVT is specified as being promoted, the
897   /// promotion code defaults to trying a larger integer/fp until it can find
898   /// one that works.  If that default is insufficient, this method can be used
899   /// by the target to override the default.
900   void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
901     PromoteToType[std::make_pair(Opc, OrigVT)] = DestVT;
902   }
903
904   /// addLegalFPImmediate - Indicate that this target can instruction select
905   /// the specified FP immediate natively.
906   void addLegalFPImmediate(const APFloat& Imm) {
907     LegalFPImmediates.push_back(Imm);
908   }
909
910   /// setTargetDAGCombine - Targets should invoke this method for each target
911   /// independent node that they want to provide a custom DAG combiner for by
912   /// implementing the PerformDAGCombine virtual method.
913   void setTargetDAGCombine(ISD::NodeType NT) {
914     assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
915     TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
916   }
917   
918   /// setJumpBufSize - Set the target's required jmp_buf buffer size (in
919   /// bytes); default is 200
920   void setJumpBufSize(unsigned Size) {
921     JumpBufSize = Size;
922   }
923
924   /// setJumpBufAlignment - Set the target's required jmp_buf buffer
925   /// alignment (in bytes); default is 0
926   void setJumpBufAlignment(unsigned Align) {
927     JumpBufAlignment = Align;
928   }
929
930   /// setIfCvtBlockSizeLimit - Set the target's if-conversion block size
931   /// limit (in number of instructions); default is 2.
932   void setIfCvtBlockSizeLimit(unsigned Limit) {
933     IfCvtBlockSizeLimit = Limit;
934   }
935   
936   /// setIfCvtDupBlockSizeLimit - Set the target's block size limit (in number
937   /// of instructions) to be considered for code duplication during
938   /// if-conversion; default is 2.
939   void setIfCvtDupBlockSizeLimit(unsigned Limit) {
940     IfCvtDupBlockSizeLimit = Limit;
941   }
942
943   /// setPrefLoopAlignment - Set the target's preferred loop alignment. Default
944   /// alignment is zero, it means the target does not care about loop alignment.
945   void setPrefLoopAlignment(unsigned Align) {
946     PrefLoopAlignment = Align;
947   }
948   
949 public:
950
951   virtual const TargetSubtarget *getSubtarget() {
952     assert(0 && "Not Implemented");
953     return NULL;    // this is here to silence compiler errors
954   }
955   //===--------------------------------------------------------------------===//
956   // Lowering methods - These methods must be implemented by targets so that
957   // the SelectionDAGLowering code knows how to lower these.
958   //
959
960   /// LowerArguments - This hook must be implemented to indicate how we should
961   /// lower the arguments for the specified function, into the specified DAG.
962   virtual std::vector<SDOperand>
963   LowerArguments(Function &F, SelectionDAG &DAG);
964
965   /// LowerCallTo - This hook lowers an abstract call to a function into an
966   /// actual call.  This returns a pair of operands.  The first element is the
967   /// return value for the function (if RetTy is not VoidTy).  The second
968   /// element is the outgoing token chain.
969   struct ArgListEntry {
970     SDOperand Node;
971     const Type* Ty;
972     bool isSExt;
973     bool isZExt;
974     bool isInReg;
975     bool isSRet;
976     bool isNest;
977     bool isByVal;
978     uint16_t Alignment;
979
980     ArgListEntry() : isSExt(false), isZExt(false), isInReg(false),
981       isSRet(false), isNest(false), isByVal(false), Alignment(0) { }
982   };
983   typedef std::vector<ArgListEntry> ArgListTy;
984   virtual std::pair<SDOperand, SDOperand>
985   LowerCallTo(SDOperand Chain, const Type *RetTy, bool RetSExt, bool RetZExt,
986               bool isVarArg, unsigned CallingConv, bool isTailCall,
987               SDOperand Callee, ArgListTy &Args, SelectionDAG &DAG);
988
989
990   /// EmitTargetCodeForMemcpy - Emit target-specific code that performs a
991   /// memcpy. This can be used by targets to provide code sequences for cases
992   /// that don't fit the target's parameters for simple loads/stores and can be
993   /// more efficient than using a library call. This function can return a null
994   /// SDOperand if the target declines to use custom code and a different
995   /// lowering strategy should be used.
996   /// 
997   /// If AlwaysInline is true, the size is constant and the target should not
998   /// emit any calls and is strongly encouraged to attempt to emit inline code
999   /// even if it is beyond the usual threshold because this intrinsic is being
1000   /// expanded in a place where calls are not feasible (e.g. within the prologue
1001   /// for another call). If the target chooses to decline an AlwaysInline
1002   /// request here, legalize will resort to using simple loads and stores.
1003   virtual SDOperand
1004   EmitTargetCodeForMemcpy(SelectionDAG &DAG,
1005                           SDOperand Chain,
1006                           SDOperand Op1, SDOperand Op2,
1007                           SDOperand Op3, unsigned Align,
1008                           bool AlwaysInline,
1009                           const Value *DstSV, uint64_t DstOff,
1010                           const Value *SrcSV, uint64_t SrcOff) {
1011     return SDOperand();
1012   }
1013
1014   /// EmitTargetCodeForMemmove - Emit target-specific code that performs a
1015   /// memmove. This can be used by targets to provide code sequences for cases
1016   /// that don't fit the target's parameters for simple loads/stores and can be
1017   /// more efficient than using a library call. This function can return a null
1018   /// SDOperand if the target declines to use custom code and a different
1019   /// lowering strategy should be used.
1020   virtual SDOperand
1021   EmitTargetCodeForMemmove(SelectionDAG &DAG,
1022                            SDOperand Chain,
1023                            SDOperand Op1, SDOperand Op2,
1024                            SDOperand Op3, unsigned Align,
1025                            const Value *DstSV, uint64_t DstOff,
1026                            const Value *SrcSV, uint64_t SrcOff) {
1027     return SDOperand();
1028   }
1029
1030   /// EmitTargetCodeForMemset - Emit target-specific code that performs a
1031   /// memset. This can be used by targets to provide code sequences for cases
1032   /// that don't fit the target's parameters for simple stores and can be more
1033   /// efficient than using a library call. This function can return a null
1034   /// SDOperand if the target declines to use custom code and a different
1035   /// lowering strategy should be used.
1036   virtual SDOperand
1037   EmitTargetCodeForMemset(SelectionDAG &DAG,
1038                           SDOperand Chain,
1039                           SDOperand Op1, SDOperand Op2,
1040                           SDOperand Op3, unsigned Align,
1041                           const Value *DstSV, uint64_t DstOff) {
1042     return SDOperand();
1043   }
1044
1045   /// LowerOperation - This callback is invoked for operations that are 
1046   /// unsupported by the target, which are registered to use 'custom' lowering,
1047   /// and whose defined values are all legal.
1048   /// If the target has no operations that require custom lowering, it need not
1049   /// implement this.  The default implementation of this aborts.
1050   virtual SDOperand LowerOperation(SDOperand Op, SelectionDAG &DAG);
1051
1052   /// ExpandOperationResult - This callback is invoked for operations that are 
1053   /// unsupported by the target, which are registered to use 'custom' lowering,
1054   /// and whose result type needs to be expanded.  This must return a node whose
1055   /// results precisely match the results of the input node.  This typically
1056   /// involves a MERGE_VALUES node and/or BUILD_PAIR.
1057   ///
1058   /// If the target has no operations that require custom lowering, it need not
1059   /// implement this.  The default implementation of this aborts.
1060   virtual SDNode *ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
1061     assert(0 && "ExpandOperationResult not implemented for this target!");
1062     return 0;
1063   }
1064   
1065   /// IsEligibleForTailCallOptimization - Check whether the call is eligible for
1066   /// tail call optimization. Targets which want to do tail call optimization
1067   /// should override this function. 
1068   virtual bool IsEligibleForTailCallOptimization(SDOperand Call, 
1069                                                  SDOperand Ret, 
1070                                                  SelectionDAG &DAG) const {
1071     return false;
1072   }
1073
1074   /// CheckTailCallReturnConstraints - Check whether CALL node immediatly
1075   /// preceeds the RET node and whether the return uses the result of the node
1076   /// or is a void return. This function can be used by the target to determine
1077   /// eligiblity of tail call optimization.
1078   static bool CheckTailCallReturnConstraints(SDOperand Call, SDOperand Ret) {
1079     unsigned NumOps = Ret.getNumOperands();
1080     if ((NumOps == 1 &&
1081        (Ret.getOperand(0) == SDOperand(Call.Val,1) ||
1082         Ret.getOperand(0) == SDOperand(Call.Val,0))) ||
1083       (NumOps > 1 &&
1084        Ret.getOperand(0) == SDOperand(Call.Val,Call.Val->getNumValues()-1) &&
1085        Ret.getOperand(1) == SDOperand(Call.Val,0)))
1086       return true;
1087     return false;
1088   }
1089
1090   /// GetPossiblePreceedingTailCall - Get preceeding TailCallNodeOpCode node if
1091   /// it exists skip possible ISD:TokenFactor.
1092   static SDOperand GetPossiblePreceedingTailCall(SDOperand Chain,
1093                                                  unsigned TailCallNodeOpCode) {
1094     if (Chain.getOpcode() == TailCallNodeOpCode) {
1095       return Chain;
1096     } else if (Chain.getOpcode() == ISD::TokenFactor) {
1097       if (Chain.getNumOperands() &&
1098           Chain.getOperand(0).getOpcode() == TailCallNodeOpCode)
1099         return Chain.getOperand(0);
1100     }
1101     return Chain;
1102   }
1103
1104   /// CustomPromoteOperation - This callback is invoked for operations that are
1105   /// unsupported by the target, are registered to use 'custom' lowering, and
1106   /// whose type needs to be promoted.
1107   virtual SDOperand CustomPromoteOperation(SDOperand Op, SelectionDAG &DAG);
1108   
1109   /// getTargetNodeName() - This method returns the name of a target specific
1110   /// DAG node.
1111   virtual const char *getTargetNodeName(unsigned Opcode) const;
1112
1113   //===--------------------------------------------------------------------===//
1114   // Inline Asm Support hooks
1115   //
1116   
1117   enum ConstraintType {
1118     C_Register,            // Constraint represents a single register.
1119     C_RegisterClass,       // Constraint represents one or more registers.
1120     C_Memory,              // Memory constraint.
1121     C_Other,               // Something else.
1122     C_Unknown              // Unsupported constraint.
1123   };
1124   
1125   /// AsmOperandInfo - This contains information for each constraint that we are
1126   /// lowering.
1127   struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
1128     /// ConstraintCode - This contains the actual string for the code, like "m".
1129     std::string ConstraintCode;
1130
1131     /// ConstraintType - Information about the constraint code, e.g. Register,
1132     /// RegisterClass, Memory, Other, Unknown.
1133     TargetLowering::ConstraintType ConstraintType;
1134   
1135     /// CallOperandval - If this is the result output operand or a
1136     /// clobber, this is null, otherwise it is the incoming operand to the
1137     /// CallInst.  This gets modified as the asm is processed.
1138     Value *CallOperandVal;
1139   
1140     /// ConstraintVT - The ValueType for the operand value.
1141     MVT ConstraintVT;
1142   
1143     AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
1144       : InlineAsm::ConstraintInfo(info), 
1145         ConstraintType(TargetLowering::C_Unknown),
1146         CallOperandVal(0), ConstraintVT(MVT::Other) {
1147     }
1148   };
1149
1150   /// ComputeConstraintToUse - Determines the constraint code and constraint
1151   /// type to use for the specific AsmOperandInfo, setting
1152   /// OpInfo.ConstraintCode and OpInfo.ConstraintType.  If the actual operand
1153   /// being passed in is available, it can be passed in as Op, otherwise an
1154   /// empty SDOperand can be passed.
1155   virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
1156                                       SDOperand Op,
1157                                       SelectionDAG *DAG = 0) const;
1158   
1159   /// getConstraintType - Given a constraint, return the type of constraint it
1160   /// is for this target.
1161   virtual ConstraintType getConstraintType(const std::string &Constraint) const;
1162   
1163   /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
1164   /// return a list of registers that can be used to satisfy the constraint.
1165   /// This should only be used for C_RegisterClass constraints.
1166   virtual std::vector<unsigned> 
1167   getRegClassForInlineAsmConstraint(const std::string &Constraint,
1168                                     MVT VT) const;
1169
1170   /// getRegForInlineAsmConstraint - Given a physical register constraint (e.g.
1171   /// {edx}), return the register number and the register class for the
1172   /// register.
1173   ///
1174   /// Given a register class constraint, like 'r', if this corresponds directly
1175   /// to an LLVM register class, return a register of 0 and the register class
1176   /// pointer.
1177   ///
1178   /// This should only be used for C_Register constraints.  On error,
1179   /// this returns a register number of 0 and a null register class pointer..
1180   virtual std::pair<unsigned, const TargetRegisterClass*> 
1181     getRegForInlineAsmConstraint(const std::string &Constraint,
1182                                  MVT VT) const;
1183   
1184   /// LowerXConstraint - try to replace an X constraint, which matches anything,
1185   /// with another that has more specific requirements based on the type of the
1186   /// corresponding operand.  This returns null if there is no replacement to
1187   /// make.
1188   virtual const char *LowerXConstraint(MVT ConstraintVT) const;
1189   
1190   /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
1191   /// vector.  If it is invalid, don't add anything to Ops.
1192   virtual void LowerAsmOperandForConstraint(SDOperand Op, char ConstraintLetter,
1193                                             std::vector<SDOperand> &Ops,
1194                                             SelectionDAG &DAG) const;
1195   
1196   //===--------------------------------------------------------------------===//
1197   // Scheduler hooks
1198   //
1199   
1200   // EmitInstrWithCustomInserter - This method should be implemented by targets
1201   // that mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
1202   // instructions are special in various ways, which require special support to
1203   // insert.  The specified MachineInstr is created but not inserted into any
1204   // basic blocks, and the scheduler passes ownership of it to this method.
1205   virtual MachineBasicBlock *EmitInstrWithCustomInserter(MachineInstr *MI,
1206                                                         MachineBasicBlock *MBB);
1207
1208   //===--------------------------------------------------------------------===//
1209   // Addressing mode description hooks (used by LSR etc).
1210   //
1211
1212   /// AddrMode - This represents an addressing mode of:
1213   ///    BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
1214   /// If BaseGV is null,  there is no BaseGV.
1215   /// If BaseOffs is zero, there is no base offset.
1216   /// If HasBaseReg is false, there is no base register.
1217   /// If Scale is zero, there is no ScaleReg.  Scale of 1 indicates a reg with
1218   /// no scale.
1219   ///
1220   struct AddrMode {
1221     GlobalValue *BaseGV;
1222     int64_t      BaseOffs;
1223     bool         HasBaseReg;
1224     int64_t      Scale;
1225     AddrMode() : BaseGV(0), BaseOffs(0), HasBaseReg(false), Scale(0) {}
1226   };
1227   
1228   /// isLegalAddressingMode - Return true if the addressing mode represented by
1229   /// AM is legal for this target, for a load/store of the specified type.
1230   /// TODO: Handle pre/postinc as well.
1231   virtual bool isLegalAddressingMode(const AddrMode &AM, const Type *Ty) const;
1232
1233   /// isTruncateFree - Return true if it's free to truncate a value of
1234   /// type Ty1 to type Ty2. e.g. On x86 it's free to truncate a i32 value in
1235   /// register EAX to i16 by referencing its sub-register AX.
1236   virtual bool isTruncateFree(const Type *Ty1, const Type *Ty2) const {
1237     return false;
1238   }
1239
1240   virtual bool isTruncateFree(MVT VT1, MVT VT2) const {
1241     return false;
1242   }
1243   
1244   //===--------------------------------------------------------------------===//
1245   // Div utility functions
1246   //
1247   SDOperand BuildSDIV(SDNode *N, SelectionDAG &DAG, 
1248                       std::vector<SDNode*>* Created) const;
1249   SDOperand BuildUDIV(SDNode *N, SelectionDAG &DAG, 
1250                       std::vector<SDNode*>* Created) const;
1251
1252
1253   //===--------------------------------------------------------------------===//
1254   // Runtime Library hooks
1255   //
1256
1257   /// setLibcallName - Rename the default libcall routine name for the specified
1258   /// libcall.
1259   void setLibcallName(RTLIB::Libcall Call, const char *Name) {
1260     LibcallRoutineNames[Call] = Name;
1261   }
1262
1263   /// getLibcallName - Get the libcall routine name for the specified libcall.
1264   ///
1265   const char *getLibcallName(RTLIB::Libcall Call) const {
1266     return LibcallRoutineNames[Call];
1267   }
1268
1269   /// setCmpLibcallCC - Override the default CondCode to be used to test the
1270   /// result of the comparison libcall against zero.
1271   void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
1272     CmpLibcallCCs[Call] = CC;
1273   }
1274
1275   /// getCmpLibcallCC - Get the CondCode that's to be used to test the result of
1276   /// the comparison libcall against zero.
1277   ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
1278     return CmpLibcallCCs[Call];
1279   }
1280
1281 private:
1282   TargetMachine &TM;
1283   const TargetData *TD;
1284
1285   /// IsLittleEndian - True if this is a little endian target.
1286   ///
1287   bool IsLittleEndian;
1288
1289   /// PointerTy - The type to use for pointers, usually i32 or i64.
1290   ///
1291   MVT PointerTy;
1292
1293   /// UsesGlobalOffsetTable - True if this target uses a GOT for PIC codegen.
1294   ///
1295   bool UsesGlobalOffsetTable;
1296   
1297   /// ShiftAmountTy - The type to use for shift amounts, usually i8 or whatever
1298   /// PointerTy is.
1299   MVT ShiftAmountTy;
1300
1301   OutOfRangeShiftAmount ShiftAmtHandling;
1302
1303   /// SelectIsExpensive - Tells the code generator not to expand operations
1304   /// into sequences that use the select operations if possible.
1305   bool SelectIsExpensive;
1306
1307   /// IntDivIsCheap - Tells the code generator not to expand integer divides by
1308   /// constants into a sequence of muls, adds, and shifts.  This is a hack until
1309   /// a real cost model is in place.  If we ever optimize for size, this will be
1310   /// set to true unconditionally.
1311   bool IntDivIsCheap;
1312   
1313   /// Pow2DivIsCheap - Tells the code generator that it shouldn't generate
1314   /// srl/add/sra for a signed divide by power of two, and let the target handle
1315   /// it.
1316   bool Pow2DivIsCheap;
1317   
1318   /// SetCCResultContents - Information about the contents of the high-bits in
1319   /// the result of a setcc comparison operation.
1320   SetCCResultValue SetCCResultContents;
1321
1322   /// SchedPreferenceInfo - The target scheduling preference: shortest possible
1323   /// total cycles or lowest register usage.
1324   SchedPreference SchedPreferenceInfo;
1325   
1326   /// UseUnderscoreSetJmp - This target prefers to use _setjmp to implement
1327   /// llvm.setjmp.  Defaults to false.
1328   bool UseUnderscoreSetJmp;
1329
1330   /// UseUnderscoreLongJmp - This target prefers to use _longjmp to implement
1331   /// llvm.longjmp.  Defaults to false.
1332   bool UseUnderscoreLongJmp;
1333
1334   /// JumpBufSize - The size, in bytes, of the target's jmp_buf buffers
1335   unsigned JumpBufSize;
1336   
1337   /// JumpBufAlignment - The alignment, in bytes, of the target's jmp_buf
1338   /// buffers
1339   unsigned JumpBufAlignment;
1340
1341   /// IfCvtBlockSizeLimit - The maximum allowed size for a block to be
1342   /// if-converted.
1343   unsigned IfCvtBlockSizeLimit;
1344   
1345   /// IfCvtDupBlockSizeLimit - The maximum allowed size for a block to be
1346   /// duplicated during if-conversion.
1347   unsigned IfCvtDupBlockSizeLimit;
1348
1349   /// PrefLoopAlignment - The perferred loop alignment.
1350   ///
1351   unsigned PrefLoopAlignment;
1352
1353   /// StackPointerRegisterToSaveRestore - If set to a physical register, this
1354   /// specifies the register that llvm.savestack/llvm.restorestack should save
1355   /// and restore.
1356   unsigned StackPointerRegisterToSaveRestore;
1357
1358   /// ExceptionPointerRegister - If set to a physical register, this specifies
1359   /// the register that receives the exception address on entry to a landing
1360   /// pad.
1361   unsigned ExceptionPointerRegister;
1362
1363   /// ExceptionSelectorRegister - If set to a physical register, this specifies
1364   /// the register that receives the exception typeid on entry to a landing
1365   /// pad.
1366   unsigned ExceptionSelectorRegister;
1367
1368   /// RegClassForVT - This indicates the default register class to use for
1369   /// each ValueType the target supports natively.
1370   TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
1371   unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
1372   MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
1373
1374   /// TransformToType - For any value types we are promoting or expanding, this
1375   /// contains the value type that we are changing to.  For Expanded types, this
1376   /// contains one step of the expand (e.g. i64 -> i32), even if there are
1377   /// multiple steps required (e.g. i64 -> i16).  For types natively supported
1378   /// by the system, this holds the same type (e.g. i32 -> i32).
1379   MVT TransformToType[MVT::LAST_VALUETYPE];
1380
1381   // Defines the capacity of the TargetLowering::OpActions table
1382   static const int OpActionsCapacity = 176;
1383
1384   /// OpActions - For each operation and each value type, keep a LegalizeAction
1385   /// that indicates how instruction selection should deal with the operation.
1386   /// Most operations are Legal (aka, supported natively by the target), but
1387   /// operations that are not should be described.  Note that operations on
1388   /// non-legal value types are not described here.
1389   uint64_t OpActions[OpActionsCapacity];
1390   
1391   /// LoadXActions - For each load of load extension type and each value type,
1392   /// keep a LegalizeAction that indicates how instruction selection should deal
1393   /// with the load.
1394   uint64_t LoadXActions[ISD::LAST_LOADX_TYPE];
1395   
1396   /// TruncStoreActions - For each truncating store, keep a LegalizeAction that
1397   /// indicates how instruction selection should deal with the store.
1398   uint64_t TruncStoreActions[MVT::LAST_VALUETYPE];
1399
1400   /// IndexedModeActions - For each indexed mode and each value type, keep a
1401   /// pair of LegalizeAction that indicates how instruction selection should
1402   /// deal with the load / store.
1403   uint64_t IndexedModeActions[2][ISD::LAST_INDEXED_MODE];
1404   
1405   /// ConvertActions - For each conversion from source type to destination type,
1406   /// keep a LegalizeAction that indicates how instruction selection should
1407   /// deal with the conversion.
1408   /// Currently, this is used only for floating->floating conversions
1409   /// (FP_EXTEND and FP_ROUND).
1410   uint64_t ConvertActions[MVT::LAST_VALUETYPE];
1411
1412   ValueTypeActionImpl ValueTypeActions;
1413
1414   std::vector<APFloat> LegalFPImmediates;
1415
1416   std::vector<std::pair<MVT, TargetRegisterClass*> > AvailableRegClasses;
1417
1418   /// TargetDAGCombineArray - Targets can specify ISD nodes that they would
1419   /// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(),
1420   /// which sets a bit in this array.
1421   unsigned char
1422   TargetDAGCombineArray[OpActionsCapacity/(sizeof(unsigned char)*8)];
1423   
1424   /// PromoteToType - For operations that must be promoted to a specific type,
1425   /// this holds the destination type.  This map should be sparse, so don't hold
1426   /// it as an array.
1427   ///
1428   /// Targets add entries to this map with AddPromotedToType(..), clients access
1429   /// this with getTypeToPromoteTo(..).
1430   std::map<std::pair<unsigned, MVT>, MVT> PromoteToType;
1431
1432   /// LibcallRoutineNames - Stores the name each libcall.
1433   ///
1434   const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
1435
1436   /// CmpLibcallCCs - The ISD::CondCode that should be used to test the result
1437   /// of each of the comparison libcall against zero.
1438   ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
1439
1440 protected:
1441   /// When lowering %llvm.memset this field specifies the maximum number of
1442   /// store operations that may be substituted for the call to memset. Targets
1443   /// must set this value based on the cost threshold for that target. Targets
1444   /// should assume that the memset will be done using as many of the largest
1445   /// store operations first, followed by smaller ones, if necessary, per
1446   /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
1447   /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
1448   /// store.  This only applies to setting a constant array of a constant size.
1449   /// @brief Specify maximum number of store instructions per memset call.
1450   unsigned maxStoresPerMemset;
1451
1452   /// When lowering %llvm.memcpy this field specifies the maximum number of
1453   /// store operations that may be substituted for a call to memcpy. Targets
1454   /// must set this value based on the cost threshold for that target. Targets
1455   /// should assume that the memcpy will be done using as many of the largest
1456   /// store operations first, followed by smaller ones, if necessary, per
1457   /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
1458   /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
1459   /// and one 1-byte store. This only applies to copying a constant array of
1460   /// constant size.
1461   /// @brief Specify maximum bytes of store instructions per memcpy call.
1462   unsigned maxStoresPerMemcpy;
1463
1464   /// When lowering %llvm.memmove this field specifies the maximum number of
1465   /// store instructions that may be substituted for a call to memmove. Targets
1466   /// must set this value based on the cost threshold for that target. Targets
1467   /// should assume that the memmove will be done using as many of the largest
1468   /// store operations first, followed by smaller ones, if necessary, per
1469   /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
1470   /// with 8-bit alignment would result in nine 1-byte stores.  This only
1471   /// applies to copying a constant array of constant size.
1472   /// @brief Specify maximum bytes of store instructions per memmove call.
1473   unsigned maxStoresPerMemmove;
1474
1475   /// This field specifies whether the target machine permits unaligned memory
1476   /// accesses.  This is used, for example, to determine the size of store 
1477   /// operations when copying small arrays and other similar tasks.
1478   /// @brief Indicate whether the target permits unaligned memory accesses.
1479   bool allowUnalignedMemoryAccesses;
1480 };
1481 } // end llvm namespace
1482
1483 #endif