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