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