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