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