Rename the 'Attributes' class to 'Attribute'. It's going to represent a single attrib...
[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/ADT/DenseMap.h"
26 #include "llvm/AddressingMode.h"
27 #include "llvm/Attributes.h"
28 #include "llvm/CallingConv.h"
29 #include "llvm/CodeGen/RuntimeLibcalls.h"
30 #include "llvm/CodeGen/SelectionDAGNodes.h"
31 #include "llvm/InlineAsm.h"
32 #include "llvm/Support/CallSite.h"
33 #include "llvm/Support/DebugLoc.h"
34 #include "llvm/Target/TargetCallingConv.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include <climits>
37 #include <map>
38 #include <vector>
39
40 namespace llvm {
41   class CallInst;
42   class CCState;
43   class FastISel;
44   class FunctionLoweringInfo;
45   class ImmutableCallSite;
46   class IntrinsicInst;
47   class MachineBasicBlock;
48   class MachineFunction;
49   class MachineInstr;
50   class MachineJumpTableInfo;
51   class MCContext;
52   class MCExpr;
53   template<typename T> class SmallVectorImpl;
54   class DataLayout;
55   class TargetRegisterClass;
56   class TargetLibraryInfo;
57   class TargetLoweringObjectFile;
58   class Value;
59
60   namespace Sched {
61     enum Preference {
62       None,             // No preference
63       Source,           // Follow source order.
64       RegPressure,      // Scheduling for lowest register pressure.
65       Hybrid,           // Scheduling for both latency and register pressure.
66       ILP,              // Scheduling for ILP in low register pressure mode.
67       VLIW              // Scheduling for VLIW targets.
68     };
69   }
70
71
72 //===----------------------------------------------------------------------===//
73 /// TargetLowering - This class defines information used to lower LLVM code to
74 /// legal SelectionDAG operators that the target instruction selector can accept
75 /// natively.
76 ///
77 /// This class also defines callbacks that targets must implement to lower
78 /// target-specific constructs to SelectionDAG operators.
79 ///
80 class TargetLowering {
81   TargetLowering(const TargetLowering&) LLVM_DELETED_FUNCTION;
82   void operator=(const TargetLowering&) LLVM_DELETED_FUNCTION;
83 public:
84   /// LegalizeAction - This enum indicates whether operations are valid for a
85   /// target, and if not, what action should be used to make them valid.
86   enum LegalizeAction {
87     Legal,      // The target natively supports this operation.
88     Promote,    // This operation should be executed in a larger type.
89     Expand,     // Try to expand this to other ops, otherwise use a libcall.
90     Custom      // Use the LowerOperation hook to implement custom lowering.
91   };
92
93   /// LegalizeTypeAction - This enum indicates whether a types are legal for a
94   /// target, and if not, what action should be used to make them valid.
95   enum LegalizeTypeAction {
96     TypeLegal,           // The target natively supports this type.
97     TypePromoteInteger,  // Replace this integer with a larger one.
98     TypeExpandInteger,   // Split this integer into two of half the size.
99     TypeSoftenFloat,     // Convert this float to a same size integer type.
100     TypeExpandFloat,     // Split this float into two of half the size.
101     TypeScalarizeVector, // Replace this one-element vector with its element.
102     TypeSplitVector,     // Split this vector into two of half the size.
103     TypeWidenVector      // This vector should be widened into a larger vector.
104   };
105
106   /// LegalizeKind holds the legalization kind that needs to happen to EVT
107   /// in order to type-legalize it.
108   typedef std::pair<LegalizeTypeAction, EVT> LegalizeKind;
109
110   enum BooleanContent { // How the target represents true/false values.
111     UndefinedBooleanContent,    // Only bit 0 counts, the rest can hold garbage.
112     ZeroOrOneBooleanContent,        // All bits zero except for bit 0.
113     ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
114   };
115
116   enum SelectSupportKind {
117     ScalarValSelect,      // The target supports scalar selects (ex: cmov).
118     ScalarCondVectorVal,  // The target supports selects with a scalar condition
119                           // and vector values (ex: cmov).
120     VectorMaskSelect      // The target supports vector selects with a vector
121                           // mask (ex: x86 blends).
122   };
123
124   static ISD::NodeType getExtendForContent(BooleanContent Content) {
125     switch (Content) {
126     case UndefinedBooleanContent:
127       // Extend by adding rubbish bits.
128       return ISD::ANY_EXTEND;
129     case ZeroOrOneBooleanContent:
130       // Extend by adding zero bits.
131       return ISD::ZERO_EXTEND;
132     case ZeroOrNegativeOneBooleanContent:
133       // Extend by copying the sign bit.
134       return ISD::SIGN_EXTEND;
135     }
136     llvm_unreachable("Invalid content kind");
137   }
138
139   /// NOTE: The constructor takes ownership of TLOF.
140   explicit TargetLowering(const TargetMachine &TM,
141                           const TargetLoweringObjectFile *TLOF);
142   virtual ~TargetLowering();
143
144   const TargetMachine &getTargetMachine() const { return TM; }
145   const DataLayout *getDataLayout() const { return TD; }
146   const TargetLoweringObjectFile &getObjFileLowering() const { return TLOF; }
147
148   bool isBigEndian() const { return !IsLittleEndian; }
149   bool isLittleEndian() const { return IsLittleEndian; }
150   // Return the pointer type for the given address space, defaults to
151   // the pointer type from the data layout.
152   // FIXME: The default needs to be removed once all the code is updated.
153   virtual MVT getPointerTy(uint32_t AS = 0) const { return PointerTy; }
154   virtual MVT getShiftAmountTy(EVT LHSTy) const;
155
156   /// isSelectExpensive - Return true if the select operation is expensive for
157   /// this target.
158   bool isSelectExpensive() const { return SelectIsExpensive; }
159
160   virtual bool isSelectSupported(SelectSupportKind kind) const { return true; }
161
162   /// shouldSplitVectorElementType - Return true if a vector of the given type
163   /// should be split (TypeSplitVector) instead of promoted
164   /// (TypePromoteInteger) during type legalization.
165   virtual bool shouldSplitVectorElementType(EVT VT) const { return false; }
166
167   /// isIntDivCheap() - Return true if integer divide is usually cheaper than
168   /// a sequence of several shifts, adds, and multiplies for this target.
169   bool isIntDivCheap() const { return IntDivIsCheap; }
170
171   /// isSlowDivBypassed - Returns true if target has indicated at least one
172   /// type should be bypassed.
173   bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
174
175   /// getBypassSlowDivTypes - Returns map of slow types for division or
176   /// remainder with corresponding fast types
177   const DenseMap<unsigned int, unsigned int> &getBypassSlowDivWidths() const {
178     return BypassSlowDivWidths;
179   }
180
181   /// isPow2DivCheap() - Return true if pow2 div is cheaper than a chain of
182   /// srl/add/sra.
183   bool isPow2DivCheap() const { return Pow2DivIsCheap; }
184
185   /// isJumpExpensive() - Return true if Flow Control is an expensive operation
186   /// that should be avoided.
187   bool isJumpExpensive() const { return JumpIsExpensive; }
188
189   /// isPredictableSelectExpensive - Return true if selects are only cheaper
190   /// than branches if the branch is unlikely to be predicted right.
191   bool isPredictableSelectExpensive() const {
192     return predictableSelectIsExpensive;
193   }
194
195   /// getSetCCResultType - Return the ValueType of the result of SETCC
196   /// operations.  Also used to obtain the target's preferred type for
197   /// the condition operand of SELECT and BRCOND nodes.  In the case of
198   /// BRCOND the argument passed is MVT::Other since there are no other
199   /// operands to get a type hint from.
200   virtual EVT getSetCCResultType(EVT VT) const;
201
202   /// getCmpLibcallReturnType - Return the ValueType for comparison
203   /// libcalls. Comparions libcalls include floating point comparion calls,
204   /// and Ordered/Unordered check calls on floating point numbers.
205   virtual
206   MVT::SimpleValueType getCmpLibcallReturnType() const;
207
208   /// getBooleanContents - For targets without i1 registers, this gives the
209   /// nature of the high-bits of boolean values held in types wider than i1.
210   /// "Boolean values" are special true/false values produced by nodes like
211   /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
212   /// Not to be confused with general values promoted from i1.
213   /// Some cpus distinguish between vectors of boolean and scalars; the isVec
214   /// parameter selects between the two kinds.  For example on X86 a scalar
215   /// boolean should be zero extended from i1, while the elements of a vector
216   /// of booleans should be sign extended from i1.
217   BooleanContent getBooleanContents(bool isVec) const {
218     return isVec ? BooleanVectorContents : BooleanContents;
219   }
220
221   /// getSchedulingPreference - Return target scheduling preference.
222   Sched::Preference getSchedulingPreference() const {
223     return SchedPreferenceInfo;
224   }
225
226   /// getSchedulingPreference - Some scheduler, e.g. hybrid, can switch to
227   /// different scheduling heuristics for different nodes. This function returns
228   /// the preference (or none) for the given node.
229   virtual Sched::Preference getSchedulingPreference(SDNode *) const {
230     return Sched::None;
231   }
232
233   /// getRegClassFor - Return the register class that should be used for the
234   /// specified value type.
235   virtual const TargetRegisterClass *getRegClassFor(MVT VT) const {
236     const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
237     assert(RC && "This value type is not natively supported!");
238     return RC;
239   }
240
241   /// getRepRegClassFor - Return the 'representative' register class for the
242   /// specified value type. The 'representative' register class is the largest
243   /// legal super-reg register class for the register class of the value type.
244   /// For example, on i386 the rep register class for i8, i16, and i32 are GR32;
245   /// while the rep register class is GR64 on x86_64.
246   virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
247     const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
248     return RC;
249   }
250
251   /// getRepRegClassCostFor - Return the cost of the 'representative' register
252   /// class for the specified value type.
253   virtual uint8_t getRepRegClassCostFor(EVT VT) const {
254     assert(VT.isSimple() && "getRepRegClassCostFor called on illegal type!");
255     return RepRegClassCostForVT[VT.getSimpleVT().SimpleTy];
256   }
257
258   /// isTypeLegal - Return true if the target has native support for the
259   /// specified value type.  This means that it has a register that directly
260   /// holds it without promotions or expansions.
261   bool isTypeLegal(EVT VT) const {
262     assert(!VT.isSimple() ||
263            (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
264     return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != 0;
265   }
266
267   class ValueTypeActionImpl {
268     /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
269     /// that indicates how instruction selection should deal with the type.
270     uint8_t ValueTypeActions[MVT::LAST_VALUETYPE];
271
272   public:
273     ValueTypeActionImpl() {
274       std::fill(ValueTypeActions, array_endof(ValueTypeActions), 0);
275     }
276
277     LegalizeTypeAction getTypeAction(MVT VT) const {
278       return (LegalizeTypeAction)ValueTypeActions[VT.SimpleTy];
279     }
280
281     void setTypeAction(MVT VT, LegalizeTypeAction Action) {
282       unsigned I = VT.SimpleTy;
283       ValueTypeActions[I] = Action;
284     }
285   };
286
287   const ValueTypeActionImpl &getValueTypeActions() const {
288     return ValueTypeActions;
289   }
290
291   /// getTypeAction - Return how we should legalize values of this type, either
292   /// it is already legal (return 'Legal') or we need to promote it to a larger
293   /// type (return 'Promote'), or we need to expand it into multiple registers
294   /// of smaller integer type (return 'Expand').  'Custom' is not an option.
295   LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const {
296     return getTypeConversion(Context, VT).first;
297   }
298   LegalizeTypeAction getTypeAction(MVT VT) const {
299     return ValueTypeActions.getTypeAction(VT);
300   }
301
302   /// getTypeToTransformTo - For types supported by the target, this is an
303   /// identity function.  For types that must be promoted to larger types, this
304   /// returns the larger type to promote to.  For integer types that are larger
305   /// than the largest integer register, this contains one step in the expansion
306   /// to get to the smaller register. For illegal floating point types, this
307   /// returns the integer type to transform to.
308   EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
309     return getTypeConversion(Context, VT).second;
310   }
311
312   /// getTypeToExpandTo - For types supported by the target, this is an
313   /// identity function.  For types that must be expanded (i.e. integer types
314   /// that are larger than the largest integer register or illegal floating
315   /// point types), this returns the largest legal type it will be expanded to.
316   EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
317     assert(!VT.isVector());
318     while (true) {
319       switch (getTypeAction(Context, VT)) {
320       case TypeLegal:
321         return VT;
322       case TypeExpandInteger:
323         VT = getTypeToTransformTo(Context, VT);
324         break;
325       default:
326         llvm_unreachable("Type is not legal nor is it to be expanded!");
327       }
328     }
329   }
330
331   /// getVectorTypeBreakdown - Vector types are broken down into some number of
332   /// legal first class types.  For example, EVT::v8f32 maps to 2 EVT::v4f32
333   /// with Altivec or SSE1, or 8 promoted EVT::f64 values with the X86 FP stack.
334   /// Similarly, EVT::v2i64 turns into 4 EVT::i32 values with both PPC and X86.
335   ///
336   /// This method returns the number of registers needed, and the VT for each
337   /// register.  It also returns the VT and quantity of the intermediate values
338   /// before they are promoted/expanded.
339   ///
340   unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
341                                   EVT &IntermediateVT,
342                                   unsigned &NumIntermediates,
343                                   EVT &RegisterVT) const;
344
345   /// getTgtMemIntrinsic: Given an intrinsic, checks if on the target the
346   /// intrinsic will need to map to a MemIntrinsicNode (touches memory). If
347   /// this is the case, it returns true and store the intrinsic
348   /// information into the IntrinsicInfo that was passed to the function.
349   struct IntrinsicInfo {
350     unsigned     opc;         // target opcode
351     EVT          memVT;       // memory VT
352     const Value* ptrVal;      // value representing memory location
353     int          offset;      // offset off of ptrVal
354     unsigned     align;       // alignment
355     bool         vol;         // is volatile?
356     bool         readMem;     // reads memory?
357     bool         writeMem;    // writes memory?
358   };
359
360   virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
361                                   unsigned /*Intrinsic*/) const {
362     return false;
363   }
364
365   /// isFPImmLegal - Returns true if the target can instruction select the
366   /// specified FP immediate natively. If false, the legalizer will materialize
367   /// the FP immediate as a load from a constant pool.
368   virtual bool isFPImmLegal(const APFloat &/*Imm*/, EVT /*VT*/) const {
369     return false;
370   }
371
372   /// isShuffleMaskLegal - Targets can use this to indicate that they only
373   /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
374   /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
375   /// are assumed to be legal.
376   virtual bool isShuffleMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
377                                   EVT /*VT*/) const {
378     return true;
379   }
380
381   /// canOpTrap - Returns true if the operation can trap for the value type.
382   /// VT must be a legal type. By default, we optimistically assume most
383   /// operations don't trap except for divide and remainder.
384   virtual bool canOpTrap(unsigned Op, EVT VT) const;
385
386   /// isVectorClearMaskLegal - Similar to isShuffleMaskLegal. This is
387   /// used by Targets can use this to indicate if there is a suitable
388   /// VECTOR_SHUFFLE that can be used to replace a VAND with a constant
389   /// pool entry.
390   virtual bool isVectorClearMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
391                                       EVT /*VT*/) const {
392     return false;
393   }
394
395   /// getOperationAction - Return how this operation should be treated: either
396   /// it is legal, needs to be promoted to a larger size, needs to be
397   /// expanded to some other code sequence, or the target has a custom expander
398   /// for it.
399   LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
400     if (VT.isExtended()) return Expand;
401     // If a target-specific SDNode requires legalization, require the target
402     // to provide custom legalization for it.
403     if (Op > array_lengthof(OpActions[0])) return Custom;
404     unsigned I = (unsigned) VT.getSimpleVT().SimpleTy;
405     return (LegalizeAction)OpActions[I][Op];
406   }
407
408   /// isOperationLegalOrCustom - Return true if the specified operation is
409   /// legal on this target or can be made legal with custom lowering. This
410   /// is used to help guide high-level lowering decisions.
411   bool isOperationLegalOrCustom(unsigned Op, EVT VT) const {
412     return (VT == MVT::Other || isTypeLegal(VT)) &&
413       (getOperationAction(Op, VT) == Legal ||
414        getOperationAction(Op, VT) == Custom);
415   }
416
417   /// isOperationExpand - Return true if the specified operation is illegal on
418   /// this target or unlikely to be made legal with custom lowering. This is
419   /// used to help guide high-level lowering decisions.
420   bool isOperationExpand(unsigned Op, EVT VT) const {
421     return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
422   }
423
424   /// isOperationLegal - Return true if the specified operation is legal on this
425   /// target.
426   bool isOperationLegal(unsigned Op, EVT VT) const {
427     return (VT == MVT::Other || isTypeLegal(VT)) &&
428            getOperationAction(Op, VT) == Legal;
429   }
430
431   /// getLoadExtAction - Return how this load with extension should be treated:
432   /// either it is legal, needs to be promoted to a larger size, needs to be
433   /// expanded to some other code sequence, or the target has a custom expander
434   /// for it.
435   LegalizeAction getLoadExtAction(unsigned ExtType, MVT VT) const {
436     assert(ExtType < ISD::LAST_LOADEXT_TYPE && VT < MVT::LAST_VALUETYPE &&
437            "Table isn't big enough!");
438     return (LegalizeAction)LoadExtActions[VT.SimpleTy][ExtType];
439   }
440
441   /// isLoadExtLegal - Return true if the specified load with extension is legal
442   /// on this target.
443   bool isLoadExtLegal(unsigned ExtType, EVT VT) const {
444     return VT.isSimple() &&
445       getLoadExtAction(ExtType, VT.getSimpleVT()) == Legal;
446   }
447
448   /// getTruncStoreAction - Return how this store with truncation should be
449   /// treated: either it is legal, needs to be promoted to a larger size, needs
450   /// to be expanded to some other code sequence, or the target has a custom
451   /// expander for it.
452   LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT) const {
453     assert(ValVT.getSimpleVT() < MVT::LAST_VALUETYPE &&
454            MemVT.getSimpleVT() < MVT::LAST_VALUETYPE &&
455            "Table isn't big enough!");
456     return (LegalizeAction)TruncStoreActions[ValVT.getSimpleVT().SimpleTy]
457                                             [MemVT.getSimpleVT().SimpleTy];
458   }
459
460   /// isTruncStoreLegal - Return true if the specified store with truncation is
461   /// legal on this target.
462   bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
463     return isTypeLegal(ValVT) && MemVT.isSimple() &&
464            getTruncStoreAction(ValVT, MemVT) == Legal;
465   }
466
467   /// getIndexedLoadAction - Return how the indexed load should be treated:
468   /// either it is legal, needs to be promoted to a larger size, needs to be
469   /// expanded to some other code sequence, or the target has a custom expander
470   /// for it.
471   LegalizeAction
472   getIndexedLoadAction(unsigned IdxMode, EVT VT) const {
473     assert(IdxMode < ISD::LAST_INDEXED_MODE &&
474            VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
475            "Table isn't big enough!");
476     unsigned Ty = (unsigned)VT.getSimpleVT().SimpleTy;
477     return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] & 0xf0) >> 4);
478   }
479
480   /// isIndexedLoadLegal - Return true if the specified indexed load is legal
481   /// on this target.
482   bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
483     return VT.isSimple() &&
484       (getIndexedLoadAction(IdxMode, VT) == Legal ||
485        getIndexedLoadAction(IdxMode, VT) == Custom);
486   }
487
488   /// getIndexedStoreAction - Return how the indexed store should be treated:
489   /// either it is legal, needs to be promoted to a larger size, needs to be
490   /// expanded to some other code sequence, or the target has a custom expander
491   /// for it.
492   LegalizeAction
493   getIndexedStoreAction(unsigned IdxMode, EVT VT) const {
494     assert(IdxMode < ISD::LAST_INDEXED_MODE &&
495            VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
496            "Table isn't big enough!");
497     unsigned Ty = (unsigned)VT.getSimpleVT().SimpleTy;
498     return (LegalizeAction)(IndexedModeActions[Ty][IdxMode] & 0x0f);
499   }
500
501   /// isIndexedStoreLegal - Return true if the specified indexed load is legal
502   /// on this target.
503   bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
504     return VT.isSimple() &&
505       (getIndexedStoreAction(IdxMode, VT) == Legal ||
506        getIndexedStoreAction(IdxMode, VT) == Custom);
507   }
508
509   /// getCondCodeAction - Return how the condition code should be treated:
510   /// either it is legal, needs to be expanded to some other code sequence,
511   /// or the target has a custom expander for it.
512   LegalizeAction
513   getCondCodeAction(ISD::CondCode CC, EVT VT) const {
514     assert((unsigned)CC < array_lengthof(CondCodeActions) &&
515            (unsigned)VT.getSimpleVT().SimpleTy < sizeof(CondCodeActions[0])*4 &&
516            "Table isn't big enough!");
517     /// The lower 5 bits of the SimpleTy index into Nth 2bit set from the 64bit
518     /// value and the upper 27 bits index into the second dimension of the
519     /// array to select what 64bit value to use.
520     LegalizeAction Action = (LegalizeAction)
521       ((CondCodeActions[CC][VT.getSimpleVT().SimpleTy >> 5]
522         >> (2*(VT.getSimpleVT().SimpleTy & 0x1F))) & 3);
523     assert(Action != Promote && "Can't promote condition code!");
524     return Action;
525   }
526
527   /// isCondCodeLegal - Return true if the specified condition code is legal
528   /// on this target.
529   bool isCondCodeLegal(ISD::CondCode CC, EVT VT) const {
530     return getCondCodeAction(CC, VT) == Legal ||
531            getCondCodeAction(CC, VT) == Custom;
532   }
533
534
535   /// getTypeToPromoteTo - If the action for this operation is to promote, this
536   /// method returns the ValueType to promote to.
537   EVT getTypeToPromoteTo(unsigned Op, EVT VT) const {
538     assert(getOperationAction(Op, VT) == Promote &&
539            "This operation isn't promoted!");
540
541     // See if this has an explicit type specified.
542     std::map<std::pair<unsigned, MVT::SimpleValueType>,
543              MVT::SimpleValueType>::const_iterator PTTI =
544       PromoteToType.find(std::make_pair(Op, VT.getSimpleVT().SimpleTy));
545     if (PTTI != PromoteToType.end()) return PTTI->second;
546
547     assert((VT.isInteger() || VT.isFloatingPoint()) &&
548            "Cannot autopromote this type, add it with AddPromotedToType.");
549
550     EVT NVT = VT;
551     do {
552       NVT = (MVT::SimpleValueType)(NVT.getSimpleVT().SimpleTy+1);
553       assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
554              "Didn't find type to promote to!");
555     } while (!isTypeLegal(NVT) ||
556               getOperationAction(Op, NVT) == Promote);
557     return NVT;
558   }
559
560   /// getValueType - Return the EVT corresponding to this LLVM type.
561   /// This is fixed by the LLVM operations except for the pointer size.  If
562   /// AllowUnknown is true, this will return MVT::Other for types with no EVT
563   /// counterpart (e.g. structs), otherwise it will assert.
564   EVT getValueType(Type *Ty, bool AllowUnknown = false) const {
565     // Lower scalar pointers to native pointer types.
566     if (Ty->isPointerTy()) return PointerTy;
567
568     if (Ty->isVectorTy()) {
569       VectorType *VTy = cast<VectorType>(Ty);
570       Type *Elm = VTy->getElementType();
571       // Lower vectors of pointers to native pointer types.
572       if (Elm->isPointerTy()) 
573         Elm = EVT(PointerTy).getTypeForEVT(Ty->getContext());
574       return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
575                        VTy->getNumElements());
576     }
577     return EVT::getEVT(Ty, AllowUnknown);
578   }
579
580   /// Return the MVT corresponding to this LLVM type. See getValueType.
581   MVT getSimpleValueType(Type *Ty, bool AllowUnknown = false) const {
582     return getValueType(Ty, AllowUnknown).getSimpleVT();
583   }
584
585   /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
586   /// function arguments in the caller parameter area.  This is the actual
587   /// alignment, not its logarithm.
588   virtual unsigned getByValTypeAlignment(Type *Ty) const;
589
590   /// getRegisterType - Return the type of registers that this ValueType will
591   /// eventually require.
592   EVT getRegisterType(MVT VT) const {
593     assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
594     return RegisterTypeForVT[VT.SimpleTy];
595   }
596
597   /// getRegisterType - Return the type of registers that this ValueType will
598   /// eventually require.
599   EVT getRegisterType(LLVMContext &Context, EVT VT) const {
600     if (VT.isSimple()) {
601       assert((unsigned)VT.getSimpleVT().SimpleTy <
602                 array_lengthof(RegisterTypeForVT));
603       return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
604     }
605     if (VT.isVector()) {
606       EVT VT1, RegisterVT;
607       unsigned NumIntermediates;
608       (void)getVectorTypeBreakdown(Context, VT, VT1,
609                                    NumIntermediates, RegisterVT);
610       return RegisterVT;
611     }
612     if (VT.isInteger()) {
613       return getRegisterType(Context, getTypeToTransformTo(Context, VT));
614     }
615     llvm_unreachable("Unsupported extended type!");
616   }
617
618   /// getNumRegisters - Return the number of registers that this ValueType will
619   /// eventually require.  This is one for any types promoted to live in larger
620   /// registers, but may be more than one for types (like i64) that are split
621   /// into pieces.  For types like i140, which are first promoted then expanded,
622   /// it is the number of registers needed to hold all the bits of the original
623   /// type.  For an i140 on a 32 bit machine this means 5 registers.
624   unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
625     if (VT.isSimple()) {
626       assert((unsigned)VT.getSimpleVT().SimpleTy <
627                 array_lengthof(NumRegistersForVT));
628       return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
629     }
630     if (VT.isVector()) {
631       EVT VT1, VT2;
632       unsigned NumIntermediates;
633       return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
634     }
635     if (VT.isInteger()) {
636       unsigned BitWidth = VT.getSizeInBits();
637       unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
638       return (BitWidth + RegWidth - 1) / RegWidth;
639     }
640     llvm_unreachable("Unsupported extended type!");
641   }
642
643   /// ShouldShrinkFPConstant - If true, then instruction selection should
644   /// seek to shrink the FP constant of the specified type to a smaller type
645   /// in order to save space and / or reduce runtime.
646   virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
647
648   /// hasTargetDAGCombine - If true, the target has custom DAG combine
649   /// transformations that it can perform for the specified node.
650   bool hasTargetDAGCombine(ISD::NodeType NT) const {
651     assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
652     return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
653   }
654
655   /// This function returns the maximum number of store operations permitted
656   /// to replace a call to llvm.memset. The value is set by the target at the
657   /// performance threshold for such a replacement. If OptSize is true,
658   /// return the limit for functions that have OptSize attribute.
659   /// @brief Get maximum # of store operations permitted for llvm.memset
660   unsigned getMaxStoresPerMemset(bool OptSize) const {
661     return OptSize ? maxStoresPerMemsetOptSize : maxStoresPerMemset;
662   }
663
664   /// This function returns the maximum number of store operations permitted
665   /// to replace a call to llvm.memcpy. The value is set by the target at the
666   /// performance threshold for such a replacement. If OptSize is true,
667   /// return the limit for functions that have OptSize attribute.
668   /// @brief Get maximum # of store operations permitted for llvm.memcpy
669   unsigned getMaxStoresPerMemcpy(bool OptSize) const {
670     return OptSize ? maxStoresPerMemcpyOptSize : maxStoresPerMemcpy;
671   }
672
673   /// This function returns the maximum number of store operations permitted
674   /// to replace a call to llvm.memmove. The value is set by the target at the
675   /// performance threshold for such a replacement. If OptSize is true,
676   /// return the limit for functions that have OptSize attribute.
677   /// @brief Get maximum # of store operations permitted for llvm.memmove
678   unsigned getMaxStoresPerMemmove(bool OptSize) const {
679     return OptSize ? maxStoresPerMemmoveOptSize : maxStoresPerMemmove;
680   }
681
682   /// This function returns true if the target allows unaligned memory accesses.
683   /// of the specified type. If true, it also returns whether the unaligned
684   /// memory access is "fast" in the second argument by reference. This is used,
685   /// for example, in situations where an array copy/move/set is  converted to a
686   /// sequence of store operations. It's use helps to ensure that such
687   /// replacements don't generate code that causes an alignment error  (trap) on
688   /// the target machine.
689   /// @brief Determine if the target supports unaligned memory accesses.
690   virtual bool allowsUnalignedMemoryAccesses(EVT, bool *Fast = 0) const {
691     return false;
692   }
693
694   /// This function returns true if the target would benefit from code placement
695   /// optimization.
696   /// @brief Determine if the target should perform code placement optimization.
697   bool shouldOptimizeCodePlacement() const {
698     return benefitFromCodePlacementOpt;
699   }
700
701   /// getOptimalMemOpType - Returns the target specific optimal type for load
702   /// and store operations as a result of memset, memcpy, and memmove
703   /// lowering. If DstAlign is zero that means it's safe to destination
704   /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
705   /// means there isn't a need to check it against alignment requirement,
706   /// probably because the source does not need to be loaded. If 'IsMemset' is
707   /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
708   /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
709   /// source is constant so it does not need to be loaded.
710   /// It returns EVT::Other if the type should be determined using generic
711   /// target-independent logic.
712   virtual EVT getOptimalMemOpType(uint64_t /*Size*/,
713                                   unsigned /*DstAlign*/, unsigned /*SrcAlign*/,
714                                   bool /*IsMemset*/,
715                                   bool /*ZeroMemset*/,
716                                   bool /*MemcpyStrSrc*/,
717                                   MachineFunction &/*MF*/) const {
718     return MVT::Other;
719   }
720
721   /// isSafeMemOpType - Returns true if it's safe to use load / store of the
722   /// specified type to expand memcpy / memset inline. This is mostly true
723   /// for all types except for some special cases. For example, on X86
724   /// targets without SSE2 f64 load / store are done with fldl / fstpl which
725   /// also does type conversion. Note the specified type doesn't have to be
726   /// legal as the hook is used before type legalization.
727   virtual bool isSafeMemOpType(MVT VT) const {
728     return true;
729   }
730
731   /// usesUnderscoreSetJmp - Determine if we should use _setjmp or setjmp
732   /// to implement llvm.setjmp.
733   bool usesUnderscoreSetJmp() const {
734     return UseUnderscoreSetJmp;
735   }
736
737   /// usesUnderscoreLongJmp - Determine if we should use _longjmp or longjmp
738   /// to implement llvm.longjmp.
739   bool usesUnderscoreLongJmp() const {
740     return UseUnderscoreLongJmp;
741   }
742
743   /// supportJumpTables - return whether the target can generate code for
744   /// jump tables.
745   bool supportJumpTables() const {
746     return SupportJumpTables;
747   }
748
749   /// getMinimumJumpTableEntries - return integer threshold on number of
750   /// blocks to use jump tables rather than if sequence.
751   int getMinimumJumpTableEntries() const {
752     return MinimumJumpTableEntries;
753   }
754
755   /// getStackPointerRegisterToSaveRestore - If a physical register, this
756   /// specifies the register that llvm.savestack/llvm.restorestack should save
757   /// and restore.
758   unsigned getStackPointerRegisterToSaveRestore() const {
759     return StackPointerRegisterToSaveRestore;
760   }
761
762   /// getExceptionPointerRegister - If a physical register, this returns
763   /// the register that receives the exception address on entry to a landing
764   /// pad.
765   unsigned getExceptionPointerRegister() const {
766     return ExceptionPointerRegister;
767   }
768
769   /// getExceptionSelectorRegister - If a physical register, this returns
770   /// the register that receives the exception typeid on entry to a landing
771   /// pad.
772   unsigned getExceptionSelectorRegister() const {
773     return ExceptionSelectorRegister;
774   }
775
776   /// getJumpBufSize - returns the target's jmp_buf size in bytes (if never
777   /// set, the default is 200)
778   unsigned getJumpBufSize() const {
779     return JumpBufSize;
780   }
781
782   /// getJumpBufAlignment - returns the target's jmp_buf alignment in bytes
783   /// (if never set, the default is 0)
784   unsigned getJumpBufAlignment() const {
785     return JumpBufAlignment;
786   }
787
788   /// getMinStackArgumentAlignment - return the minimum stack alignment of an
789   /// argument.
790   unsigned getMinStackArgumentAlignment() const {
791     return MinStackArgumentAlignment;
792   }
793
794   /// getMinFunctionAlignment - return the minimum function alignment.
795   ///
796   unsigned getMinFunctionAlignment() const {
797     return MinFunctionAlignment;
798   }
799
800   /// getPrefFunctionAlignment - return the preferred function alignment.
801   ///
802   unsigned getPrefFunctionAlignment() const {
803     return PrefFunctionAlignment;
804   }
805
806   /// getPrefLoopAlignment - return the preferred loop alignment.
807   ///
808   unsigned getPrefLoopAlignment() const {
809     return PrefLoopAlignment;
810   }
811
812   /// getShouldFoldAtomicFences - return whether the combiner should fold
813   /// fence MEMBARRIER instructions into the atomic intrinsic instructions.
814   ///
815   bool getShouldFoldAtomicFences() const {
816     return ShouldFoldAtomicFences;
817   }
818
819   /// getInsertFencesFor - return whether the DAG builder should automatically
820   /// insert fences and reduce ordering for atomics.
821   ///
822   bool getInsertFencesForAtomic() const {
823     return InsertFencesForAtomic;
824   }
825
826   /// getPreIndexedAddressParts - returns true by value, base pointer and
827   /// offset pointer and addressing mode by reference if the node's address
828   /// can be legally represented as pre-indexed load / store address.
829   virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
830                                          SDValue &/*Offset*/,
831                                          ISD::MemIndexedMode &/*AM*/,
832                                          SelectionDAG &/*DAG*/) const {
833     return false;
834   }
835
836   /// getPostIndexedAddressParts - returns true by value, base pointer and
837   /// offset pointer and addressing mode by reference if this node can be
838   /// combined with a load / store to form a post-indexed load / store.
839   virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
840                                           SDValue &/*Base*/, SDValue &/*Offset*/,
841                                           ISD::MemIndexedMode &/*AM*/,
842                                           SelectionDAG &/*DAG*/) const {
843     return false;
844   }
845
846   /// getJumpTableEncoding - Return the entry encoding for a jump table in the
847   /// current function.  The returned value is a member of the
848   /// MachineJumpTableInfo::JTEntryKind enum.
849   virtual unsigned getJumpTableEncoding() const;
850
851   virtual const MCExpr *
852   LowerCustomJumpTableEntry(const MachineJumpTableInfo * /*MJTI*/,
853                             const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
854                             MCContext &/*Ctx*/) const {
855     llvm_unreachable("Need to implement this hook if target has custom JTIs");
856   }
857
858   /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
859   /// jumptable.
860   virtual SDValue getPICJumpTableRelocBase(SDValue Table,
861                                            SelectionDAG &DAG) const;
862
863   /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
864   /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
865   /// MCExpr.
866   virtual const MCExpr *
867   getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
868                                unsigned JTI, MCContext &Ctx) const;
869
870   /// isOffsetFoldingLegal - Return true if folding a constant offset
871   /// with the given GlobalAddress is legal.  It is frequently not legal in
872   /// PIC relocation models.
873   virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
874
875   /// getStackCookieLocation - Return true if the target stores stack
876   /// protector cookies at a fixed offset in some non-standard address
877   /// space, and populates the address space and offset as
878   /// appropriate.
879   virtual bool getStackCookieLocation(unsigned &/*AddressSpace*/,
880                                       unsigned &/*Offset*/) const {
881     return false;
882   }
883
884   /// getMaximalGlobalOffset - Returns the maximal possible offset which can be
885   /// used for loads / stores from the global.
886   virtual unsigned getMaximalGlobalOffset() const {
887     return 0;
888   }
889
890   //===--------------------------------------------------------------------===//
891   // TargetLowering Optimization Methods
892   //
893
894   /// TargetLoweringOpt - A convenience struct that encapsulates a DAG, and two
895   /// SDValues for returning information from TargetLowering to its clients
896   /// that want to combine
897   struct TargetLoweringOpt {
898     SelectionDAG &DAG;
899     bool LegalTys;
900     bool LegalOps;
901     SDValue Old;
902     SDValue New;
903
904     explicit TargetLoweringOpt(SelectionDAG &InDAG,
905                                bool LT, bool LO) :
906       DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
907
908     bool LegalTypes() const { return LegalTys; }
909     bool LegalOperations() const { return LegalOps; }
910
911     bool CombineTo(SDValue O, SDValue N) {
912       Old = O;
913       New = N;
914       return true;
915     }
916
917     /// ShrinkDemandedConstant - Check to see if the specified operand of the
918     /// specified instruction is a constant integer.  If so, check to see if
919     /// there are any bits set in the constant that are not demanded.  If so,
920     /// shrink the constant and return true.
921     bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded);
922
923     /// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the
924     /// casts are free.  This uses isZExtFree and ZERO_EXTEND for the widening
925     /// cast, but it could be generalized for targets with other types of
926     /// implicit widening casts.
927     bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
928                           DebugLoc dl);
929   };
930
931   /// SimplifyDemandedBits - Look at Op.  At this point, we know that only the
932   /// DemandedMask bits of the result of Op are ever used downstream.  If we can
933   /// use this information to simplify Op, create a new simplified DAG node and
934   /// return true, returning the original and new nodes in Old and New.
935   /// Otherwise, analyze the expression and return a mask of KnownOne and
936   /// KnownZero bits for the expression (used to simplify the caller).
937   /// The KnownZero/One bits may only be accurate for those bits in the
938   /// DemandedMask.
939   bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
940                             APInt &KnownZero, APInt &KnownOne,
941                             TargetLoweringOpt &TLO, unsigned Depth = 0) const;
942
943   /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
944   /// Mask are known to be either zero or one and return them in the
945   /// KnownZero/KnownOne bitsets.
946   virtual void computeMaskedBitsForTargetNode(const SDValue Op,
947                                               APInt &KnownZero,
948                                               APInt &KnownOne,
949                                               const SelectionDAG &DAG,
950                                               unsigned Depth = 0) const;
951
952   /// ComputeNumSignBitsForTargetNode - This method can be implemented by
953   /// targets that want to expose additional information about sign bits to the
954   /// DAG Combiner.
955   virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
956                                                    unsigned Depth = 0) const;
957
958   struct DAGCombinerInfo {
959     void *DC;  // The DAG Combiner object.
960     bool BeforeLegalize;
961     bool BeforeLegalizeOps;
962     bool CalledByLegalizer;
963   public:
964     SelectionDAG &DAG;
965
966     DAGCombinerInfo(SelectionDAG &dag, bool bl, bool blo, bool cl, void *dc)
967       : DC(dc), BeforeLegalize(bl), BeforeLegalizeOps(blo),
968         CalledByLegalizer(cl), DAG(dag) {}
969
970     bool isBeforeLegalize() const { return BeforeLegalize; }
971     bool isBeforeLegalizeOps() const { return BeforeLegalizeOps; }
972     bool isCalledByLegalizer() const { return CalledByLegalizer; }
973
974     void AddToWorklist(SDNode *N);
975     void RemoveFromWorklist(SDNode *N);
976     SDValue CombineTo(SDNode *N, const std::vector<SDValue> &To,
977                       bool AddTo = true);
978     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
979     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
980
981     void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
982   };
983
984   /// SimplifySetCC - Try to simplify a setcc built with the specified operands
985   /// and cc. If it is unable to simplify it, return a null SDValue.
986   SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
987                           ISD::CondCode Cond, bool foldBooleans,
988                           DAGCombinerInfo &DCI, DebugLoc dl) const;
989
990   /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
991   /// node is a GlobalAddress + offset.
992   virtual bool
993   isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
994
995   /// PerformDAGCombine - This method will be invoked for all target nodes and
996   /// for any target-independent nodes that the target has registered with
997   /// invoke it for.
998   ///
999   /// The semantics are as follows:
1000   /// Return Value:
1001   ///   SDValue.Val == 0   - No change was made
1002   ///   SDValue.Val == N   - N was replaced, is dead, and is already handled.
1003   ///   otherwise          - N should be replaced by the returned Operand.
1004   ///
1005   /// In addition, methods provided by DAGCombinerInfo may be used to perform
1006   /// more complex transformations.
1007   ///
1008   virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
1009
1010   /// isTypeDesirableForOp - Return true if the target has native support for
1011   /// the specified value type and it is 'desirable' to use the type for the
1012   /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
1013   /// instruction encodings are longer and some i16 instructions are slow.
1014   virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
1015     // By default, assume all legal types are desirable.
1016     return isTypeLegal(VT);
1017   }
1018
1019   /// isDesirableToPromoteOp - Return true if it is profitable for dag combiner
1020   /// to transform a floating point op of specified opcode to a equivalent op of
1021   /// an integer type. e.g. f32 load -> i32 load can be profitable on ARM.
1022   virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
1023                                                  EVT /*VT*/) const {
1024     return false;
1025   }
1026
1027   /// IsDesirableToPromoteOp - This method query the target whether it is
1028   /// beneficial for dag combiner to promote the specified node. If true, it
1029   /// should return the desired promotion type by reference.
1030   virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
1031     return false;
1032   }
1033
1034   //===--------------------------------------------------------------------===//
1035   // TargetLowering Configuration Methods - These methods should be invoked by
1036   // the derived class constructor to configure this object for the target.
1037   //
1038
1039 protected:
1040   /// setBooleanContents - Specify how the target extends the result of a
1041   /// boolean value from i1 to a wider type.  See getBooleanContents.
1042   void setBooleanContents(BooleanContent Ty) { BooleanContents = Ty; }
1043   /// setBooleanVectorContents - Specify how the target extends the result
1044   /// of a vector boolean value from a vector of i1 to a wider type.  See
1045   /// getBooleanContents.
1046   void setBooleanVectorContents(BooleanContent Ty) {
1047     BooleanVectorContents = Ty;
1048   }
1049
1050   /// setSchedulingPreference - Specify the target scheduling preference.
1051   void setSchedulingPreference(Sched::Preference Pref) {
1052     SchedPreferenceInfo = Pref;
1053   }
1054
1055   /// setUseUnderscoreSetJmp - Indicate whether this target prefers to
1056   /// use _setjmp to implement llvm.setjmp or the non _ version.
1057   /// Defaults to false.
1058   void setUseUnderscoreSetJmp(bool Val) {
1059     UseUnderscoreSetJmp = Val;
1060   }
1061
1062   /// setUseUnderscoreLongJmp - Indicate whether this target prefers to
1063   /// use _longjmp to implement llvm.longjmp or the non _ version.
1064   /// Defaults to false.
1065   void setUseUnderscoreLongJmp(bool Val) {
1066     UseUnderscoreLongJmp = Val;
1067   }
1068
1069   /// setSupportJumpTables - Indicate whether the target can generate code for
1070   /// jump tables.
1071   void setSupportJumpTables(bool Val) {
1072     SupportJumpTables = Val;
1073   }
1074
1075   /// setMinimumJumpTableEntries - Indicate the number of blocks to generate
1076   /// jump tables rather than if sequence.
1077   void setMinimumJumpTableEntries(int Val) {
1078     MinimumJumpTableEntries = Val;
1079   }
1080
1081   /// setStackPointerRegisterToSaveRestore - If set to a physical register, this
1082   /// specifies the register that llvm.savestack/llvm.restorestack should save
1083   /// and restore.
1084   void setStackPointerRegisterToSaveRestore(unsigned R) {
1085     StackPointerRegisterToSaveRestore = R;
1086   }
1087
1088   /// setExceptionPointerRegister - If set to a physical register, this sets
1089   /// the register that receives the exception address on entry to a landing
1090   /// pad.
1091   void setExceptionPointerRegister(unsigned R) {
1092     ExceptionPointerRegister = R;
1093   }
1094
1095   /// setExceptionSelectorRegister - If set to a physical register, this sets
1096   /// the register that receives the exception typeid on entry to a landing
1097   /// pad.
1098   void setExceptionSelectorRegister(unsigned R) {
1099     ExceptionSelectorRegister = R;
1100   }
1101
1102   /// SelectIsExpensive - Tells the code generator not to expand operations
1103   /// into sequences that use the select operations if possible.
1104   void setSelectIsExpensive(bool isExpensive = true) {
1105     SelectIsExpensive = isExpensive;
1106   }
1107
1108   /// JumpIsExpensive - Tells the code generator not to expand sequence of
1109   /// operations into a separate sequences that increases the amount of
1110   /// flow control.
1111   void setJumpIsExpensive(bool isExpensive = true) {
1112     JumpIsExpensive = isExpensive;
1113   }
1114
1115   /// setIntDivIsCheap - Tells the code generator that integer divide is
1116   /// expensive, and if possible, should be replaced by an alternate sequence
1117   /// of instructions not containing an integer divide.
1118   void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
1119
1120   /// addBypassSlowDiv - Tells the code generator which bitwidths to bypass.
1121   void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
1122     BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
1123   }
1124
1125   /// setPow2DivIsCheap - Tells the code generator that it shouldn't generate
1126   /// srl/add/sra for a signed divide by power of two, and let the target handle
1127   /// it.
1128   void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
1129
1130   /// addRegisterClass - Add the specified register class as an available
1131   /// regclass for the specified value type.  This indicates the selector can
1132   /// handle values of that class natively.
1133   void addRegisterClass(EVT VT, const TargetRegisterClass *RC) {
1134     assert((unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
1135     AvailableRegClasses.push_back(std::make_pair(VT, RC));
1136     RegClassForVT[VT.getSimpleVT().SimpleTy] = RC;
1137   }
1138
1139   /// findRepresentativeClass - Return the largest legal super-reg register class
1140   /// of the register class for the specified type and its associated "cost".
1141   virtual std::pair<const TargetRegisterClass*, uint8_t>
1142   findRepresentativeClass(EVT VT) const;
1143
1144   /// computeRegisterProperties - Once all of the register classes are added,
1145   /// this allows us to compute derived properties we expose.
1146   void computeRegisterProperties();
1147
1148   /// setOperationAction - Indicate that the specified operation does not work
1149   /// with the specified type and indicate what to do about it.
1150   void setOperationAction(unsigned Op, MVT VT,
1151                           LegalizeAction Action) {
1152     assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
1153     OpActions[(unsigned)VT.SimpleTy][Op] = (uint8_t)Action;
1154   }
1155
1156   /// setLoadExtAction - Indicate that the specified load with extension does
1157   /// not work with the specified type and indicate what to do about it.
1158   void setLoadExtAction(unsigned ExtType, MVT VT,
1159                         LegalizeAction Action) {
1160     assert(ExtType < ISD::LAST_LOADEXT_TYPE && VT < MVT::LAST_VALUETYPE &&
1161            "Table isn't big enough!");
1162     LoadExtActions[VT.SimpleTy][ExtType] = (uint8_t)Action;
1163   }
1164
1165   /// setTruncStoreAction - Indicate that the specified truncating store does
1166   /// not work with the specified type and indicate what to do about it.
1167   void setTruncStoreAction(MVT ValVT, MVT MemVT,
1168                            LegalizeAction Action) {
1169     assert(ValVT < MVT::LAST_VALUETYPE && MemVT < MVT::LAST_VALUETYPE &&
1170            "Table isn't big enough!");
1171     TruncStoreActions[ValVT.SimpleTy][MemVT.SimpleTy] = (uint8_t)Action;
1172   }
1173
1174   /// setIndexedLoadAction - Indicate that the specified indexed load does or
1175   /// does not work with the specified type and indicate what to do abort
1176   /// it. NOTE: All indexed mode loads are initialized to Expand in
1177   /// TargetLowering.cpp
1178   void setIndexedLoadAction(unsigned IdxMode, MVT VT,
1179                             LegalizeAction Action) {
1180     assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
1181            (unsigned)Action < 0xf && "Table isn't big enough!");
1182     // Load action are kept in the upper half.
1183     IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0xf0;
1184     IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action) <<4;
1185   }
1186
1187   /// setIndexedStoreAction - Indicate that the specified indexed store does or
1188   /// does not work with the specified type and indicate what to do about
1189   /// it. NOTE: All indexed mode stores are initialized to Expand in
1190   /// TargetLowering.cpp
1191   void setIndexedStoreAction(unsigned IdxMode, MVT VT,
1192                              LegalizeAction Action) {
1193     assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
1194            (unsigned)Action < 0xf && "Table isn't big enough!");
1195     // Store action are kept in the lower half.
1196     IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0x0f;
1197     IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action);
1198   }
1199
1200   /// setCondCodeAction - Indicate that the specified condition code is or isn't
1201   /// supported on the target and indicate what to do about it.
1202   void setCondCodeAction(ISD::CondCode CC, MVT VT,
1203                          LegalizeAction Action) {
1204     assert(VT < MVT::LAST_VALUETYPE &&
1205            (unsigned)CC < array_lengthof(CondCodeActions) &&
1206            "Table isn't big enough!");
1207     /// The lower 5 bits of the SimpleTy index into Nth 2bit set from the 64bit
1208     /// value and the upper 27 bits index into the second dimension of the
1209     /// array to select what 64bit value to use.
1210     CondCodeActions[(unsigned)CC][VT.SimpleTy >> 5]
1211       &= ~(uint64_t(3UL)  << (VT.SimpleTy & 0x1F)*2);
1212     CondCodeActions[(unsigned)CC][VT.SimpleTy >> 5]
1213       |= (uint64_t)Action << (VT.SimpleTy & 0x1F)*2;
1214   }
1215
1216   /// AddPromotedToType - If Opc/OrigVT is specified as being promoted, the
1217   /// promotion code defaults to trying a larger integer/fp until it can find
1218   /// one that works.  If that default is insufficient, this method can be used
1219   /// by the target to override the default.
1220   void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1221     PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
1222   }
1223
1224   /// setTargetDAGCombine - Targets should invoke this method for each target
1225   /// independent node that they want to provide a custom DAG combiner for by
1226   /// implementing the PerformDAGCombine virtual method.
1227   void setTargetDAGCombine(ISD::NodeType NT) {
1228     assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1229     TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
1230   }
1231
1232   /// setJumpBufSize - Set the target's required jmp_buf buffer size (in
1233   /// bytes); default is 200
1234   void setJumpBufSize(unsigned Size) {
1235     JumpBufSize = Size;
1236   }
1237
1238   /// setJumpBufAlignment - Set the target's required jmp_buf buffer
1239   /// alignment (in bytes); default is 0
1240   void setJumpBufAlignment(unsigned Align) {
1241     JumpBufAlignment = Align;
1242   }
1243
1244   /// setMinFunctionAlignment - Set the target's minimum function alignment (in
1245   /// log2(bytes))
1246   void setMinFunctionAlignment(unsigned Align) {
1247     MinFunctionAlignment = Align;
1248   }
1249
1250   /// setPrefFunctionAlignment - Set the target's preferred function alignment.
1251   /// This should be set if there is a performance benefit to
1252   /// higher-than-minimum alignment (in log2(bytes))
1253   void setPrefFunctionAlignment(unsigned Align) {
1254     PrefFunctionAlignment = Align;
1255   }
1256
1257   /// setPrefLoopAlignment - Set the target's preferred loop alignment. Default
1258   /// alignment is zero, it means the target does not care about loop alignment.
1259   /// The alignment is specified in log2(bytes).
1260   void setPrefLoopAlignment(unsigned Align) {
1261     PrefLoopAlignment = Align;
1262   }
1263
1264   /// setMinStackArgumentAlignment - Set the minimum stack alignment of an
1265   /// argument (in log2(bytes)).
1266   void setMinStackArgumentAlignment(unsigned Align) {
1267     MinStackArgumentAlignment = Align;
1268   }
1269
1270   /// setShouldFoldAtomicFences - Set if the target's implementation of the
1271   /// atomic operation intrinsics includes locking. Default is false.
1272   void setShouldFoldAtomicFences(bool fold) {
1273     ShouldFoldAtomicFences = fold;
1274   }
1275
1276   /// setInsertFencesForAtomic - Set if the DAG builder should
1277   /// automatically insert fences and reduce the order of atomic memory
1278   /// operations to Monotonic.
1279   void setInsertFencesForAtomic(bool fence) {
1280     InsertFencesForAtomic = fence;
1281   }
1282
1283 public:
1284   //===--------------------------------------------------------------------===//
1285   // Lowering methods - These methods must be implemented by targets so that
1286   // the SelectionDAGBuilder code knows how to lower these.
1287   //
1288
1289   /// LowerFormalArguments - This hook must be implemented to lower the
1290   /// incoming (formal) arguments, described by the Ins array, into the
1291   /// specified DAG. The implementation should fill in the InVals array
1292   /// with legal-type argument values, and return the resulting token
1293   /// chain value.
1294   ///
1295   virtual SDValue
1296     LowerFormalArguments(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
1297                          bool /*isVarArg*/,
1298                          const SmallVectorImpl<ISD::InputArg> &/*Ins*/,
1299                          DebugLoc /*dl*/, SelectionDAG &/*DAG*/,
1300                          SmallVectorImpl<SDValue> &/*InVals*/) const {
1301     llvm_unreachable("Not Implemented");
1302   }
1303
1304   struct ArgListEntry {
1305     SDValue Node;
1306     Type* Ty;
1307     bool isSExt  : 1;
1308     bool isZExt  : 1;
1309     bool isInReg : 1;
1310     bool isSRet  : 1;
1311     bool isNest  : 1;
1312     bool isByVal : 1;
1313     uint16_t Alignment;
1314
1315     ArgListEntry() : isSExt(false), isZExt(false), isInReg(false),
1316       isSRet(false), isNest(false), isByVal(false), Alignment(0) { }
1317   };
1318   typedef std::vector<ArgListEntry> ArgListTy;
1319
1320   /// CallLoweringInfo - This structure contains all information that is
1321   /// necessary for lowering calls. It is passed to TLI::LowerCallTo when the
1322   /// SelectionDAG builder needs to lower a call, and targets will see this
1323   /// struct in their LowerCall implementation.
1324   struct CallLoweringInfo {
1325     SDValue Chain;
1326     Type *RetTy;
1327     bool RetSExt           : 1;
1328     bool RetZExt           : 1;
1329     bool IsVarArg          : 1;
1330     bool IsInReg           : 1;
1331     bool DoesNotReturn     : 1;
1332     bool IsReturnValueUsed : 1;
1333
1334     // IsTailCall should be modified by implementations of
1335     // TargetLowering::LowerCall that perform tail call conversions.
1336     bool IsTailCall;
1337
1338     unsigned NumFixedArgs;
1339     CallingConv::ID CallConv;
1340     SDValue Callee;
1341     ArgListTy &Args;
1342     SelectionDAG &DAG;
1343     DebugLoc DL;
1344     ImmutableCallSite *CS;
1345     SmallVector<ISD::OutputArg, 32> Outs;
1346     SmallVector<SDValue, 32> OutVals;
1347     SmallVector<ISD::InputArg, 32> Ins;
1348
1349
1350     /// CallLoweringInfo - Constructs a call lowering context based on the
1351     /// ImmutableCallSite \p cs.
1352     CallLoweringInfo(SDValue chain, Type *retTy,
1353                      FunctionType *FTy, bool isTailCall, SDValue callee,
1354                      ArgListTy &args, SelectionDAG &dag, DebugLoc dl,
1355                      ImmutableCallSite &cs)
1356     : Chain(chain), RetTy(retTy), RetSExt(cs.paramHasAttr(0, Attribute::SExt)),
1357       RetZExt(cs.paramHasAttr(0, Attribute::ZExt)), IsVarArg(FTy->isVarArg()),
1358       IsInReg(cs.paramHasAttr(0, Attribute::InReg)),
1359       DoesNotReturn(cs.doesNotReturn()),
1360       IsReturnValueUsed(!cs.getInstruction()->use_empty()),
1361       IsTailCall(isTailCall), NumFixedArgs(FTy->getNumParams()),
1362       CallConv(cs.getCallingConv()), Callee(callee), Args(args), DAG(dag),
1363       DL(dl), CS(&cs) {}
1364
1365     /// CallLoweringInfo - Constructs a call lowering context based on the
1366     /// provided call information.
1367     CallLoweringInfo(SDValue chain, Type *retTy, bool retSExt, bool retZExt,
1368                      bool isVarArg, bool isInReg, unsigned numFixedArgs,
1369                      CallingConv::ID callConv, bool isTailCall,
1370                      bool doesNotReturn, bool isReturnValueUsed, SDValue callee,
1371                      ArgListTy &args, SelectionDAG &dag, DebugLoc dl)
1372     : Chain(chain), RetTy(retTy), RetSExt(retSExt), RetZExt(retZExt),
1373       IsVarArg(isVarArg), IsInReg(isInReg), DoesNotReturn(doesNotReturn),
1374       IsReturnValueUsed(isReturnValueUsed), IsTailCall(isTailCall),
1375       NumFixedArgs(numFixedArgs), CallConv(callConv), Callee(callee),
1376       Args(args), DAG(dag), DL(dl), CS(NULL) {}
1377   };
1378
1379   /// LowerCallTo - This function lowers an abstract call to a function into an
1380   /// actual call.  This returns a pair of operands.  The first element is the
1381   /// return value for the function (if RetTy is not VoidTy).  The second
1382   /// element is the outgoing token chain. It calls LowerCall to do the actual
1383   /// lowering.
1384   std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
1385
1386   /// LowerCall - This hook must be implemented to lower calls into the
1387   /// the specified DAG. The outgoing arguments to the call are described
1388   /// by the Outs array, and the values to be returned by the call are
1389   /// described by the Ins array. The implementation should fill in the
1390   /// InVals array with legal-type return values from the call, and return
1391   /// the resulting token chain value.
1392   virtual SDValue
1393     LowerCall(CallLoweringInfo &/*CLI*/,
1394               SmallVectorImpl<SDValue> &/*InVals*/) const {
1395     llvm_unreachable("Not Implemented");
1396   }
1397
1398   /// HandleByVal - Target-specific cleanup for formal ByVal parameters.
1399   virtual void HandleByVal(CCState *, unsigned &, unsigned) const {}
1400
1401   /// CanLowerReturn - This hook should be implemented to check whether the
1402   /// return values described by the Outs array can fit into the return
1403   /// registers.  If false is returned, an sret-demotion is performed.
1404   ///
1405   virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
1406                               MachineFunction &/*MF*/, bool /*isVarArg*/,
1407                const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
1408                LLVMContext &/*Context*/) const
1409   {
1410     // Return true by default to get preexisting behavior.
1411     return true;
1412   }
1413
1414   /// LowerReturn - This hook must be implemented to lower outgoing
1415   /// return values, described by the Outs array, into the specified
1416   /// DAG. The implementation should return the resulting token chain
1417   /// value.
1418   ///
1419   virtual SDValue
1420     LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
1421                 bool /*isVarArg*/,
1422                 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
1423                 const SmallVectorImpl<SDValue> &/*OutVals*/,
1424                 DebugLoc /*dl*/, SelectionDAG &/*DAG*/) const {
1425     llvm_unreachable("Not Implemented");
1426   }
1427
1428   /// isUsedByReturnOnly - Return true if result of the specified node is used
1429   /// by a return node only. It also compute and return the input chain for the
1430   /// tail call.
1431   /// This is used to determine whether it is possible
1432   /// to codegen a libcall as tail call at legalization time.
1433   virtual bool isUsedByReturnOnly(SDNode *, SDValue &Chain) const {
1434     return false;
1435   }
1436
1437   /// mayBeEmittedAsTailCall - Return true if the target may be able emit the
1438   /// call instruction as a tail call. This is used by optimization passes to
1439   /// determine if it's profitable to duplicate return instructions to enable
1440   /// tailcall optimization.
1441   virtual bool mayBeEmittedAsTailCall(CallInst *) const {
1442     return false;
1443   }
1444
1445   /// getTypeForExtArgOrReturn - Return the type that should be used to zero or
1446   /// sign extend a zeroext/signext integer argument or return value.
1447   /// FIXME: Most C calling convention requires the return type to be promoted,
1448   /// but this is not true all the time, e.g. i1 on x86-64. It is also not
1449   /// necessary for non-C calling conventions. The frontend should handle this
1450   /// and include all of the necessary information.
1451   virtual EVT getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1452                                        ISD::NodeType /*ExtendKind*/) const {
1453     EVT MinVT = getRegisterType(Context, MVT::i32);
1454     return VT.bitsLT(MinVT) ? MinVT : VT;
1455   }
1456
1457   /// LowerOperationWrapper - This callback is invoked by the type legalizer
1458   /// to legalize nodes with an illegal operand type but legal result types.
1459   /// It replaces the LowerOperation callback in the type Legalizer.
1460   /// The reason we can not do away with LowerOperation entirely is that
1461   /// LegalizeDAG isn't yet ready to use this callback.
1462   /// TODO: Consider merging with ReplaceNodeResults.
1463
1464   /// The target places new result values for the node in Results (their number
1465   /// and types must exactly match those of the original return values of
1466   /// the node), or leaves Results empty, which indicates that the node is not
1467   /// to be custom lowered after all.
1468   /// The default implementation calls LowerOperation.
1469   virtual void LowerOperationWrapper(SDNode *N,
1470                                      SmallVectorImpl<SDValue> &Results,
1471                                      SelectionDAG &DAG) const;
1472
1473   /// LowerOperation - This callback is invoked for operations that are
1474   /// unsupported by the target, which are registered to use 'custom' lowering,
1475   /// and whose defined values are all legal.
1476   /// If the target has no operations that require custom lowering, it need not
1477   /// implement this.  The default implementation of this aborts.
1478   virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
1479
1480   /// ReplaceNodeResults - This callback is invoked when a node result type is
1481   /// illegal for the target, and the operation was registered to use 'custom'
1482   /// lowering for that result type.  The target places new result values for
1483   /// the node in Results (their number and types must exactly match those of
1484   /// the original return values of the node), or leaves Results empty, which
1485   /// indicates that the node is not to be custom lowered after all.
1486   ///
1487   /// If the target has no operations that require custom lowering, it need not
1488   /// implement this.  The default implementation aborts.
1489   virtual void ReplaceNodeResults(SDNode * /*N*/,
1490                                   SmallVectorImpl<SDValue> &/*Results*/,
1491                                   SelectionDAG &/*DAG*/) const {
1492     llvm_unreachable("ReplaceNodeResults not implemented for this target!");
1493   }
1494
1495   /// getTargetNodeName() - This method returns the name of a target specific
1496   /// DAG node.
1497   virtual const char *getTargetNodeName(unsigned Opcode) const;
1498
1499   /// createFastISel - This method returns a target specific FastISel object,
1500   /// or null if the target does not support "fast" ISel.
1501   virtual FastISel *createFastISel(FunctionLoweringInfo &,
1502                                    const TargetLibraryInfo *) const {
1503     return 0;
1504   }
1505
1506   //===--------------------------------------------------------------------===//
1507   // Inline Asm Support hooks
1508   //
1509
1510   /// ExpandInlineAsm - This hook allows the target to expand an inline asm
1511   /// call to be explicit llvm code if it wants to.  This is useful for
1512   /// turning simple inline asms into LLVM intrinsics, which gives the
1513   /// compiler more information about the behavior of the code.
1514   virtual bool ExpandInlineAsm(CallInst *) const {
1515     return false;
1516   }
1517
1518   enum ConstraintType {
1519     C_Register,            // Constraint represents specific register(s).
1520     C_RegisterClass,       // Constraint represents any of register(s) in class.
1521     C_Memory,              // Memory constraint.
1522     C_Other,               // Something else.
1523     C_Unknown              // Unsupported constraint.
1524   };
1525
1526   enum ConstraintWeight {
1527     // Generic weights.
1528     CW_Invalid  = -1,     // No match.
1529     CW_Okay     = 0,      // Acceptable.
1530     CW_Good     = 1,      // Good weight.
1531     CW_Better   = 2,      // Better weight.
1532     CW_Best     = 3,      // Best weight.
1533
1534     // Well-known weights.
1535     CW_SpecificReg  = CW_Okay,    // Specific register operands.
1536     CW_Register     = CW_Good,    // Register operands.
1537     CW_Memory       = CW_Better,  // Memory operands.
1538     CW_Constant     = CW_Best,    // Constant operand.
1539     CW_Default      = CW_Okay     // Default or don't know type.
1540   };
1541
1542   /// AsmOperandInfo - This contains information for each constraint that we are
1543   /// lowering.
1544   struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
1545     /// ConstraintCode - This contains the actual string for the code, like "m".
1546     /// TargetLowering picks the 'best' code from ConstraintInfo::Codes that
1547     /// most closely matches the operand.
1548     std::string ConstraintCode;
1549
1550     /// ConstraintType - Information about the constraint code, e.g. Register,
1551     /// RegisterClass, Memory, Other, Unknown.
1552     TargetLowering::ConstraintType ConstraintType;
1553
1554     /// CallOperandval - If this is the result output operand or a
1555     /// clobber, this is null, otherwise it is the incoming operand to the
1556     /// CallInst.  This gets modified as the asm is processed.
1557     Value *CallOperandVal;
1558
1559     /// ConstraintVT - The ValueType for the operand value.
1560     EVT ConstraintVT;
1561
1562     /// isMatchingInputConstraint - Return true of this is an input operand that
1563     /// is a matching constraint like "4".
1564     bool isMatchingInputConstraint() const;
1565
1566     /// getMatchedOperand - If this is an input matching constraint, this method
1567     /// returns the output operand it matches.
1568     unsigned getMatchedOperand() const;
1569
1570     /// Copy constructor for copying from an AsmOperandInfo.
1571     AsmOperandInfo(const AsmOperandInfo &info)
1572       : InlineAsm::ConstraintInfo(info),
1573         ConstraintCode(info.ConstraintCode),
1574         ConstraintType(info.ConstraintType),
1575         CallOperandVal(info.CallOperandVal),
1576         ConstraintVT(info.ConstraintVT) {
1577     }
1578
1579     /// Copy constructor for copying from a ConstraintInfo.
1580     AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
1581       : InlineAsm::ConstraintInfo(info),
1582         ConstraintType(TargetLowering::C_Unknown),
1583         CallOperandVal(0), ConstraintVT(MVT::Other) {
1584     }
1585   };
1586
1587   typedef std::vector<AsmOperandInfo> AsmOperandInfoVector;
1588
1589   /// ParseConstraints - Split up the constraint string from the inline
1590   /// assembly value into the specific constraints and their prefixes,
1591   /// and also tie in the associated operand values.
1592   /// If this returns an empty vector, and if the constraint string itself
1593   /// isn't empty, there was an error parsing.
1594   virtual AsmOperandInfoVector ParseConstraints(ImmutableCallSite CS) const;
1595
1596   /// Examine constraint type and operand type and determine a weight value.
1597   /// The operand object must already have been set up with the operand type.
1598   virtual ConstraintWeight getMultipleConstraintMatchWeight(
1599       AsmOperandInfo &info, int maIndex) const;
1600
1601   /// Examine constraint string and operand type and determine a weight value.
1602   /// The operand object must already have been set up with the operand type.
1603   virtual ConstraintWeight getSingleConstraintMatchWeight(
1604       AsmOperandInfo &info, const char *constraint) const;
1605
1606   /// ComputeConstraintToUse - Determines the constraint code and constraint
1607   /// type to use for the specific AsmOperandInfo, setting
1608   /// OpInfo.ConstraintCode and OpInfo.ConstraintType.  If the actual operand
1609   /// being passed in is available, it can be passed in as Op, otherwise an
1610   /// empty SDValue can be passed.
1611   virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
1612                                       SDValue Op,
1613                                       SelectionDAG *DAG = 0) const;
1614
1615   /// getConstraintType - Given a constraint, return the type of constraint it
1616   /// is for this target.
1617   virtual ConstraintType getConstraintType(const std::string &Constraint) const;
1618
1619   /// getRegForInlineAsmConstraint - Given a physical register constraint (e.g.
1620   /// {edx}), return the register number and the register class for the
1621   /// register.
1622   ///
1623   /// Given a register class constraint, like 'r', if this corresponds directly
1624   /// to an LLVM register class, return a register of 0 and the register class
1625   /// pointer.
1626   ///
1627   /// This should only be used for C_Register constraints.  On error,
1628   /// this returns a register number of 0 and a null register class pointer..
1629   virtual std::pair<unsigned, const TargetRegisterClass*>
1630     getRegForInlineAsmConstraint(const std::string &Constraint,
1631                                  EVT VT) const;
1632
1633   /// LowerXConstraint - try to replace an X constraint, which matches anything,
1634   /// with another that has more specific requirements based on the type of the
1635   /// corresponding operand.  This returns null if there is no replacement to
1636   /// make.
1637   virtual const char *LowerXConstraint(EVT ConstraintVT) const;
1638
1639   /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
1640   /// vector.  If it is invalid, don't add anything to Ops.
1641   virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
1642                                             std::vector<SDValue> &Ops,
1643                                             SelectionDAG &DAG) const;
1644
1645   //===--------------------------------------------------------------------===//
1646   // Instruction Emitting Hooks
1647   //
1648
1649   // EmitInstrWithCustomInserter - This method should be implemented by targets
1650   // that mark instructions with the 'usesCustomInserter' flag.  These
1651   // instructions are special in various ways, which require special support to
1652   // insert.  The specified MachineInstr is created but not inserted into any
1653   // basic blocks, and this method is called to expand it into a sequence of
1654   // instructions, potentially also creating new basic blocks and control flow.
1655   virtual MachineBasicBlock *
1656     EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const;
1657
1658   /// AdjustInstrPostInstrSelection - This method should be implemented by
1659   /// targets that mark instructions with the 'hasPostISelHook' flag. These
1660   /// instructions must be adjusted after instruction selection by target hooks.
1661   /// e.g. To fill in optional defs for ARM 's' setting instructions.
1662   virtual void
1663   AdjustInstrPostInstrSelection(MachineInstr *MI, SDNode *Node) const;
1664
1665   //===--------------------------------------------------------------------===//
1666   // Addressing mode description hooks (used by LSR etc).
1667   //
1668
1669   /// GetAddrModeArguments - CodeGenPrepare sinks address calculations into the
1670   /// same BB as Load/Store instructions reading the address.  This allows as
1671   /// much computation as possible to be done in the address mode for that
1672   /// operand.  This hook lets targets also pass back when this should be done
1673   /// on intrinsics which load/store.
1674   virtual bool GetAddrModeArguments(IntrinsicInst *I,
1675                                     SmallVectorImpl<Value*> &Ops,
1676                                     Type *&AccessTy) const {
1677     return false;
1678   }
1679
1680   /// isLegalAddressingMode - Return true if the addressing mode represented by
1681   /// AM is legal for this target, for a load/store of the specified type.
1682   /// The type may be VoidTy, in which case only return true if the addressing
1683   /// mode is legal for a load/store of any legal type.
1684   /// TODO: Handle pre/postinc as well.
1685   virtual bool isLegalAddressingMode(const AddrMode &AM, Type *Ty) const;
1686
1687   /// isLegalICmpImmediate - Return true if the specified immediate is legal
1688   /// icmp immediate, that is the target has icmp instructions which can compare
1689   /// a register against the immediate without having to materialize the
1690   /// immediate into a register.
1691   virtual bool isLegalICmpImmediate(int64_t) const {
1692     return true;
1693   }
1694
1695   /// isLegalAddImmediate - Return true if the specified immediate is legal
1696   /// add immediate, that is the target has add instructions which can add
1697   /// a register with the immediate without having to materialize the
1698   /// immediate into a register.
1699   virtual bool isLegalAddImmediate(int64_t) const {
1700     return true;
1701   }
1702
1703   /// isTruncateFree - Return true if it's free to truncate a value of
1704   /// type Ty1 to type Ty2. e.g. On x86 it's free to truncate a i32 value in
1705   /// register EAX to i16 by referencing its sub-register AX.
1706   virtual bool isTruncateFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1707     return false;
1708   }
1709
1710   virtual bool isTruncateFree(EVT /*VT1*/, EVT /*VT2*/) const {
1711     return false;
1712   }
1713
1714   /// isZExtFree - Return true if any actual instruction that defines a
1715   /// value of type Ty1 implicitly zero-extends the value to Ty2 in the result
1716   /// register. This does not necessarily include registers defined in
1717   /// unknown ways, such as incoming arguments, or copies from unknown
1718   /// virtual registers. Also, if isTruncateFree(Ty2, Ty1) is true, this
1719   /// does not necessarily apply to truncate instructions. e.g. on x86-64,
1720   /// all instructions that define 32-bit values implicit zero-extend the
1721   /// result out to 64 bits.
1722   virtual bool isZExtFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1723     return false;
1724   }
1725
1726   virtual bool isZExtFree(EVT /*VT1*/, EVT /*VT2*/) const {
1727     return false;
1728   }
1729
1730   /// isZExtFree - Return true if zero-extending the specific node Val to type
1731   /// VT2 is free (either because it's implicitly zero-extended such as ARM
1732   /// ldrb / ldrh or because it's folded such as X86 zero-extending loads).
1733   virtual bool isZExtFree(SDValue Val, EVT VT2) const {
1734     return isZExtFree(Val.getValueType(), VT2);
1735   }
1736
1737   /// isFNegFree - Return true if an fneg operation is free to the point where
1738   /// it is never worthwhile to replace it with a bitwise operation.
1739   virtual bool isFNegFree(EVT) const {
1740     return false;
1741   }
1742
1743   /// isFAbsFree - Return true if an fneg operation is free to the point where
1744   /// it is never worthwhile to replace it with a bitwise operation.
1745   virtual bool isFAbsFree(EVT) const {
1746     return false;
1747   }
1748
1749   /// isFMAFasterThanMulAndAdd - Return true if an FMA operation is faster than
1750   /// a pair of mul and add instructions. fmuladd intrinsics will be expanded to
1751   /// FMAs when this method returns true (and FMAs are legal), otherwise fmuladd
1752   /// is expanded to mul + add.
1753   virtual bool isFMAFasterThanMulAndAdd(EVT) const {
1754     return false;
1755   }
1756
1757   /// isNarrowingProfitable - Return true if it's profitable to narrow
1758   /// operations of type VT1 to VT2. e.g. on x86, it's profitable to narrow
1759   /// from i32 to i8 but not from i32 to i16.
1760   virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
1761     return false;
1762   }
1763
1764   //===--------------------------------------------------------------------===//
1765   // Div utility functions
1766   //
1767   SDValue BuildExactSDIV(SDValue Op1, SDValue Op2, DebugLoc dl,
1768                          SelectionDAG &DAG) const;
1769   SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
1770                       std::vector<SDNode*> *Created) const;
1771   SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
1772                       std::vector<SDNode*> *Created) const;
1773
1774
1775   //===--------------------------------------------------------------------===//
1776   // Runtime Library hooks
1777   //
1778
1779   /// setLibcallName - Rename the default libcall routine name for the specified
1780   /// libcall.
1781   void setLibcallName(RTLIB::Libcall Call, const char *Name) {
1782     LibcallRoutineNames[Call] = Name;
1783   }
1784
1785   /// getLibcallName - Get the libcall routine name for the specified libcall.
1786   ///
1787   const char *getLibcallName(RTLIB::Libcall Call) const {
1788     return LibcallRoutineNames[Call];
1789   }
1790
1791   /// setCmpLibcallCC - Override the default CondCode to be used to test the
1792   /// result of the comparison libcall against zero.
1793   void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
1794     CmpLibcallCCs[Call] = CC;
1795   }
1796
1797   /// getCmpLibcallCC - Get the CondCode that's to be used to test the result of
1798   /// the comparison libcall against zero.
1799   ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
1800     return CmpLibcallCCs[Call];
1801   }
1802
1803   /// setLibcallCallingConv - Set the CallingConv that should be used for the
1804   /// specified libcall.
1805   void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
1806     LibcallCallingConvs[Call] = CC;
1807   }
1808
1809   /// getLibcallCallingConv - Get the CallingConv that should be used for the
1810   /// specified libcall.
1811   CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
1812     return LibcallCallingConvs[Call];
1813   }
1814
1815 private:
1816   const TargetMachine &TM;
1817   const DataLayout *TD;
1818   const TargetLoweringObjectFile &TLOF;
1819
1820   /// PointerTy - The type to use for pointers for the default address space,
1821   /// usually i32 or i64.
1822   ///
1823   MVT PointerTy;
1824
1825   /// IsLittleEndian - True if this is a little endian target.
1826   ///
1827   bool IsLittleEndian;
1828
1829   /// SelectIsExpensive - Tells the code generator not to expand operations
1830   /// into sequences that use the select operations if possible.
1831   bool SelectIsExpensive;
1832
1833   /// IntDivIsCheap - Tells the code generator not to expand integer divides by
1834   /// constants into a sequence of muls, adds, and shifts.  This is a hack until
1835   /// a real cost model is in place.  If we ever optimize for size, this will be
1836   /// set to true unconditionally.
1837   bool IntDivIsCheap;
1838
1839   /// BypassSlowDivMap - Tells the code generator to bypass slow divide or
1840   /// remainder instructions. For example, BypassSlowDivWidths[32,8] tells the
1841   /// code generator to bypass 32-bit integer div/rem with an 8-bit unsigned
1842   /// integer div/rem when the operands are positive and less than 256.
1843   DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
1844
1845   /// Pow2DivIsCheap - Tells the code generator that it shouldn't generate
1846   /// srl/add/sra for a signed divide by power of two, and let the target handle
1847   /// it.
1848   bool Pow2DivIsCheap;
1849
1850   /// JumpIsExpensive - Tells the code generator that it shouldn't generate
1851   /// extra flow control instructions and should attempt to combine flow
1852   /// control instructions via predication.
1853   bool JumpIsExpensive;
1854
1855   /// UseUnderscoreSetJmp - This target prefers to use _setjmp to implement
1856   /// llvm.setjmp.  Defaults to false.
1857   bool UseUnderscoreSetJmp;
1858
1859   /// UseUnderscoreLongJmp - This target prefers to use _longjmp to implement
1860   /// llvm.longjmp.  Defaults to false.
1861   bool UseUnderscoreLongJmp;
1862
1863   /// SupportJumpTables - Whether the target can generate code for jumptables.
1864   /// If it's not true, then each jumptable must be lowered into if-then-else's.
1865   bool SupportJumpTables;
1866
1867   /// MinimumJumpTableEntries - Number of blocks threshold to use jump tables.
1868   int MinimumJumpTableEntries;
1869
1870   /// BooleanContents - Information about the contents of the high-bits in
1871   /// boolean values held in a type wider than i1.  See getBooleanContents.
1872   BooleanContent BooleanContents;
1873   /// BooleanVectorContents - Information about the contents of the high-bits
1874   /// in boolean vector values when the element type is wider than i1.  See
1875   /// getBooleanContents.
1876   BooleanContent BooleanVectorContents;
1877
1878   /// SchedPreferenceInfo - The target scheduling preference: shortest possible
1879   /// total cycles or lowest register usage.
1880   Sched::Preference SchedPreferenceInfo;
1881
1882   /// JumpBufSize - The size, in bytes, of the target's jmp_buf buffers
1883   unsigned JumpBufSize;
1884
1885   /// JumpBufAlignment - The alignment, in bytes, of the target's jmp_buf
1886   /// buffers
1887   unsigned JumpBufAlignment;
1888
1889   /// MinStackArgumentAlignment - The minimum alignment that any argument
1890   /// on the stack needs to have.
1891   ///
1892   unsigned MinStackArgumentAlignment;
1893
1894   /// MinFunctionAlignment - The minimum function alignment (used when
1895   /// optimizing for size, and to prevent explicitly provided alignment
1896   /// from leading to incorrect code).
1897   ///
1898   unsigned MinFunctionAlignment;
1899
1900   /// PrefFunctionAlignment - The preferred function alignment (used when
1901   /// alignment unspecified and optimizing for speed).
1902   ///
1903   unsigned PrefFunctionAlignment;
1904
1905   /// PrefLoopAlignment - The preferred loop alignment.
1906   ///
1907   unsigned PrefLoopAlignment;
1908
1909   /// ShouldFoldAtomicFences - Whether fencing MEMBARRIER instructions should
1910   /// be folded into the enclosed atomic intrinsic instruction by the
1911   /// combiner.
1912   bool ShouldFoldAtomicFences;
1913
1914   /// InsertFencesForAtomic - Whether the DAG builder should automatically
1915   /// insert fences and reduce ordering for atomics.  (This will be set for
1916   /// for most architectures with weak memory ordering.)
1917   bool InsertFencesForAtomic;
1918
1919   /// StackPointerRegisterToSaveRestore - If set to a physical register, this
1920   /// specifies the register that llvm.savestack/llvm.restorestack should save
1921   /// and restore.
1922   unsigned StackPointerRegisterToSaveRestore;
1923
1924   /// ExceptionPointerRegister - If set to a physical register, this specifies
1925   /// the register that receives the exception address on entry to a landing
1926   /// pad.
1927   unsigned ExceptionPointerRegister;
1928
1929   /// ExceptionSelectorRegister - If set to a physical register, this specifies
1930   /// the register that receives the exception typeid on entry to a landing
1931   /// pad.
1932   unsigned ExceptionSelectorRegister;
1933
1934   /// RegClassForVT - This indicates the default register class to use for
1935   /// each ValueType the target supports natively.
1936   const TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
1937   unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
1938   EVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
1939
1940   /// RepRegClassForVT - This indicates the "representative" register class to
1941   /// use for each ValueType the target supports natively. This information is
1942   /// used by the scheduler to track register pressure. By default, the
1943   /// representative register class is the largest legal super-reg register
1944   /// class of the register class of the specified type. e.g. On x86, i8, i16,
1945   /// and i32's representative class would be GR32.
1946   const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
1947
1948   /// RepRegClassCostForVT - This indicates the "cost" of the "representative"
1949   /// register class for each ValueType. The cost is used by the scheduler to
1950   /// approximate register pressure.
1951   uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
1952
1953   /// TransformToType - For any value types we are promoting or expanding, this
1954   /// contains the value type that we are changing to.  For Expanded types, this
1955   /// contains one step of the expand (e.g. i64 -> i32), even if there are
1956   /// multiple steps required (e.g. i64 -> i16).  For types natively supported
1957   /// by the system, this holds the same type (e.g. i32 -> i32).
1958   EVT TransformToType[MVT::LAST_VALUETYPE];
1959
1960   /// OpActions - For each operation and each value type, keep a LegalizeAction
1961   /// that indicates how instruction selection should deal with the operation.
1962   /// Most operations are Legal (aka, supported natively by the target), but
1963   /// operations that are not should be described.  Note that operations on
1964   /// non-legal value types are not described here.
1965   uint8_t OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END];
1966
1967   /// LoadExtActions - For each load extension type and each value type,
1968   /// keep a LegalizeAction that indicates how instruction selection should deal
1969   /// with a load of a specific value type and extension type.
1970   uint8_t LoadExtActions[MVT::LAST_VALUETYPE][ISD::LAST_LOADEXT_TYPE];
1971
1972   /// TruncStoreActions - For each value type pair keep a LegalizeAction that
1973   /// indicates whether a truncating store of a specific value type and
1974   /// truncating type is legal.
1975   uint8_t TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
1976
1977   /// IndexedModeActions - For each indexed mode and each value type,
1978   /// keep a pair of LegalizeAction that indicates how instruction
1979   /// selection should deal with the load / store.  The first dimension is the
1980   /// value_type for the reference. The second dimension represents the various
1981   /// modes for load store.
1982   uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
1983
1984   /// CondCodeActions - For each condition code (ISD::CondCode) keep a
1985   /// LegalizeAction that indicates how instruction selection should
1986   /// deal with the condition code.
1987   /// Because each CC action takes up 2 bits, we need to have the array size
1988   /// be large enough to fit all of the value types. This can be done by
1989   /// dividing the MVT::LAST_VALUETYPE by 32 and adding one.
1990   uint64_t CondCodeActions[ISD::SETCC_INVALID][(MVT::LAST_VALUETYPE / 32) + 1];
1991
1992   ValueTypeActionImpl ValueTypeActions;
1993
1994 public:
1995   LegalizeKind
1996   getTypeConversion(LLVMContext &Context, EVT VT) const {
1997     // If this is a simple type, use the ComputeRegisterProp mechanism.
1998     if (VT.isSimple()) {
1999       assert((unsigned)VT.getSimpleVT().SimpleTy <
2000              array_lengthof(TransformToType));
2001       EVT NVT = TransformToType[VT.getSimpleVT().SimpleTy];
2002       LegalizeTypeAction LA = ValueTypeActions.getTypeAction(VT.getSimpleVT());
2003
2004       assert(
2005         (!(NVT.isSimple() && LA != TypeLegal) ||
2006          ValueTypeActions.getTypeAction(NVT.getSimpleVT()) != TypePromoteInteger)
2007          && "Promote may not follow Expand or Promote");
2008
2009       if (LA == TypeSplitVector)
2010         NVT = EVT::getVectorVT(Context, VT.getVectorElementType(),
2011                                VT.getVectorNumElements() / 2);
2012       return LegalizeKind(LA, NVT);
2013     }
2014
2015     // Handle Extended Scalar Types.
2016     if (!VT.isVector()) {
2017       assert(VT.isInteger() && "Float types must be simple");
2018       unsigned BitSize = VT.getSizeInBits();
2019       // First promote to a power-of-two size, then expand if necessary.
2020       if (BitSize < 8 || !isPowerOf2_32(BitSize)) {
2021         EVT NVT = VT.getRoundIntegerType(Context);
2022         assert(NVT != VT && "Unable to round integer VT");
2023         LegalizeKind NextStep = getTypeConversion(Context, NVT);
2024         // Avoid multi-step promotion.
2025         if (NextStep.first == TypePromoteInteger) return NextStep;
2026         // Return rounded integer type.
2027         return LegalizeKind(TypePromoteInteger, NVT);
2028       }
2029
2030       return LegalizeKind(TypeExpandInteger,
2031                           EVT::getIntegerVT(Context, VT.getSizeInBits()/2));
2032     }
2033
2034     // Handle vector types.
2035     unsigned NumElts = VT.getVectorNumElements();
2036     EVT EltVT = VT.getVectorElementType();
2037
2038     // Vectors with only one element are always scalarized.
2039     if (NumElts == 1)
2040       return LegalizeKind(TypeScalarizeVector, EltVT);
2041
2042     // Try to widen vector elements until a legal type is found.
2043     if (EltVT.isInteger()) {
2044       // Vectors with a number of elements that is not a power of two are always
2045       // widened, for example <3 x float> -> <4 x float>.
2046       if (!VT.isPow2VectorType()) {
2047         NumElts = (unsigned)NextPowerOf2(NumElts);
2048         EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts);
2049         return LegalizeKind(TypeWidenVector, NVT);
2050       }
2051
2052       // Examine the element type.
2053       LegalizeKind LK = getTypeConversion(Context, EltVT);
2054
2055       // If type is to be expanded, split the vector.
2056       //  <4 x i140> -> <2 x i140>
2057       if (LK.first == TypeExpandInteger)
2058         return LegalizeKind(TypeSplitVector,
2059                             EVT::getVectorVT(Context, EltVT, NumElts / 2));
2060
2061       // Promote the integer element types until a legal vector type is found
2062       // or until the element integer type is too big. If a legal type was not
2063       // found, fallback to the usual mechanism of widening/splitting the
2064       // vector.
2065       while (1) {
2066         // Increase the bitwidth of the element to the next pow-of-two
2067         // (which is greater than 8 bits).
2068         EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits()
2069                                  ).getRoundIntegerType(Context);
2070
2071         // Stop trying when getting a non-simple element type.
2072         // Note that vector elements may be greater than legal vector element
2073         // types. Example: X86 XMM registers hold 64bit element on 32bit systems.
2074         if (!EltVT.isSimple()) break;
2075
2076         // Build a new vector type and check if it is legal.
2077         MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
2078         // Found a legal promoted vector type.
2079         if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal)
2080           return LegalizeKind(TypePromoteInteger,
2081                               EVT::getVectorVT(Context, EltVT, NumElts));
2082       }
2083     }
2084
2085     // Try to widen the vector until a legal type is found.
2086     // If there is no wider legal type, split the vector.
2087     while (1) {
2088       // Round up to the next power of 2.
2089       NumElts = (unsigned)NextPowerOf2(NumElts);
2090
2091       // If there is no simple vector type with this many elements then there
2092       // cannot be a larger legal vector type.  Note that this assumes that
2093       // there are no skipped intermediate vector types in the simple types.
2094       if (!EltVT.isSimple()) break;
2095       MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
2096       if (LargerVector == MVT()) break;
2097
2098       // If this type is legal then widen the vector.
2099       if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal)
2100         return LegalizeKind(TypeWidenVector, LargerVector);
2101     }
2102
2103     // Widen odd vectors to next power of two.
2104     if (!VT.isPow2VectorType()) {
2105       EVT NVT = VT.getPow2VectorType(Context);
2106       return LegalizeKind(TypeWidenVector, NVT);
2107     }
2108
2109     // Vectors with illegal element types are expanded.
2110     EVT NVT = EVT::getVectorVT(Context, EltVT, VT.getVectorNumElements() / 2);
2111     return LegalizeKind(TypeSplitVector, NVT);
2112   }
2113
2114 private:
2115   std::vector<std::pair<EVT, const TargetRegisterClass*> > AvailableRegClasses;
2116
2117   /// TargetDAGCombineArray - Targets can specify ISD nodes that they would
2118   /// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(),
2119   /// which sets a bit in this array.
2120   unsigned char
2121   TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
2122
2123   /// PromoteToType - For operations that must be promoted to a specific type,
2124   /// this holds the destination type.  This map should be sparse, so don't hold
2125   /// it as an array.
2126   ///
2127   /// Targets add entries to this map with AddPromotedToType(..), clients access
2128   /// this with getTypeToPromoteTo(..).
2129   std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
2130     PromoteToType;
2131
2132   /// LibcallRoutineNames - Stores the name each libcall.
2133   ///
2134   const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
2135
2136   /// CmpLibcallCCs - The ISD::CondCode that should be used to test the result
2137   /// of each of the comparison libcall against zero.
2138   ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
2139
2140   /// LibcallCallingConvs - Stores the CallingConv that should be used for each
2141   /// libcall.
2142   CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
2143
2144 protected:
2145   /// When lowering \@llvm.memset this field specifies the maximum number of
2146   /// store operations that may be substituted for the call to memset. Targets
2147   /// must set this value based on the cost threshold for that target. Targets
2148   /// should assume that the memset will be done using as many of the largest
2149   /// store operations first, followed by smaller ones, if necessary, per
2150   /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
2151   /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
2152   /// store.  This only applies to setting a constant array of a constant size.
2153   /// @brief Specify maximum number of store instructions per memset call.
2154   unsigned maxStoresPerMemset;
2155
2156   /// Maximum number of stores operations that may be substituted for the call
2157   /// to memset, used for functions with OptSize attribute.
2158   unsigned maxStoresPerMemsetOptSize;
2159
2160   /// When lowering \@llvm.memcpy this field specifies the maximum number of
2161   /// store operations that may be substituted for a call to memcpy. Targets
2162   /// must set this value based on the cost threshold for that target. Targets
2163   /// should assume that the memcpy will be done using as many of the largest
2164   /// store operations first, followed by smaller ones, if necessary, per
2165   /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
2166   /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
2167   /// and one 1-byte store. This only applies to copying a constant array of
2168   /// constant size.
2169   /// @brief Specify maximum bytes of store instructions per memcpy call.
2170   unsigned maxStoresPerMemcpy;
2171
2172   /// Maximum number of store operations that may be substituted for a call
2173   /// to memcpy, used for functions with OptSize attribute.
2174   unsigned maxStoresPerMemcpyOptSize;
2175
2176   /// When lowering \@llvm.memmove this field specifies the maximum number of
2177   /// store instructions that may be substituted for a call to memmove. Targets
2178   /// must set this value based on the cost threshold for that target. Targets
2179   /// should assume that the memmove will be done using as many of the largest
2180   /// store operations first, followed by smaller ones, if necessary, per
2181   /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
2182   /// with 8-bit alignment would result in nine 1-byte stores.  This only
2183   /// applies to copying a constant array of constant size.
2184   /// @brief Specify maximum bytes of store instructions per memmove call.
2185   unsigned maxStoresPerMemmove;
2186
2187   /// Maximum number of store instructions that may be substituted for a call
2188   /// to memmove, used for functions with OpSize attribute.
2189   unsigned maxStoresPerMemmoveOptSize;
2190
2191   /// This field specifies whether the target can benefit from code placement
2192   /// optimization.
2193   bool benefitFromCodePlacementOpt;
2194
2195   /// predictableSelectIsExpensive - Tells the code generator that select is
2196   /// more expensive than a branch if the branch is usually predicted right.
2197   bool predictableSelectIsExpensive;
2198
2199 private:
2200   /// isLegalRC - Return true if the value types that can be represented by the
2201   /// specified register class are all legal.
2202   bool isLegalRC(const TargetRegisterClass *RC) const;
2203 };
2204
2205 /// GetReturnInfo - Given an LLVM IR type and return type attributes,
2206 /// compute the return value EVTs and flags, and optionally also
2207 /// the offsets, if the return value is being lowered to memory.
2208 void GetReturnInfo(Type* ReturnType, Attribute attr,
2209                    SmallVectorImpl<ISD::OutputArg> &Outs,
2210                    const TargetLowering &TLI);
2211
2212 } // end llvm namespace
2213
2214 #endif