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