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