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