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