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