- Remove isSetCCExpensive() etc. These are no longer used.
[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   /// usesGlobalOffsetTable - Return true if this target uses a GOT for PIC
89   /// codegen.
90   bool usesGlobalOffsetTable() const { return UsesGlobalOffsetTable; }
91   
92   /// isSelectExpensive - Return true if the select operation is expensive for
93   /// this target.
94   bool isSelectExpensive() const { return SelectIsExpensive; }
95   
96   /// isIntDivCheap() - Return true if integer divide is usually cheaper than
97   /// a sequence of several shifts, adds, and multiplies for this target.
98   bool isIntDivCheap() const { return IntDivIsCheap; }
99
100   /// isPow2DivCheap() - Return true if pow2 div is cheaper than a chain of
101   /// srl/add/sra.
102   bool isPow2DivCheap() const { return Pow2DivIsCheap; }
103   
104   /// getSetCCResultTy - Return the ValueType of the result of setcc operations.
105   ///
106   MVT::ValueType getSetCCResultTy() const { return SetCCResultTy; }
107
108   /// getSetCCResultContents - For targets without boolean registers, this flag
109   /// returns information about the contents of the high-bits in the setcc
110   /// result register.
111   SetCCResultValue getSetCCResultContents() const { return SetCCResultContents;}
112
113   /// getSchedulingPreference - Return target scheduling preference.
114   SchedPreference getSchedulingPreference() const {
115     return SchedPreferenceInfo;
116   }
117
118   /// getRegClassFor - Return the register class that should be used for the
119   /// specified value type.  This may only be called on legal types.
120   TargetRegisterClass *getRegClassFor(MVT::ValueType VT) const {
121     TargetRegisterClass *RC = RegClassForVT[VT];
122     assert(RC && "This value type is not natively supported!");
123     return RC;
124   }
125   
126   /// isTypeLegal - Return true if the target has native support for the
127   /// specified value type.  This means that it has a register that directly
128   /// holds it without promotions or expansions.
129   bool isTypeLegal(MVT::ValueType VT) const {
130     return RegClassForVT[VT] != 0;
131   }
132
133   class ValueTypeActionImpl {
134     /// ValueTypeActions - This is a bitvector that contains two bits for each
135     /// value type, where the two bits correspond to the LegalizeAction enum.
136     /// This can be queried with "getTypeAction(VT)".
137     uint32_t ValueTypeActions[2];
138   public:
139     ValueTypeActionImpl() {
140       ValueTypeActions[0] = ValueTypeActions[1] = 0;
141     }
142     ValueTypeActionImpl(const ValueTypeActionImpl &RHS) {
143       ValueTypeActions[0] = RHS.ValueTypeActions[0];
144       ValueTypeActions[1] = RHS.ValueTypeActions[1];
145     }
146     
147     LegalizeAction getTypeAction(MVT::ValueType VT) const {
148       return (LegalizeAction)((ValueTypeActions[VT>>4] >> ((2*VT) & 31)) & 3);
149     }
150     void setTypeAction(MVT::ValueType VT, LegalizeAction Action) {
151       assert(unsigned(VT >> 4) < 
152              sizeof(ValueTypeActions)/sizeof(ValueTypeActions[0]));
153       ValueTypeActions[VT>>4] |= Action << ((VT*2) & 31);
154     }
155   };
156   
157   const ValueTypeActionImpl &getValueTypeActions() const {
158     return ValueTypeActions;
159   }
160   
161   /// getTypeAction - Return how we should legalize values of this type, either
162   /// it is already legal (return 'Legal') or we need to promote it to a larger
163   /// type (return 'Promote'), or we need to expand it into multiple registers
164   /// of smaller integer type (return 'Expand').  'Custom' is not an option.
165   LegalizeAction getTypeAction(MVT::ValueType VT) const {
166     return ValueTypeActions.getTypeAction(VT);
167   }
168
169   /// getTypeToTransformTo - For types supported by the target, this is an
170   /// identity function.  For types that must be promoted to larger types, this
171   /// returns the larger type to promote to.  For integer types that are larger
172   /// than the largest integer register, this contains one step in the expansion
173   /// to get to the smaller register. For illegal floating point types, this
174   /// returns the integer type to transform to.
175   MVT::ValueType getTypeToTransformTo(MVT::ValueType VT) const {
176     return TransformToType[VT];
177   }
178   
179   /// getTypeToExpandTo - For types supported by the target, this is an
180   /// identity function.  For types that must be expanded (i.e. integer types
181   /// that are larger than the largest integer register or illegal floating
182   /// point types), this returns the largest legal type it will be expanded to.
183   MVT::ValueType getTypeToExpandTo(MVT::ValueType VT) const {
184     while (true) {
185       switch (getTypeAction(VT)) {
186       case Legal:
187         return VT;
188       case Expand:
189         VT = TransformToType[VT];
190         break;
191       default:
192         assert(false && "Type is not legal nor is it to be expanded!");
193         return VT;
194       }
195     }
196     return VT;
197   }
198
199   /// getPackedTypeBreakdown - Packed types are broken down into some number of
200   /// legal first class types.  For example, <8 x float> maps to 2 MVT::v4f32
201   /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
202   /// Similarly, <2 x long> turns into 4 MVT::i32 values with both PPC and X86.
203   ///
204   /// This method returns the number of registers needed, and the VT for each
205   /// register.  It also returns the VT of the PackedType elements before they
206   /// are promoted/expanded.
207   ///
208   unsigned getPackedTypeBreakdown(const PackedType *PTy, 
209                                   MVT::ValueType &PTyElementVT,
210                                   MVT::ValueType &PTyLegalElementVT) const;
211   
212   typedef std::vector<double>::const_iterator legal_fpimm_iterator;
213   legal_fpimm_iterator legal_fpimm_begin() const {
214     return LegalFPImmediates.begin();
215   }
216   legal_fpimm_iterator legal_fpimm_end() const {
217     return LegalFPImmediates.end();
218   }
219   
220   /// isShuffleMaskLegal - Targets can use this to indicate that they only
221   /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
222   /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
223   /// are assumed to be legal.
224   virtual bool isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
225     return true;
226   }
227
228   /// isVectorClearMaskLegal - Similar to isShuffleMaskLegal. This is
229   /// used by Targets can use this to indicate if there is a suitable
230   /// VECTOR_SHUFFLE that can be used to replace a VAND with a constant
231   /// pool entry.
232   virtual bool isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
233                                       MVT::ValueType EVT,
234                                       SelectionDAG &DAG) const {
235     return false;
236   }
237
238   /// getOperationAction - Return how this operation should be treated: either
239   /// it is legal, needs to be promoted to a larger size, needs to be
240   /// expanded to some other code sequence, or the target has a custom expander
241   /// for it.
242   LegalizeAction getOperationAction(unsigned Op, MVT::ValueType VT) const {
243     return (LegalizeAction)((OpActions[Op] >> (2*VT)) & 3);
244   }
245   
246   /// isOperationLegal - Return true if the specified operation is legal on this
247   /// target.
248   bool isOperationLegal(unsigned Op, MVT::ValueType VT) const {
249     return getOperationAction(Op, VT) == Legal ||
250            getOperationAction(Op, VT) == Custom;
251   }
252   
253   /// getLoadXAction - Return how this load with extension should be treated:
254   /// either it is legal, needs to be promoted to a larger size, needs to be
255   /// expanded to some other code sequence, or the target has a custom expander
256   /// for it.
257   LegalizeAction getLoadXAction(unsigned LType, MVT::ValueType VT) const {
258     return (LegalizeAction)((LoadXActions[LType] >> (2*VT)) & 3);
259   }
260   
261   /// isLoadXLegal - Return true if the specified load with extension is legal
262   /// on this target.
263   bool isLoadXLegal(unsigned LType, MVT::ValueType VT) const {
264     return getLoadXAction(LType, VT) == Legal ||
265            getLoadXAction(LType, VT) == Custom;
266   }
267   
268   /// getStoreXAction - Return how this store with truncation should be treated:
269   /// either it is legal, needs to be promoted to a larger size, needs to be
270   /// expanded to some other code sequence, or the target has a custom expander
271   /// for it.
272   LegalizeAction getStoreXAction(MVT::ValueType VT) const {
273     return (LegalizeAction)((StoreXActions >> (2*VT)) & 3);
274   }
275   
276   /// isStoreXLegal - Return true if the specified store with truncation is
277   /// legal on this target.
278   bool isStoreXLegal(MVT::ValueType VT) const {
279     return getStoreXAction(VT) == Legal || getStoreXAction(VT) == Custom;
280   }
281
282   /// getIndexedLoadAction - Return how the indexed load should be treated:
283   /// either it is legal, needs to be promoted to a larger size, needs to be
284   /// expanded to some other code sequence, or the target has a custom expander
285   /// for it.
286   LegalizeAction
287   getIndexedLoadAction(unsigned IdxMode, MVT::ValueType VT) const {
288     return (LegalizeAction)((IndexedModeActions[0][IdxMode] >> (2*VT)) & 3);
289   }
290
291   /// isIndexedLoadLegal - Return true if the specified indexed load is legal
292   /// on this target.
293   bool isIndexedLoadLegal(unsigned IdxMode, MVT::ValueType VT) const {
294     return getIndexedLoadAction(IdxMode, VT) == Legal ||
295            getIndexedLoadAction(IdxMode, VT) == Custom;
296   }
297   
298   /// getIndexedStoreAction - Return how the indexed store should be treated:
299   /// either it is legal, needs to be promoted to a larger size, needs to be
300   /// expanded to some other code sequence, or the target has a custom expander
301   /// for it.
302   LegalizeAction
303   getIndexedStoreAction(unsigned IdxMode, MVT::ValueType VT) const {
304     return (LegalizeAction)((IndexedModeActions[1][IdxMode] >> (2*VT)) & 3);
305   }  
306   
307   /// isIndexedStoreLegal - Return true if the specified indexed load is legal
308   /// on this target.
309   bool isIndexedStoreLegal(unsigned IdxMode, MVT::ValueType VT) const {
310     return getIndexedStoreAction(IdxMode, VT) == Legal ||
311            getIndexedStoreAction(IdxMode, VT) == Custom;
312   }
313   
314   /// getTypeToPromoteTo - If the action for this operation is to promote, this
315   /// method returns the ValueType to promote to.
316   MVT::ValueType getTypeToPromoteTo(unsigned Op, MVT::ValueType VT) const {
317     assert(getOperationAction(Op, VT) == Promote &&
318            "This operation isn't promoted!");
319
320     // See if this has an explicit type specified.
321     std::map<std::pair<unsigned, MVT::ValueType>, 
322              MVT::ValueType>::const_iterator PTTI =
323       PromoteToType.find(std::make_pair(Op, VT));
324     if (PTTI != PromoteToType.end()) return PTTI->second;
325     
326     assert((MVT::isInteger(VT) || MVT::isFloatingPoint(VT)) &&
327            "Cannot autopromote this type, add it with AddPromotedToType.");
328     
329     MVT::ValueType NVT = VT;
330     do {
331       NVT = (MVT::ValueType)(NVT+1);
332       assert(MVT::isInteger(NVT) == MVT::isInteger(VT) && NVT != MVT::isVoid &&
333              "Didn't find type to promote to!");
334     } while (!isTypeLegal(NVT) ||
335               getOperationAction(Op, NVT) == Promote);
336     return NVT;
337   }
338
339   /// getValueType - Return the MVT::ValueType corresponding to this LLVM type.
340   /// This is fixed by the LLVM operations except for the pointer size.
341   MVT::ValueType getValueType(const Type *Ty) const {
342     switch (Ty->getTypeID()) {
343     default: assert(0 && "Unknown type!");
344     case Type::VoidTyID:    return MVT::isVoid;
345     case Type::BoolTyID:    return MVT::i1;
346     case Type::Int8TyID:    return MVT::i8;
347     case Type::Int16TyID:   return MVT::i16;
348     case Type::Int32TyID:   return MVT::i32;
349     case Type::Int64TyID:   return MVT::i64;
350     case Type::FloatTyID:   return MVT::f32;
351     case Type::DoubleTyID:  return MVT::f64;
352     case Type::PointerTyID: return PointerTy;
353     case Type::PackedTyID:  return MVT::Vector;
354     }
355   }
356
357   /// getNumElements - Return the number of registers that this ValueType will
358   /// eventually require.  This is one for any types promoted to live in larger
359   /// registers, but may be more than one for types (like i64) that are split
360   /// into pieces.
361   unsigned getNumElements(MVT::ValueType VT) const {
362     return NumElementsForVT[VT];
363   }
364   
365   /// hasTargetDAGCombine - If true, the target has custom DAG combine
366   /// transformations that it can perform for the specified node.
367   bool hasTargetDAGCombine(ISD::NodeType NT) const {
368     return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
369   }
370
371   /// This function returns the maximum number of store operations permitted
372   /// to replace a call to llvm.memset. The value is set by the target at the
373   /// performance threshold for such a replacement.
374   /// @brief Get maximum # of store operations permitted for llvm.memset
375   unsigned getMaxStoresPerMemset() const { return maxStoresPerMemset; }
376
377   /// This function returns the maximum number of store operations permitted
378   /// to replace a call to llvm.memcpy. The value is set by the target at the
379   /// performance threshold for such a replacement.
380   /// @brief Get maximum # of store operations permitted for llvm.memcpy
381   unsigned getMaxStoresPerMemcpy() const { return maxStoresPerMemcpy; }
382
383   /// This function returns the maximum number of store operations permitted
384   /// to replace a call to llvm.memmove. The value is set by the target at the
385   /// performance threshold for such a replacement.
386   /// @brief Get maximum # of store operations permitted for llvm.memmove
387   unsigned getMaxStoresPerMemmove() const { return maxStoresPerMemmove; }
388
389   /// This function returns true if the target allows unaligned memory accesses.
390   /// This is used, for example, in situations where an array copy/move/set is 
391   /// converted to a sequence of store operations. It's use helps to ensure that
392   /// such replacements don't generate code that causes an alignment error 
393   /// (trap) on the target machine. 
394   /// @brief Determine if the target supports unaligned memory accesses.
395   bool allowsUnalignedMemoryAccesses() const {
396     return allowUnalignedMemoryAccesses;
397   }
398   
399   /// usesUnderscoreSetJmp - Determine if we should use _setjmp or setjmp
400   /// to implement llvm.setjmp.
401   bool usesUnderscoreSetJmp() const {
402     return UseUnderscoreSetJmp;
403   }
404
405   /// usesUnderscoreLongJmp - Determine if we should use _longjmp or longjmp
406   /// to implement llvm.longjmp.
407   bool usesUnderscoreLongJmp() const {
408     return UseUnderscoreLongJmp;
409   }
410
411   /// getStackPointerRegisterToSaveRestore - If a physical register, this
412   /// specifies the register that llvm.savestack/llvm.restorestack should save
413   /// and restore.
414   unsigned getStackPointerRegisterToSaveRestore() const {
415     return StackPointerRegisterToSaveRestore;
416   }
417
418   /// getJumpBufSize - returns the target's jmp_buf size in bytes (if never
419   /// set, the default is 200)
420   unsigned getJumpBufSize() const {
421     return JumpBufSize;
422   }
423
424   /// getJumpBufAlignment - returns the target's jmp_buf alignment in bytes
425   /// (if never set, the default is 0)
426   unsigned getJumpBufAlignment() const {
427     return JumpBufAlignment;
428   }
429
430   /// getPreIndexedAddressParts - returns true by value, base pointer and
431   /// offset pointer and addressing mode by reference if the node's address
432   /// can be legally represented as pre-indexed load / store address.
433   virtual bool getPreIndexedAddressParts(SDNode *N, SDOperand &Base,
434                                          SDOperand &Offset,
435                                          ISD::MemIndexedMode &AM,
436                                          SelectionDAG &DAG) {
437     return false;
438   }
439   
440   /// getPostIndexedAddressParts - returns true by value, base pointer and
441   /// offset pointer and addressing mode by reference if this node can be
442   /// combined with a load / store to form a post-indexed load / store.
443   virtual bool getPostIndexedAddressParts(SDNode *N, SDNode *Op,
444                                           SDOperand &Base, SDOperand &Offset,
445                                           ISD::MemIndexedMode &AM,
446                                           SelectionDAG &DAG) {
447     return false;
448   }
449   
450   //===--------------------------------------------------------------------===//
451   // TargetLowering Optimization Methods
452   //
453   
454   /// TargetLoweringOpt - A convenience struct that encapsulates a DAG, and two
455   /// SDOperands for returning information from TargetLowering to its clients
456   /// that want to combine 
457   struct TargetLoweringOpt {
458     SelectionDAG &DAG;
459     SDOperand Old;
460     SDOperand New;
461
462     TargetLoweringOpt(SelectionDAG &InDAG) : DAG(InDAG) {}
463     
464     bool CombineTo(SDOperand O, SDOperand N) { 
465       Old = O; 
466       New = N; 
467       return true;
468     }
469     
470     /// ShrinkDemandedConstant - Check to see if the specified operand of the 
471     /// specified instruction is a constant integer.  If so, check to see if there
472     /// are any bits set in the constant that are not demanded.  If so, shrink the
473     /// constant and return true.
474     bool ShrinkDemandedConstant(SDOperand Op, uint64_t Demanded);
475   };
476                                                 
477   /// MaskedValueIsZero - Return true if 'Op & Mask' is known to be zero.  We
478   /// use this predicate to simplify operations downstream.  Op and Mask are
479   /// known to be the same type.
480   bool MaskedValueIsZero(SDOperand Op, uint64_t Mask, unsigned Depth = 0)
481     const;
482   
483   /// ComputeMaskedBits - Determine which of the bits specified in Mask are
484   /// known to be either zero or one and return them in the KnownZero/KnownOne
485   /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
486   /// processing.  Targets can implement the computeMaskedBitsForTargetNode 
487   /// method, to allow target nodes to be understood.
488   void ComputeMaskedBits(SDOperand Op, uint64_t Mask, uint64_t &KnownZero,
489                          uint64_t &KnownOne, unsigned Depth = 0) const;
490     
491   /// SimplifyDemandedBits - Look at Op.  At this point, we know that only the
492   /// DemandedMask bits of the result of Op are ever used downstream.  If we can
493   /// use this information to simplify Op, create a new simplified DAG node and
494   /// return true, returning the original and new nodes in Old and New. 
495   /// Otherwise, analyze the expression and return a mask of KnownOne and 
496   /// KnownZero bits for the expression (used to simplify the caller).  
497   /// The KnownZero/One bits may only be accurate for those bits in the 
498   /// DemandedMask.
499   bool SimplifyDemandedBits(SDOperand Op, uint64_t DemandedMask, 
500                             uint64_t &KnownZero, uint64_t &KnownOne,
501                             TargetLoweringOpt &TLO, unsigned Depth = 0) const;
502   
503   /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
504   /// Mask are known to be either zero or one and return them in the 
505   /// KnownZero/KnownOne bitsets.
506   virtual void computeMaskedBitsForTargetNode(const SDOperand Op,
507                                               uint64_t Mask,
508                                               uint64_t &KnownZero, 
509                                               uint64_t &KnownOne,
510                                               unsigned Depth = 0) const;
511
512   /// ComputeNumSignBits - Return the number of times the sign bit of the
513   /// register is replicated into the other bits.  We know that at least 1 bit
514   /// is always equal to the sign bit (itself), but other cases can give us
515   /// information.  For example, immediately after an "SRA X, 2", we know that
516   /// the top 3 bits are all equal to each other, so we return 3.
517   unsigned ComputeNumSignBits(SDOperand Op, unsigned Depth = 0) const;
518   
519   /// ComputeNumSignBitsForTargetNode - This method can be implemented by
520   /// targets that want to expose additional information about sign bits to the
521   /// DAG Combiner.
522   virtual unsigned ComputeNumSignBitsForTargetNode(SDOperand Op,
523                                                    unsigned Depth = 0) const;
524   
525   struct DAGCombinerInfo {
526     void *DC;  // The DAG Combiner object.
527     bool BeforeLegalize;
528   public:
529     SelectionDAG &DAG;
530     
531     DAGCombinerInfo(SelectionDAG &dag, bool bl, void *dc)
532       : DC(dc), BeforeLegalize(bl), DAG(dag) {}
533     
534     bool isBeforeLegalize() const { return BeforeLegalize; }
535     
536     void AddToWorklist(SDNode *N);
537     SDOperand CombineTo(SDNode *N, const std::vector<SDOperand> &To);
538     SDOperand CombineTo(SDNode *N, SDOperand Res);
539     SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1);
540   };
541
542   /// PerformDAGCombine - This method will be invoked for all target nodes and
543   /// for any target-independent nodes that the target has registered with
544   /// invoke it for.
545   ///
546   /// The semantics are as follows:
547   /// Return Value:
548   ///   SDOperand.Val == 0   - No change was made
549   ///   SDOperand.Val == N   - N was replaced, is dead, and is already handled.
550   ///   otherwise            - N should be replaced by the returned Operand.
551   ///
552   /// In addition, methods provided by DAGCombinerInfo may be used to perform
553   /// more complex transformations.
554   ///
555   virtual SDOperand PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
556   
557   //===--------------------------------------------------------------------===//
558   // TargetLowering Configuration Methods - These methods should be invoked by
559   // the derived class constructor to configure this object for the target.
560   //
561
562 protected:
563   /// setUsesGlobalOffsetTable - Specify that this target does or doesn't use a
564   /// GOT for PC-relative code.
565   void setUsesGlobalOffsetTable(bool V) { UsesGlobalOffsetTable = V; }
566
567   /// setShiftAmountType - Describe the type that should be used for shift
568   /// amounts.  This type defaults to the pointer type.
569   void setShiftAmountType(MVT::ValueType VT) { ShiftAmountTy = VT; }
570
571   /// setSetCCResultType - Describe the type that shoudl be used as the result
572   /// of a setcc operation.  This defaults to the pointer type.
573   void setSetCCResultType(MVT::ValueType VT) { SetCCResultTy = VT; }
574
575   /// setSetCCResultContents - Specify how the target extends the result of a
576   /// setcc operation in a register.
577   void setSetCCResultContents(SetCCResultValue Ty) { SetCCResultContents = Ty; }
578
579   /// setSchedulingPreference - Specify the target scheduling preference.
580   void setSchedulingPreference(SchedPreference Pref) {
581     SchedPreferenceInfo = Pref;
582   }
583
584   /// setShiftAmountFlavor - Describe how the target handles out of range shift
585   /// amounts.
586   void setShiftAmountFlavor(OutOfRangeShiftAmount OORSA) {
587     ShiftAmtHandling = OORSA;
588   }
589
590   /// setUseUnderscoreSetJmp - Indicate whether this target prefers to
591   /// use _setjmp to implement llvm.setjmp or the non _ version.
592   /// Defaults to false.
593   void setUseUnderscoreSetJmp(bool Val) {
594     UseUnderscoreSetJmp = Val;
595   }
596
597   /// setUseUnderscoreLongJmp - Indicate whether this target prefers to
598   /// use _longjmp to implement llvm.longjmp or the non _ version.
599   /// Defaults to false.
600   void setUseUnderscoreLongJmp(bool Val) {
601     UseUnderscoreLongJmp = Val;
602   }
603
604   /// setStackPointerRegisterToSaveRestore - If set to a physical register, this
605   /// specifies the register that llvm.savestack/llvm.restorestack should save
606   /// and restore.
607   void setStackPointerRegisterToSaveRestore(unsigned R) {
608     StackPointerRegisterToSaveRestore = R;
609   }
610   
611   /// SelectIsExpensive - Tells the code generator not to expand operations
612   /// into sequences that use the select operations if possible.
613   void setSelectIsExpensive() { SelectIsExpensive = true; }
614
615   /// setIntDivIsCheap - Tells the code generator that integer divide is
616   /// expensive, and if possible, should be replaced by an alternate sequence
617   /// of instructions not containing an integer divide.
618   void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
619   
620   /// setPow2DivIsCheap - Tells the code generator that it shouldn't generate
621   /// srl/add/sra for a signed divide by power of two, and let the target handle
622   /// it.
623   void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
624   
625   /// addRegisterClass - Add the specified register class as an available
626   /// regclass for the specified value type.  This indicates the selector can
627   /// handle values of that class natively.
628   void addRegisterClass(MVT::ValueType VT, TargetRegisterClass *RC) {
629     AvailableRegClasses.push_back(std::make_pair(VT, RC));
630     RegClassForVT[VT] = RC;
631   }
632
633   /// computeRegisterProperties - Once all of the register classes are added,
634   /// this allows us to compute derived properties we expose.
635   void computeRegisterProperties();
636
637   /// setOperationAction - Indicate that the specified operation does not work
638   /// with the specified type and indicate what to do about it.
639   void setOperationAction(unsigned Op, MVT::ValueType VT,
640                           LegalizeAction Action) {
641     assert(VT < 32 && Op < sizeof(OpActions)/sizeof(OpActions[0]) &&
642            "Table isn't big enough!");
643     OpActions[Op] &= ~(uint64_t(3UL) << VT*2);
644     OpActions[Op] |= (uint64_t)Action << VT*2;
645   }
646   
647   /// setLoadXAction - Indicate that the specified load with extension does not
648   /// work with the with specified type and indicate what to do about it.
649   void setLoadXAction(unsigned ExtType, MVT::ValueType VT,
650                       LegalizeAction Action) {
651     assert(VT < 32 && ExtType < sizeof(LoadXActions)/sizeof(LoadXActions[0]) &&
652            "Table isn't big enough!");
653     LoadXActions[ExtType] &= ~(uint64_t(3UL) << VT*2);
654     LoadXActions[ExtType] |= (uint64_t)Action << VT*2;
655   }
656   
657   /// setStoreXAction - Indicate that the specified store with truncation does
658   /// not work with the with specified type and indicate what to do about it.
659   void setStoreXAction(MVT::ValueType VT, LegalizeAction Action) {
660     assert(VT < 32 && "Table isn't big enough!");
661     StoreXActions &= ~(uint64_t(3UL) << VT*2);
662     StoreXActions |= (uint64_t)Action << VT*2;
663   }
664
665   /// setIndexedLoadAction - Indicate that the specified indexed load does or
666   /// does not work with the with specified type and indicate what to do abort
667   /// it. NOTE: All indexed mode loads are initialized to Expand in
668   /// TargetLowering.cpp
669   void setIndexedLoadAction(unsigned IdxMode, MVT::ValueType VT,
670                             LegalizeAction Action) {
671     assert(VT < 32 && IdxMode <
672            sizeof(IndexedModeActions[0]) / sizeof(IndexedModeActions[0][0]) &&
673            "Table isn't big enough!");
674     IndexedModeActions[0][IdxMode] &= ~(uint64_t(3UL) << VT*2);
675     IndexedModeActions[0][IdxMode] |= (uint64_t)Action << VT*2;
676   }
677   
678   /// setIndexedStoreAction - Indicate that the specified indexed store does or
679   /// does not work with the with specified type and indicate what to do about
680   /// it. NOTE: All indexed mode stores are initialized to Expand in
681   /// TargetLowering.cpp
682   void setIndexedStoreAction(unsigned IdxMode, MVT::ValueType VT,
683                              LegalizeAction Action) {
684     assert(VT < 32 && IdxMode <
685            sizeof(IndexedModeActions[1]) / sizeof(IndexedModeActions[1][0]) &&
686            "Table isn't big enough!");
687     IndexedModeActions[1][IdxMode] &= ~(uint64_t(3UL) << VT*2);
688     IndexedModeActions[1][IdxMode] |= (uint64_t)Action << VT*2;
689   }
690   
691   /// AddPromotedToType - If Opc/OrigVT is specified as being promoted, the
692   /// promotion code defaults to trying a larger integer/fp until it can find
693   /// one that works.  If that default is insufficient, this method can be used
694   /// by the target to override the default.
695   void AddPromotedToType(unsigned Opc, MVT::ValueType OrigVT, 
696                          MVT::ValueType DestVT) {
697     PromoteToType[std::make_pair(Opc, OrigVT)] = DestVT;
698   }
699
700   /// addLegalFPImmediate - Indicate that this target can instruction select
701   /// the specified FP immediate natively.
702   void addLegalFPImmediate(double Imm) {
703     LegalFPImmediates.push_back(Imm);
704   }
705
706   /// setTargetDAGCombine - Targets should invoke this method for each target
707   /// independent node that they want to provide a custom DAG combiner for by
708   /// implementing the PerformDAGCombine virtual method.
709   void setTargetDAGCombine(ISD::NodeType NT) {
710     TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
711   }
712   
713   /// setJumpBufSize - Set the target's required jmp_buf buffer size (in
714   /// bytes); default is 200
715   void setJumpBufSize(unsigned Size) {
716     JumpBufSize = Size;
717   }
718
719   /// setJumpBufAlignment - Set the target's required jmp_buf buffer
720   /// alignment (in bytes); default is 0
721   void setJumpBufAlignment(unsigned Align) {
722     JumpBufAlignment = Align;
723   }
724   
725 public:
726
727   //===--------------------------------------------------------------------===//
728   // Lowering methods - These methods must be implemented by targets so that
729   // the SelectionDAGLowering code knows how to lower these.
730   //
731
732   /// LowerArguments - This hook must be implemented to indicate how we should
733   /// lower the arguments for the specified function, into the specified DAG.
734   virtual std::vector<SDOperand>
735   LowerArguments(Function &F, SelectionDAG &DAG);
736
737   /// LowerCallTo - This hook lowers an abstract call to a function into an
738   /// actual call.  This returns a pair of operands.  The first element is the
739   /// return value for the function (if RetTy is not VoidTy).  The second
740   /// element is the outgoing token chain.
741   struct ArgListEntry {
742     SDOperand Node;
743     const Type* Ty;
744     bool isSigned;
745   };
746   typedef std::vector<ArgListEntry> ArgListTy;
747   virtual std::pair<SDOperand, SDOperand>
748   LowerCallTo(SDOperand Chain, const Type *RetTy, bool RetTyIsSigned, 
749               bool isVarArg, unsigned CallingConv, bool isTailCall, 
750               SDOperand Callee, ArgListTy &Args, SelectionDAG &DAG);
751
752   /// LowerFrameReturnAddress - This hook lowers a call to llvm.returnaddress or
753   /// llvm.frameaddress (depending on the value of the first argument).  The
754   /// return values are the result pointer and the resultant token chain.  If
755   /// not implemented, both of these intrinsics will return null.
756   virtual std::pair<SDOperand, SDOperand>
757   LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain, unsigned Depth,
758                           SelectionDAG &DAG);
759
760   /// LowerOperation - This callback is invoked for operations that are 
761   /// unsupported by the target, which are registered to use 'custom' lowering,
762   /// and whose defined values are all legal.
763   /// If the target has no operations that require custom lowering, it need not
764   /// implement this.  The default implementation of this aborts.
765   virtual SDOperand LowerOperation(SDOperand Op, SelectionDAG &DAG);
766
767   /// CustomPromoteOperation - This callback is invoked for operations that are
768   /// unsupported by the target, are registered to use 'custom' lowering, and
769   /// whose type needs to be promoted.
770   virtual SDOperand CustomPromoteOperation(SDOperand Op, SelectionDAG &DAG);
771   
772   /// getTargetNodeName() - This method returns the name of a target specific
773   /// DAG node.
774   virtual const char *getTargetNodeName(unsigned Opcode) const;
775
776   //===--------------------------------------------------------------------===//
777   // Inline Asm Support hooks
778   //
779   
780   enum ConstraintType {
781     C_Register,            // Constraint represents a single register.
782     C_RegisterClass,       // Constraint represents one or more registers.
783     C_Memory,              // Memory constraint.
784     C_Other,               // Something else.
785     C_Unknown              // Unsupported constraint.
786   };
787   
788   /// getConstraintType - Given a constraint letter, return the type of
789   /// constraint it is for this target.
790   virtual ConstraintType getConstraintType(char ConstraintLetter) const;
791   
792   
793   /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
794   /// return a list of registers that can be used to satisfy the constraint.
795   /// This should only be used for C_RegisterClass constraints.
796   virtual std::vector<unsigned> 
797   getRegClassForInlineAsmConstraint(const std::string &Constraint,
798                                     MVT::ValueType VT) const;
799
800   /// getRegForInlineAsmConstraint - Given a physical register constraint (e.g.
801   /// {edx}), return the register number and the register class for the
802   /// register.
803   ///
804   /// Given a register class constraint, like 'r', if this corresponds directly
805   /// to an LLVM register class, return a register of 0 and the register class
806   /// pointer.
807   ///
808   /// This should only be used for C_Register constraints.  On error,
809   /// this returns a register number of 0 and a null register class pointer..
810   virtual std::pair<unsigned, const TargetRegisterClass*> 
811     getRegForInlineAsmConstraint(const std::string &Constraint,
812                                  MVT::ValueType VT) const;
813   
814   
815   /// isOperandValidForConstraint - Return the specified operand (possibly
816   /// modified) if the specified SDOperand is valid for the specified target
817   /// constraint letter, otherwise return null.
818   virtual SDOperand 
819     isOperandValidForConstraint(SDOperand Op, char ConstraintLetter,
820                                 SelectionDAG &DAG);
821   
822   //===--------------------------------------------------------------------===//
823   // Scheduler hooks
824   //
825   
826   // InsertAtEndOfBasicBlock - This method should be implemented by targets that
827   // mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
828   // instructions are special in various ways, which require special support to
829   // insert.  The specified MachineInstr is created but not inserted into any
830   // basic blocks, and the scheduler passes ownership of it to this method.
831   virtual MachineBasicBlock *InsertAtEndOfBasicBlock(MachineInstr *MI,
832                                                      MachineBasicBlock *MBB);
833
834   //===--------------------------------------------------------------------===//
835   // Loop Strength Reduction hooks
836   //
837   
838   /// isLegalAddressImmediate - Return true if the integer value or GlobalValue
839   /// can be used as the offset of the target addressing mode.
840   virtual bool isLegalAddressImmediate(int64_t V) const;
841   virtual bool isLegalAddressImmediate(GlobalValue *GV) const;
842
843   typedef std::vector<unsigned>::const_iterator legal_am_scale_iterator;
844   legal_am_scale_iterator legal_am_scale_begin() const {
845     return LegalAddressScales.begin();
846   }
847   legal_am_scale_iterator legal_am_scale_end() const {
848     return LegalAddressScales.end();
849   }
850
851   //===--------------------------------------------------------------------===//
852   // Div utility functions
853   //
854   SDOperand BuildSDIV(SDNode *N, SelectionDAG &DAG, 
855                       std::vector<SDNode*>* Created) const;
856   SDOperand BuildUDIV(SDNode *N, SelectionDAG &DAG, 
857                       std::vector<SDNode*>* Created) const;
858
859
860 protected:
861   /// addLegalAddressScale - Add a integer (> 1) value which can be used as
862   /// scale in the target addressing mode. Note: the ordering matters so the
863   /// least efficient ones should be entered first.
864   void addLegalAddressScale(unsigned Scale) {
865     LegalAddressScales.push_back(Scale);
866   }
867
868 private:
869   std::vector<unsigned> LegalAddressScales;
870   
871   TargetMachine &TM;
872   const TargetData *TD;
873
874   /// IsLittleEndian - True if this is a little endian target.
875   ///
876   bool IsLittleEndian;
877
878   /// PointerTy - The type to use for pointers, usually i32 or i64.
879   ///
880   MVT::ValueType PointerTy;
881
882   /// UsesGlobalOffsetTable - True if this target uses a GOT for PIC codegen.
883   ///
884   bool UsesGlobalOffsetTable;
885   
886   /// ShiftAmountTy - The type to use for shift amounts, usually i8 or whatever
887   /// PointerTy is.
888   MVT::ValueType ShiftAmountTy;
889
890   OutOfRangeShiftAmount ShiftAmtHandling;
891
892   /// SelectIsExpensive - Tells the code generator not to expand operations
893   /// into sequences that use the select operations if possible.
894   bool SelectIsExpensive;
895
896   /// IntDivIsCheap - Tells the code generator not to expand integer divides by
897   /// constants into a sequence of muls, adds, and shifts.  This is a hack until
898   /// a real cost model is in place.  If we ever optimize for size, this will be
899   /// set to true unconditionally.
900   bool IntDivIsCheap;
901   
902   /// Pow2DivIsCheap - Tells the code generator that it shouldn't generate
903   /// srl/add/sra for a signed divide by power of two, and let the target handle
904   /// it.
905   bool Pow2DivIsCheap;
906   
907   /// SetCCResultTy - The type that SetCC operations use.  This defaults to the
908   /// PointerTy.
909   MVT::ValueType SetCCResultTy;
910
911   /// SetCCResultContents - Information about the contents of the high-bits in
912   /// the result of a setcc comparison operation.
913   SetCCResultValue SetCCResultContents;
914
915   /// SchedPreferenceInfo - The target scheduling preference: shortest possible
916   /// total cycles or lowest register usage.
917   SchedPreference SchedPreferenceInfo;
918   
919   /// UseUnderscoreSetJmp - This target prefers to use _setjmp to implement
920   /// llvm.setjmp.  Defaults to false.
921   bool UseUnderscoreSetJmp;
922
923   /// UseUnderscoreLongJmp - This target prefers to use _longjmp to implement
924   /// llvm.longjmp.  Defaults to false.
925   bool UseUnderscoreLongJmp;
926
927   /// JumpBufSize - The size, in bytes, of the target's jmp_buf buffers
928   unsigned JumpBufSize;
929   
930   /// JumpBufAlignment - The alignment, in bytes, of the target's jmp_buf
931   /// buffers
932   unsigned JumpBufAlignment;
933   
934   /// StackPointerRegisterToSaveRestore - If set to a physical register, this
935   /// specifies the register that llvm.savestack/llvm.restorestack should save
936   /// and restore.
937   unsigned StackPointerRegisterToSaveRestore;
938
939   /// RegClassForVT - This indicates the default register class to use for
940   /// each ValueType the target supports natively.
941   TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
942   unsigned char NumElementsForVT[MVT::LAST_VALUETYPE];
943
944   /// TransformToType - For any value types we are promoting or expanding, this
945   /// contains the value type that we are changing to.  For Expanded types, this
946   /// contains one step of the expand (e.g. i64 -> i32), even if there are
947   /// multiple steps required (e.g. i64 -> i16).  For types natively supported
948   /// by the system, this holds the same type (e.g. i32 -> i32).
949   MVT::ValueType TransformToType[MVT::LAST_VALUETYPE];
950
951   /// OpActions - For each operation and each value type, keep a LegalizeAction
952   /// that indicates how instruction selection should deal with the operation.
953   /// Most operations are Legal (aka, supported natively by the target), but
954   /// operations that are not should be described.  Note that operations on
955   /// non-legal value types are not described here.
956   uint64_t OpActions[156];
957   
958   /// LoadXActions - For each load of load extension type and each value type,
959   /// keep a LegalizeAction that indicates how instruction selection should deal
960   /// with the load.
961   uint64_t LoadXActions[ISD::LAST_LOADX_TYPE];
962   
963   /// StoreXActions - For each store with truncation of each value type, keep a
964   /// LegalizeAction that indicates how instruction selection should deal with
965   /// the store.
966   uint64_t StoreXActions;
967
968   /// IndexedModeActions - For each indexed mode and each value type, keep a
969   /// pair of LegalizeAction that indicates how instruction selection should
970   /// deal with the load / store.
971   uint64_t IndexedModeActions[2][ISD::LAST_INDEXED_MODE];
972   
973   ValueTypeActionImpl ValueTypeActions;
974
975   std::vector<double> LegalFPImmediates;
976
977   std::vector<std::pair<MVT::ValueType,
978                         TargetRegisterClass*> > AvailableRegClasses;
979
980   /// TargetDAGCombineArray - Targets can specify ISD nodes that they would
981   /// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(),
982   /// which sets a bit in this array.
983   unsigned char TargetDAGCombineArray[156/(sizeof(unsigned char)*8)];
984   
985   /// PromoteToType - For operations that must be promoted to a specific type,
986   /// this holds the destination type.  This map should be sparse, so don't hold
987   /// it as an array.
988   ///
989   /// Targets add entries to this map with AddPromotedToType(..), clients access
990   /// this with getTypeToPromoteTo(..).
991   std::map<std::pair<unsigned, MVT::ValueType>, MVT::ValueType> PromoteToType;
992   
993 protected:
994   /// When lowering %llvm.memset this field specifies the maximum number of
995   /// store operations that may be substituted for the call to memset. Targets
996   /// must set this value based on the cost threshold for that target. Targets
997   /// should assume that the memset will be done using as many of the largest
998   /// store operations first, followed by smaller ones, if necessary, per
999   /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
1000   /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
1001   /// store.  This only applies to setting a constant array of a constant size.
1002   /// @brief Specify maximum number of store instructions per memset call.
1003   unsigned maxStoresPerMemset;
1004
1005   /// When lowering %llvm.memcpy this field specifies the maximum number of
1006   /// store operations that may be substituted for a call to memcpy. Targets
1007   /// must set this value based on the cost threshold for that target. Targets
1008   /// should assume that the memcpy will be done using as many of the largest
1009   /// store operations first, followed by smaller ones, if necessary, per
1010   /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
1011   /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
1012   /// and one 1-byte store. This only applies to copying a constant array of
1013   /// constant size.
1014   /// @brief Specify maximum bytes of store instructions per memcpy call.
1015   unsigned maxStoresPerMemcpy;
1016
1017   /// When lowering %llvm.memmove this field specifies the maximum number of
1018   /// store instructions that may be substituted for a call to memmove. Targets
1019   /// must set this value based on the cost threshold for that target. Targets
1020   /// should assume that the memmove will be done using as many of the largest
1021   /// store operations first, followed by smaller ones, if necessary, per
1022   /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
1023   /// with 8-bit alignment would result in nine 1-byte stores.  This only
1024   /// applies to copying a constant array of constant size.
1025   /// @brief Specify maximum bytes of store instructions per memmove call.
1026   unsigned maxStoresPerMemmove;
1027
1028   /// This field specifies whether the target machine permits unaligned memory
1029   /// accesses.  This is used, for example, to determine the size of store 
1030   /// operations when copying small arrays and other similar tasks.
1031   /// @brief Indicate whether the target permits unaligned memory accesses.
1032   bool allowUnalignedMemoryAccesses;
1033 };
1034 } // end llvm namespace
1035
1036 #endif