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