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