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