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