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