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