Refactor TargetMachine, pushing handling of TargetData into the target-specific subcl...
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/Type.h"
26 #include "llvm/CodeGen/SelectionDAGNodes.h"
27 #include <map>
28
29 namespace llvm {
30   class Value;
31   class Function;
32   class TargetMachine;
33   class TargetData;
34   class TargetRegisterClass;
35   class SDNode;
36   class SDOperand;
37   class SelectionDAG;
38   class MachineBasicBlock;
39   class MachineInstr;
40
41 //===----------------------------------------------------------------------===//
42 /// TargetLowering - This class defines information used to lower LLVM code to
43 /// legal SelectionDAG operators that the target instruction selector can accept
44 /// natively.
45 ///
46 /// This class also defines callbacks that targets must implement to lower
47 /// target-specific constructs to SelectionDAG operators.
48 ///
49 class TargetLowering {
50 public:
51   /// LegalizeAction - This enum indicates whether operations are valid for a
52   /// target, and if not, what action should be used to make them valid.
53   enum LegalizeAction {
54     Legal,      // The target natively supports this operation.
55     Promote,    // This operation should be executed in a larger type.
56     Expand,     // Try to expand this to other ops, otherwise use a libcall.
57     Custom      // Use the LowerOperation hook to implement custom lowering.
58   };
59
60   enum OutOfRangeShiftAmount {
61     Undefined,  // Oversized shift amounts are undefined (default).
62     Mask,       // Shift amounts are auto masked (anded) to value size.
63     Extend      // Oversized shift pulls in zeros or sign bits.
64   };
65
66   enum SetCCResultValue {
67     UndefinedSetCCResult,          // SetCC returns a garbage/unknown extend.
68     ZeroOrOneSetCCResult,          // SetCC returns a zero extended result.
69     ZeroOrNegativeOneSetCCResult   // SetCC returns a sign extended result.
70   };
71
72   enum SchedPreference {
73     SchedulingForLatency,          // Scheduling for shortest total latency.
74     SchedulingForRegPressure       // Scheduling for lowest register pressure.
75   };
76
77   TargetLowering(TargetMachine &TM);
78   virtual ~TargetLowering();
79
80   TargetMachine &getTargetMachine() const { return TM; }
81   const TargetData *getTargetData() const { return TD; }
82
83   bool isLittleEndian() const { return IsLittleEndian; }
84   MVT::ValueType getPointerTy() const { return PointerTy; }
85   MVT::ValueType getShiftAmountTy() const { return ShiftAmountTy; }
86   OutOfRangeShiftAmount getShiftAmountFlavor() const {return ShiftAmtHandling; }
87
88   /// isSetCCExpensive - Return true if the setcc operation is expensive for
89   /// this target.
90   bool isSetCCExpensive() const { return SetCCIsExpensive; }
91   
92   /// isIntDivCheap() - Return true if integer divide is usually cheaper than
93   /// a sequence of several shifts, adds, and multiplies for this target.
94   bool isIntDivCheap() const { return IntDivIsCheap; }
95
96   /// isPow2DivCheap() - Return true if pow2 div is cheaper than a chain of
97   /// srl/add/sra.
98   bool isPow2DivCheap() const { return Pow2DivIsCheap; }
99   
100   /// getSetCCResultTy - Return the ValueType of the result of setcc operations.
101   ///
102   MVT::ValueType getSetCCResultTy() const { return SetCCResultTy; }
103
104   /// getSetCCResultContents - For targets without boolean registers, this flag
105   /// returns information about the contents of the high-bits in the setcc
106   /// result register.
107   SetCCResultValue getSetCCResultContents() const { return SetCCResultContents;}
108
109   /// getSchedulingPreference - Return target scheduling preference.
110   SchedPreference getSchedulingPreference() const {
111     return SchedPreferenceInfo;
112   }
113
114   /// getRegClassFor - Return the register class that should be used for the
115   /// specified value type.  This may only be called on legal types.
116   TargetRegisterClass *getRegClassFor(MVT::ValueType VT) const {
117     TargetRegisterClass *RC = RegClassForVT[VT];
118     assert(RC && "This value type is not natively supported!");
119     return RC;
120   }
121   
122   /// isTypeLegal - Return true if the target has native support for the
123   /// specified value type.  This means that it has a register that directly
124   /// holds it without promotions or expansions.
125   bool isTypeLegal(MVT::ValueType VT) const {
126     return RegClassForVT[VT] != 0;
127   }
128
129   class ValueTypeActionImpl {
130     /// ValueTypeActions - This is a bitvector that contains two bits for each
131     /// value type, where the two bits correspond to the LegalizeAction enum.
132     /// This can be queried with "getTypeAction(VT)".
133     uint32_t ValueTypeActions[2];
134   public:
135     ValueTypeActionImpl() {
136       ValueTypeActions[0] = ValueTypeActions[1] = 0;
137     }
138     ValueTypeActionImpl(const ValueTypeActionImpl &RHS) {
139       ValueTypeActions[0] = RHS.ValueTypeActions[0];
140       ValueTypeActions[1] = RHS.ValueTypeActions[1];
141     }
142     
143     LegalizeAction getTypeAction(MVT::ValueType VT) const {
144       return (LegalizeAction)((ValueTypeActions[VT>>4] >> ((2*VT) & 31)) & 3);
145     }
146     void setTypeAction(MVT::ValueType VT, LegalizeAction Action) {
147       assert(unsigned(VT >> 4) < 
148              sizeof(ValueTypeActions)/sizeof(ValueTypeActions[0]));
149       ValueTypeActions[VT>>4] |= Action << ((VT*2) & 31);
150     }
151   };
152   
153   const ValueTypeActionImpl &getValueTypeActions() const {
154     return ValueTypeActions;
155   }
156   
157   /// getTypeAction - Return how we should legalize values of this type, either
158   /// it is already legal (return 'Legal') or we need to promote it to a larger
159   /// type (return 'Promote'), or we need to expand it into multiple registers
160   /// of smaller integer type (return 'Expand').  'Custom' is not an option.
161   LegalizeAction getTypeAction(MVT::ValueType VT) const {
162     return ValueTypeActions.getTypeAction(VT);
163   }
164
165   /// getTypeToTransformTo - For types supported by the target, this is an
166   /// identity function.  For types that must be promoted to larger types, this
167   /// returns the larger type to promote to.  For types that are larger than the
168   /// largest integer register, this contains one step in the expansion to get
169   /// to the smaller register.
170   MVT::ValueType getTypeToTransformTo(MVT::ValueType VT) const {
171     return TransformToType[VT];
172   }
173   
174   /// getPackedTypeBreakdown - Packed types are broken down into some number of
175   /// legal scalar types.  For example, <8 x float> maps to 2 MVT::v2f32 values
176   /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
177   /// Similarly, <2 x long> turns into 4 MVT::i32 values with both PPC and X86.
178   ///
179   /// This method returns the number of registers needed, and the VT for each
180   /// register.  It also returns the VT of the PackedType elements before they
181   /// are promoted/expanded.
182   ///
183   unsigned getPackedTypeBreakdown(const PackedType *PTy, 
184                                   MVT::ValueType &PTyElementVT,
185                                   MVT::ValueType &PTyLegalElementVT) const;
186   
187   typedef std::vector<double>::const_iterator legal_fpimm_iterator;
188   legal_fpimm_iterator legal_fpimm_begin() const {
189     return LegalFPImmediates.begin();
190   }
191   legal_fpimm_iterator legal_fpimm_end() const {
192     return LegalFPImmediates.end();
193   }
194   
195   /// isShuffleMaskLegal - Targets can use this to indicate that they only
196   /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
197   /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
198   /// are assumed to be legal.
199   virtual bool isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
200     return true;
201   }
202
203   /// isVectorClearMaskLegal - Similar to isShuffleMaskLegal. This is
204   /// used by Targets can use this to indicate if there is a suitable
205   /// VECTOR_SHUFFLE that can be used to replace a VAND with a constant
206   /// pool entry.
207   virtual bool isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
208                                       MVT::ValueType EVT,
209                                       SelectionDAG &DAG) const {
210     return false;
211   }
212
213   /// getOperationAction - Return how this operation should be treated: either
214   /// it is legal, needs to be promoted to a larger size, needs to be
215   /// expanded to some other code sequence, or the target has a custom expander
216   /// for it.
217   LegalizeAction getOperationAction(unsigned Op, MVT::ValueType VT) const {
218     return (LegalizeAction)((OpActions[Op] >> (2*VT)) & 3);
219   }
220   
221   /// isOperationLegal - Return true if the specified operation is legal on this
222   /// target.
223   bool isOperationLegal(unsigned Op, MVT::ValueType VT) const {
224     return getOperationAction(Op, VT) == Legal ||
225            getOperationAction(Op, VT) == Custom;
226   }
227   
228   /// getTypeToPromoteTo - If the action for this operation is to promote, this
229   /// method returns the ValueType to promote to.
230   MVT::ValueType getTypeToPromoteTo(unsigned Op, MVT::ValueType VT) const {
231     assert(getOperationAction(Op, VT) == Promote &&
232            "This operation isn't promoted!");
233
234     // See if this has an explicit type specified.
235     std::map<std::pair<unsigned, MVT::ValueType>, 
236              MVT::ValueType>::const_iterator PTTI =
237       PromoteToType.find(std::make_pair(Op, VT));
238     if (PTTI != PromoteToType.end()) return PTTI->second;
239     
240     assert((MVT::isInteger(VT) || MVT::isFloatingPoint(VT)) &&
241            "Cannot autopromote this type, add it with AddPromotedToType.");
242     
243     MVT::ValueType NVT = VT;
244     do {
245       NVT = (MVT::ValueType)(NVT+1);
246       assert(MVT::isInteger(NVT) == MVT::isInteger(VT) && NVT != MVT::isVoid &&
247              "Didn't find type to promote to!");
248     } while (!isTypeLegal(NVT) ||
249               getOperationAction(Op, NVT) == Promote);
250     return NVT;
251   }
252
253   /// getValueType - Return the MVT::ValueType corresponding to this LLVM type.
254   /// This is fixed by the LLVM operations except for the pointer size.
255   MVT::ValueType getValueType(const Type *Ty) const {
256     switch (Ty->getTypeID()) {
257     default: assert(0 && "Unknown type!");
258     case Type::VoidTyID:    return MVT::isVoid;
259     case Type::BoolTyID:    return MVT::i1;
260     case Type::UByteTyID:
261     case Type::SByteTyID:   return MVT::i8;
262     case Type::ShortTyID:
263     case Type::UShortTyID:  return MVT::i16;
264     case Type::IntTyID:
265     case Type::UIntTyID:    return MVT::i32;
266     case Type::LongTyID:
267     case Type::ULongTyID:   return MVT::i64;
268     case Type::FloatTyID:   return MVT::f32;
269     case Type::DoubleTyID:  return MVT::f64;
270     case Type::PointerTyID: return PointerTy;
271     case Type::PackedTyID:  return MVT::Vector;
272     }
273   }
274
275   /// getNumElements - Return the number of registers that this ValueType will
276   /// eventually require.  This is always one for all non-integer types, is
277   /// one for any types promoted to live in larger registers, but may be more
278   /// than one for types (like i64) that are split into pieces.
279   unsigned getNumElements(MVT::ValueType VT) const {
280     return NumElementsForVT[VT];
281   }
282   
283   /// hasTargetDAGCombine - If true, the target has custom DAG combine
284   /// transformations that it can perform for the specified node.
285   bool hasTargetDAGCombine(ISD::NodeType NT) const {
286     return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
287   }
288
289   /// This function returns the maximum number of store operations permitted
290   /// to replace a call to llvm.memset. The value is set by the target at the
291   /// performance threshold for such a replacement.
292   /// @brief Get maximum # of store operations permitted for llvm.memset
293   unsigned getMaxStoresPerMemset() const { return maxStoresPerMemset; }
294
295   /// This function returns the maximum number of store operations permitted
296   /// to replace a call to llvm.memcpy. The value is set by the target at the
297   /// performance threshold for such a replacement.
298   /// @brief Get maximum # of store operations permitted for llvm.memcpy
299   unsigned getMaxStoresPerMemcpy() const { return maxStoresPerMemcpy; }
300
301   /// This function returns the maximum number of store operations permitted
302   /// to replace a call to llvm.memmove. The value is set by the target at the
303   /// performance threshold for such a replacement.
304   /// @brief Get maximum # of store operations permitted for llvm.memmove
305   unsigned getMaxStoresPerMemmove() const { return maxStoresPerMemmove; }
306
307   /// This function returns true if the target allows unaligned memory accesses.
308   /// This is used, for example, in situations where an array copy/move/set is 
309   /// converted to a sequence of store operations. It's use helps to ensure that
310   /// such replacements don't generate code that causes an alignment error 
311   /// (trap) on the target machine. 
312   /// @brief Determine if the target supports unaligned memory accesses.
313   bool allowsUnalignedMemoryAccesses() const {
314     return allowUnalignedMemoryAccesses;
315   }
316   
317   /// usesUnderscoreSetJmpLongJmp - Determine if we should use _setjmp or setjmp
318   /// to implement llvm.setjmp.
319   bool usesUnderscoreSetJmpLongJmp() const {
320     return UseUnderscoreSetJmpLongJmp;
321   }
322   
323   /// getStackPointerRegisterToSaveRestore - If a physical register, this
324   /// specifies the register that llvm.savestack/llvm.restorestack should save
325   /// and restore.
326   unsigned getStackPointerRegisterToSaveRestore() const {
327     return StackPointerRegisterToSaveRestore;
328   }
329
330   //===--------------------------------------------------------------------===//
331   // TargetLowering Optimization Methods
332   //
333   
334   /// TargetLoweringOpt - A convenience struct that encapsulates a DAG, and two
335   /// SDOperands for returning information from TargetLowering to its clients
336   /// that want to combine 
337   struct TargetLoweringOpt {
338     SelectionDAG &DAG;
339     SDOperand Old;
340     SDOperand New;
341
342     TargetLoweringOpt(SelectionDAG &InDAG) : DAG(InDAG) {}
343     
344     bool CombineTo(SDOperand O, SDOperand N) { 
345       Old = O; 
346       New = N; 
347       return true;
348     }
349     
350     /// ShrinkDemandedConstant - Check to see if the specified operand of the 
351     /// specified instruction is a constant integer.  If so, check to see if there
352     /// are any bits set in the constant that are not demanded.  If so, shrink the
353     /// constant and return true.
354     bool ShrinkDemandedConstant(SDOperand Op, uint64_t Demanded);
355   };
356                                                 
357   /// MaskedValueIsZero - Return true if 'Op & Mask' is known to be zero.  We
358   /// use this predicate to simplify operations downstream.  Op and Mask are
359   /// known to be the same type.
360   bool MaskedValueIsZero(SDOperand Op, uint64_t Mask, unsigned Depth = 0)
361     const;
362   
363   /// ComputeMaskedBits - Determine which of the bits specified in Mask are
364   /// known to be either zero or one and return them in the KnownZero/KnownOne
365   /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
366   /// processing.  Targets can implement the computeMaskedBitsForTargetNode 
367   /// method, to allow target nodes to be understood.
368   void ComputeMaskedBits(SDOperand Op, uint64_t Mask, uint64_t &KnownZero,
369                          uint64_t &KnownOne, unsigned Depth = 0) const;
370     
371   /// SimplifyDemandedBits - Look at Op.  At this point, we know that only the
372   /// DemandedMask bits of the result of Op are ever used downstream.  If we can
373   /// use this information to simplify Op, create a new simplified DAG node and
374   /// return true, returning the original and new nodes in Old and New. 
375   /// Otherwise, analyze the expression and return a mask of KnownOne and 
376   /// KnownZero bits for the expression (used to simplify the caller).  
377   /// The KnownZero/One bits may only be accurate for those bits in the 
378   /// DemandedMask.
379   bool SimplifyDemandedBits(SDOperand Op, uint64_t DemandedMask, 
380                             uint64_t &KnownZero, uint64_t &KnownOne,
381                             TargetLoweringOpt &TLO, unsigned Depth = 0) const;
382   
383   /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
384   /// Mask are known to be either zero or one and return them in the 
385   /// KnownZero/KnownOne bitsets.
386   virtual void computeMaskedBitsForTargetNode(const SDOperand Op,
387                                               uint64_t Mask,
388                                               uint64_t &KnownZero, 
389                                               uint64_t &KnownOne,
390                                               unsigned Depth = 0) const;
391
392   struct DAGCombinerInfo {
393     void *DC;  // The DAG Combiner object.
394     bool BeforeLegalize;
395   public:
396     SelectionDAG &DAG;
397     
398     DAGCombinerInfo(SelectionDAG &dag, bool bl, void *dc)
399       : DC(dc), BeforeLegalize(bl), DAG(dag) {}
400     
401     bool isBeforeLegalize() const { return BeforeLegalize; }
402     
403     void AddToWorklist(SDNode *N);
404     SDOperand CombineTo(SDNode *N, const std::vector<SDOperand> &To);
405     SDOperand CombineTo(SDNode *N, SDOperand Res);
406     SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1);
407   };
408
409   /// PerformDAGCombine - This method will be invoked for all target nodes and
410   /// for any target-independent nodes that the target has registered with
411   /// invoke it for.
412   ///
413   /// The semantics are as follows:
414   /// Return Value:
415   ///   SDOperand.Val == 0   - No change was made
416   ///   SDOperand.Val == N   - N was replaced, is dead, and is already handled.
417   ///   otherwise            - N should be replaced by the returned Operand.
418   ///
419   /// In addition, methods provided by DAGCombinerInfo may be used to perform
420   /// more complex transformations.
421   ///
422   virtual SDOperand PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
423   
424   //===--------------------------------------------------------------------===//
425   // TargetLowering Configuration Methods - These methods should be invoked by
426   // the derived class constructor to configure this object for the target.
427   //
428
429 protected:
430
431   /// setShiftAmountType - Describe the type that should be used for shift
432   /// amounts.  This type defaults to the pointer type.
433   void setShiftAmountType(MVT::ValueType VT) { ShiftAmountTy = VT; }
434
435   /// setSetCCResultType - Describe the type that shoudl be used as the result
436   /// of a setcc operation.  This defaults to the pointer type.
437   void setSetCCResultType(MVT::ValueType VT) { SetCCResultTy = VT; }
438
439   /// setSetCCResultContents - Specify how the target extends the result of a
440   /// setcc operation in a register.
441   void setSetCCResultContents(SetCCResultValue Ty) { SetCCResultContents = Ty; }
442
443   /// setSchedulingPreference - Specify the target scheduling preference.
444   void setSchedulingPreference(SchedPreference Pref) {
445     SchedPreferenceInfo = Pref;
446   }
447
448   /// setShiftAmountFlavor - Describe how the target handles out of range shift
449   /// amounts.
450   void setShiftAmountFlavor(OutOfRangeShiftAmount OORSA) {
451     ShiftAmtHandling = OORSA;
452   }
453
454   /// setUseUnderscoreSetJmpLongJmp - Indicate whether this target prefers to
455   /// use _setjmp and _longjmp to or implement llvm.setjmp/llvm.longjmp or
456   /// the non _ versions.  Defaults to false.
457   void setUseUnderscoreSetJmpLongJmp(bool Val) {
458     UseUnderscoreSetJmpLongJmp = Val;
459   }
460   
461   /// setStackPointerRegisterToSaveRestore - If set to a physical register, this
462   /// specifies the register that llvm.savestack/llvm.restorestack should save
463   /// and restore.
464   void setStackPointerRegisterToSaveRestore(unsigned R) {
465     StackPointerRegisterToSaveRestore = R;
466   }
467   
468   /// setSetCCIxExpensive - This is a short term hack for targets that codegen
469   /// setcc as a conditional branch.  This encourages the code generator to fold
470   /// setcc operations into other operations if possible.
471   void setSetCCIsExpensive() { SetCCIsExpensive = true; }
472
473   /// setIntDivIsCheap - Tells the code generator that integer divide is
474   /// expensive, and if possible, should be replaced by an alternate sequence
475   /// of instructions not containing an integer divide.
476   void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
477   
478   /// setPow2DivIsCheap - Tells the code generator that it shouldn't generate
479   /// srl/add/sra for a signed divide by power of two, and let the target handle
480   /// it.
481   void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
482   
483   /// addRegisterClass - Add the specified register class as an available
484   /// regclass for the specified value type.  This indicates the selector can
485   /// handle values of that class natively.
486   void addRegisterClass(MVT::ValueType VT, TargetRegisterClass *RC) {
487     AvailableRegClasses.push_back(std::make_pair(VT, RC));
488     RegClassForVT[VT] = RC;
489   }
490
491   /// computeRegisterProperties - Once all of the register classes are added,
492   /// this allows us to compute derived properties we expose.
493   void computeRegisterProperties();
494
495   /// setOperationAction - Indicate that the specified operation does not work
496   /// with the specified type and indicate what to do about it.
497   void setOperationAction(unsigned Op, MVT::ValueType VT,
498                           LegalizeAction Action) {
499     assert(VT < 32 && Op < sizeof(OpActions)/sizeof(OpActions[0]) &&
500            "Table isn't big enough!");
501     OpActions[Op] &= ~(3ULL << VT*2);
502     OpActions[Op] |= (uint64_t)Action << VT*2;
503   }
504   
505   /// AddPromotedToType - If Opc/OrigVT is specified as being promoted, the
506   /// promotion code defaults to trying a larger integer/fp until it can find
507   /// one that works.  If that default is insufficient, this method can be used
508   /// by the target to override the default.
509   void AddPromotedToType(unsigned Opc, MVT::ValueType OrigVT, 
510                          MVT::ValueType DestVT) {
511     PromoteToType[std::make_pair(Opc, OrigVT)] = DestVT;
512   }
513
514   /// addLegalFPImmediate - Indicate that this target can instruction select
515   /// the specified FP immediate natively.
516   void addLegalFPImmediate(double Imm) {
517     LegalFPImmediates.push_back(Imm);
518   }
519
520   /// setTargetDAGCombine - Targets should invoke this method for each target
521   /// independent node that they want to provide a custom DAG combiner for by
522   /// implementing the PerformDAGCombine virtual method.
523   void setTargetDAGCombine(ISD::NodeType NT) {
524     TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
525   }
526   
527 public:
528
529   //===--------------------------------------------------------------------===//
530   // Lowering methods - These methods must be implemented by targets so that
531   // the SelectionDAGLowering code knows how to lower these.
532   //
533
534   /// LowerArguments - This hook must be implemented to indicate how we should
535   /// lower the arguments for the specified function, into the specified DAG.
536   virtual std::vector<SDOperand>
537   LowerArguments(Function &F, SelectionDAG &DAG);
538
539   /// LowerCallTo - This hook lowers an abstract call to a function into an
540   /// actual call.  This returns a pair of operands.  The first element is the
541   /// return value for the function (if RetTy is not VoidTy).  The second
542   /// element is the outgoing token chain.
543   typedef std::vector<std::pair<SDOperand, const Type*> > ArgListTy;
544   virtual std::pair<SDOperand, SDOperand>
545   LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
546               unsigned CallingConv, bool isTailCall, SDOperand Callee,
547               ArgListTy &Args, SelectionDAG &DAG) = 0;
548
549   /// LowerFrameReturnAddress - This hook lowers a call to llvm.returnaddress or
550   /// llvm.frameaddress (depending on the value of the first argument).  The
551   /// return values are the result pointer and the resultant token chain.  If
552   /// not implemented, both of these intrinsics will return null.
553   virtual std::pair<SDOperand, SDOperand>
554   LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain, unsigned Depth,
555                           SelectionDAG &DAG);
556
557   /// LowerOperation - This callback is invoked for operations that are 
558   /// unsupported by the target, which are registered to use 'custom' lowering,
559   /// and whose defined values are all legal.
560   /// If the target has no operations that require custom lowering, it need not
561   /// implement this.  The default implementation of this aborts.
562   virtual SDOperand LowerOperation(SDOperand Op, SelectionDAG &DAG);
563
564   /// CustomPromoteOperation - This callback is invoked for operations that are
565   /// unsupported by the target, are registered to use 'custom' lowering, and
566   /// whose type needs to be promoted.
567   virtual SDOperand CustomPromoteOperation(SDOperand Op, SelectionDAG &DAG);
568   
569   /// getTargetNodeName() - This method returns the name of a target specific
570   /// DAG node.
571   virtual const char *getTargetNodeName(unsigned Opcode) const;
572
573   //===--------------------------------------------------------------------===//
574   // Inline Asm Support hooks
575   //
576   
577   enum ConstraintType {
578     C_Register,            // Constraint represents a single register.
579     C_RegisterClass,       // Constraint represents one or more registers.
580     C_Memory,              // Memory constraint.
581     C_Other,               // Something else.
582     C_Unknown              // Unsupported constraint.
583   };
584   
585   /// getConstraintType - Given a constraint letter, return the type of
586   /// constraint it is for this target.
587   virtual ConstraintType getConstraintType(char ConstraintLetter) const;
588   
589   
590   /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
591   /// return a list of registers that can be used to satisfy the constraint.
592   /// This should only be used for C_RegisterClass constraints.
593   virtual std::vector<unsigned> 
594   getRegClassForInlineAsmConstraint(const std::string &Constraint,
595                                     MVT::ValueType VT) const;
596
597   /// getRegForInlineAsmConstraint - Given a physical register constraint (e.g.
598   /// {edx}), return the register number and the register class for the
599   /// register.  This should only be used for C_Register constraints.  On error,
600   /// this returns a register number of 0.
601   virtual std::pair<unsigned, const TargetRegisterClass*> 
602     getRegForInlineAsmConstraint(const std::string &Constraint,
603                                  MVT::ValueType VT) const;
604   
605   
606   /// isOperandValidForConstraint - Return true if the specified SDOperand is
607   /// valid for the specified target constraint letter.
608   virtual bool isOperandValidForConstraint(SDOperand Op, char ConstraintLetter);
609   
610   //===--------------------------------------------------------------------===//
611   // Scheduler hooks
612   //
613   
614   // InsertAtEndOfBasicBlock - This method should be implemented by targets that
615   // mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
616   // instructions are special in various ways, which require special support to
617   // insert.  The specified MachineInstr is created but not inserted into any
618   // basic blocks, and the scheduler passes ownership of it to this method.
619   virtual MachineBasicBlock *InsertAtEndOfBasicBlock(MachineInstr *MI,
620                                                      MachineBasicBlock *MBB);
621
622   //===--------------------------------------------------------------------===//
623   // Loop Strength Reduction hooks
624   //
625   
626   /// isLegalAddressImmediate - Return true if the integer value or GlobalValue
627   /// can be used as the offset of the target addressing mode.
628   virtual bool isLegalAddressImmediate(int64_t V) const;
629   virtual bool isLegalAddressImmediate(GlobalValue *GV) const;
630
631   typedef std::vector<unsigned>::const_iterator legal_am_scale_iterator;
632   legal_am_scale_iterator legal_am_scale_begin() const {
633     return LegalAddressScales.begin();
634   }
635   legal_am_scale_iterator legal_am_scale_end() const {
636     return LegalAddressScales.end();
637   }
638
639 protected:
640   /// addLegalAddressScale - Add a integer (> 1) value which can be used as
641   /// scale in the target addressing mode. Note: the ordering matters so the
642   /// least efficient ones should be entered first.
643   void addLegalAddressScale(unsigned Scale) {
644     LegalAddressScales.push_back(Scale);
645   }
646
647 private:
648   std::vector<unsigned> LegalAddressScales;
649   
650   TargetMachine &TM;
651   const TargetData *TD;
652
653   /// IsLittleEndian - True if this is a little endian target.
654   ///
655   bool IsLittleEndian;
656
657   /// PointerTy - The type to use for pointers, usually i32 or i64.
658   ///
659   MVT::ValueType PointerTy;
660
661   /// ShiftAmountTy - The type to use for shift amounts, usually i8 or whatever
662   /// PointerTy is.
663   MVT::ValueType ShiftAmountTy;
664
665   OutOfRangeShiftAmount ShiftAmtHandling;
666
667   /// SetCCIsExpensive - This is a short term hack for targets that codegen
668   /// setcc as a conditional branch.  This encourages the code generator to fold
669   /// setcc operations into other operations if possible.
670   bool SetCCIsExpensive;
671
672   /// IntDivIsCheap - Tells the code generator not to expand integer divides by
673   /// constants into a sequence of muls, adds, and shifts.  This is a hack until
674   /// a real cost model is in place.  If we ever optimize for size, this will be
675   /// set to true unconditionally.
676   bool IntDivIsCheap;
677   
678   /// Pow2DivIsCheap - Tells the code generator that it shouldn't generate
679   /// srl/add/sra for a signed divide by power of two, and let the target handle
680   /// it.
681   bool Pow2DivIsCheap;
682   
683   /// SetCCResultTy - The type that SetCC operations use.  This defaults to the
684   /// PointerTy.
685   MVT::ValueType SetCCResultTy;
686
687   /// SetCCResultContents - Information about the contents of the high-bits in
688   /// the result of a setcc comparison operation.
689   SetCCResultValue SetCCResultContents;
690
691   /// SchedPreferenceInfo - The target scheduling preference: shortest possible
692   /// total cycles or lowest register usage.
693   SchedPreference SchedPreferenceInfo;
694   
695   /// UseUnderscoreSetJmpLongJmp - This target prefers to use _setjmp and
696   /// _longjmp to implement llvm.setjmp/llvm.longjmp.  Defaults to false.
697   bool UseUnderscoreSetJmpLongJmp;
698   
699   /// StackPointerRegisterToSaveRestore - If set to a physical register, this
700   /// specifies the register that llvm.savestack/llvm.restorestack should save
701   /// and restore.
702   unsigned StackPointerRegisterToSaveRestore;
703
704   /// RegClassForVT - This indicates the default register class to use for
705   /// each ValueType the target supports natively.
706   TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
707   unsigned char NumElementsForVT[MVT::LAST_VALUETYPE];
708
709   /// TransformToType - For any value types we are promoting or expanding, this
710   /// contains the value type that we are changing to.  For Expanded types, this
711   /// contains one step of the expand (e.g. i64 -> i32), even if there are
712   /// multiple steps required (e.g. i64 -> i16).  For types natively supported
713   /// by the system, this holds the same type (e.g. i32 -> i32).
714   MVT::ValueType TransformToType[MVT::LAST_VALUETYPE];
715
716   /// OpActions - For each operation and each value type, keep a LegalizeAction
717   /// that indicates how instruction selection should deal with the operation.
718   /// Most operations are Legal (aka, supported natively by the target), but
719   /// operations that are not should be described.  Note that operations on
720   /// non-legal value types are not described here.
721   uint64_t OpActions[156];
722   
723   ValueTypeActionImpl ValueTypeActions;
724
725   std::vector<double> LegalFPImmediates;
726
727   std::vector<std::pair<MVT::ValueType,
728                         TargetRegisterClass*> > AvailableRegClasses;
729
730   /// TargetDAGCombineArray - Targets can specify ISD nodes that they would
731   /// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(),
732   /// which sets a bit in this array.
733   unsigned char TargetDAGCombineArray[156/(sizeof(unsigned char)*8)];
734   
735   /// PromoteToType - For operations that must be promoted to a specific type,
736   /// this holds the destination type.  This map should be sparse, so don't hold
737   /// it as an array.
738   ///
739   /// Targets add entries to this map with AddPromotedToType(..), clients access
740   /// this with getTypeToPromoteTo(..).
741   std::map<std::pair<unsigned, MVT::ValueType>, MVT::ValueType> PromoteToType;
742   
743 protected:
744   /// When lowering %llvm.memset this field specifies the maximum number of
745   /// store operations that may be substituted for the call to memset. Targets
746   /// must set this value based on the cost threshold for that target. Targets
747   /// should assume that the memset will be done using as many of the largest
748   /// store operations first, followed by smaller ones, if necessary, per
749   /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
750   /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
751   /// store.  This only applies to setting a constant array of a constant size.
752   /// @brief Specify maximum number of store instructions per memset call.
753   unsigned maxStoresPerMemset;
754
755   /// When lowering %llvm.memcpy this field specifies the maximum number of
756   /// store operations that may be substituted for a call to memcpy. Targets
757   /// must set this value based on the cost threshold for that target. Targets
758   /// should assume that the memcpy will be done using as many of the largest
759   /// store operations first, followed by smaller ones, if necessary, per
760   /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
761   /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
762   /// and one 1-byte store. This only applies to copying a constant array of
763   /// constant size.
764   /// @brief Specify maximum bytes of store instructions per memcpy call.
765   unsigned maxStoresPerMemcpy;
766
767   /// When lowering %llvm.memmove this field specifies the maximum number of
768   /// store instructions that may be substituted for a call to memmove. Targets
769   /// must set this value based on the cost threshold for that target. Targets
770   /// should assume that the memmove will be done using as many of the largest
771   /// store operations first, followed by smaller ones, if necessary, per
772   /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
773   /// with 8-bit alignment would result in nine 1-byte stores.  This only
774   /// applies to copying a constant array of constant size.
775   /// @brief Specify maximum bytes of store instructions per memmove call.
776   unsigned maxStoresPerMemmove;
777
778   /// This field specifies whether the target machine permits unaligned memory
779   /// accesses.  This is used, for example, to determine the size of store 
780   /// operations when copying small arrays and other similar tasks.
781   /// @brief Indicate whether the target permits unaligned memory accesses.
782   bool allowUnalignedMemoryAccesses;
783 };
784 } // end llvm namespace
785
786 #endif