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