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