Add back r201608, r201622, r201624 and r201625
[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 significantly cheaper to shift a vector by a uniform
1189   /// scalar than by an amount which will vary across each lane. On x86, for
1190   /// example, there is a "psllw" instruction for the former case, but no simple
1191   /// instruction for a general "a << b" operation on vectors.
1192   virtual bool isVectorShiftByScalarCheap(Type *Ty) const {
1193     return false;
1194   }
1195
1196   /// Return true if it's free to truncate a value of type Ty1 to type
1197   /// Ty2. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
1198   /// by referencing its sub-register AX.
1199   virtual bool isTruncateFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1200     return false;
1201   }
1202
1203   /// Return true if a truncation from Ty1 to Ty2 is permitted when deciding
1204   /// whether a call is in tail position. Typically this means that both results
1205   /// would be assigned to the same register or stack slot, but it could mean
1206   /// the target performs adequate checks of its own before proceeding with the
1207   /// tail call.
1208   virtual bool allowTruncateForTailCall(Type * /*Ty1*/, Type * /*Ty2*/) const {
1209     return false;
1210   }
1211
1212   virtual bool isTruncateFree(EVT /*VT1*/, EVT /*VT2*/) const {
1213     return false;
1214   }
1215
1216   /// Return true if any actual instruction that defines a value of type Ty1
1217   /// implicitly zero-extends the value to Ty2 in the result register.
1218   ///
1219   /// This does not necessarily include registers defined in unknown ways, such
1220   /// as incoming arguments, or copies from unknown virtual registers. Also, if
1221   /// isTruncateFree(Ty2, Ty1) is true, this does not necessarily apply to
1222   /// truncate instructions. e.g. on x86-64, all instructions that define 32-bit
1223   /// values implicit zero-extend the result out to 64 bits.
1224   virtual bool isZExtFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1225     return false;
1226   }
1227
1228   virtual bool isZExtFree(EVT /*VT1*/, EVT /*VT2*/) const {
1229     return false;
1230   }
1231
1232   /// Return true if the target supplies and combines to a paired load
1233   /// two loaded values of type LoadedType next to each other in memory.
1234   /// RequiredAlignment gives the minimal alignment constraints that must be met
1235   /// to be able to select this paired load.
1236   ///
1237   /// This information is *not* used to generate actual paired loads, but it is
1238   /// used to generate a sequence of loads that is easier to combine into a
1239   /// paired load.
1240   /// For instance, something like this:
1241   /// a = load i64* addr
1242   /// b = trunc i64 a to i32
1243   /// c = lshr i64 a, 32
1244   /// d = trunc i64 c to i32
1245   /// will be optimized into:
1246   /// b = load i32* addr1
1247   /// d = load i32* addr2
1248   /// Where addr1 = addr2 +/- sizeof(i32).
1249   ///
1250   /// In other words, unless the target performs a post-isel load combining,
1251   /// this information should not be provided because it will generate more
1252   /// loads.
1253   virtual bool hasPairedLoad(Type * /*LoadedType*/,
1254                              unsigned & /*RequiredAligment*/) const {
1255     return false;
1256   }
1257
1258   virtual bool hasPairedLoad(EVT /*LoadedType*/,
1259                              unsigned & /*RequiredAligment*/) const {
1260     return false;
1261   }
1262
1263   /// Return true if zero-extending the specific node Val to type VT2 is free
1264   /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
1265   /// because it's folded such as X86 zero-extending loads).
1266   virtual bool isZExtFree(SDValue Val, EVT VT2) const {
1267     return isZExtFree(Val.getValueType(), VT2);
1268   }
1269
1270   /// Return true if an fneg operation is free to the point where it is never
1271   /// worthwhile to replace it with a bitwise operation.
1272   virtual bool isFNegFree(EVT VT) const {
1273     assert(VT.isFloatingPoint());
1274     return false;
1275   }
1276
1277   /// Return true if an fabs operation is free to the point where it is never
1278   /// worthwhile to replace it with a bitwise operation.
1279   virtual bool isFAbsFree(EVT VT) const {
1280     assert(VT.isFloatingPoint());
1281     return false;
1282   }
1283
1284   /// Return true if an FMA operation is faster than a pair of fmul and fadd
1285   /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
1286   /// returns true, otherwise fmuladd is expanded to fmul + fadd.
1287   ///
1288   /// NOTE: This may be called before legalization on types for which FMAs are
1289   /// not legal, but should return true if those types will eventually legalize
1290   /// to types that support FMAs. After legalization, it will only be called on
1291   /// types that support FMAs (via Legal or Custom actions)
1292   virtual bool isFMAFasterThanFMulAndFAdd(EVT) const {
1293     return false;
1294   }
1295
1296   /// Return true if it's profitable to narrow operations of type VT1 to
1297   /// VT2. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
1298   /// i32 to i16.
1299   virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
1300     return false;
1301   }
1302
1303   /// \brief Return true if it is beneficial to convert a load of a constant to
1304   /// just the constant itself.
1305   /// On some targets it might be more efficient to use a combination of
1306   /// arithmetic instructions to materialize the constant instead of loading it
1307   /// from a constant pool.
1308   virtual bool shouldConvertConstantLoadToIntImm(const APInt &Imm,
1309                                                  Type *Ty) const {
1310     return false;
1311   }
1312   //===--------------------------------------------------------------------===//
1313   // Runtime Library hooks
1314   //
1315
1316   /// Rename the default libcall routine name for the specified libcall.
1317   void setLibcallName(RTLIB::Libcall Call, const char *Name) {
1318     LibcallRoutineNames[Call] = Name;
1319   }
1320
1321   /// Get the libcall routine name for the specified libcall.
1322   const char *getLibcallName(RTLIB::Libcall Call) const {
1323     return LibcallRoutineNames[Call];
1324   }
1325
1326   /// Override the default CondCode to be used to test the result of the
1327   /// comparison libcall against zero.
1328   void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
1329     CmpLibcallCCs[Call] = CC;
1330   }
1331
1332   /// Get the CondCode that's to be used to test the result of the comparison
1333   /// libcall against zero.
1334   ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
1335     return CmpLibcallCCs[Call];
1336   }
1337
1338   /// Set the CallingConv that should be used for the specified libcall.
1339   void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
1340     LibcallCallingConvs[Call] = CC;
1341   }
1342
1343   /// Get the CallingConv that should be used for the specified libcall.
1344   CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
1345     return LibcallCallingConvs[Call];
1346   }
1347
1348   void getNameWithPrefix(SmallVectorImpl<char> &Name, const GlobalValue *GV,
1349                          Mangler &Mang, bool MayAlwaysUsePrivate = false) const;
1350   MCSymbol *getSymbol(const GlobalValue *GV, Mangler &Mang) const;
1351
1352 private:
1353   const TargetMachine &TM;
1354   const DataLayout *DL;
1355   const TargetLoweringObjectFile &TLOF;
1356
1357   /// True if this is a little endian target.
1358   bool IsLittleEndian;
1359
1360   /// Tells the code generator not to expand operations into sequences that use
1361   /// the select operations if possible.
1362   bool SelectIsExpensive;
1363
1364   /// Tells the code generator that the target has multiple (allocatable)
1365   /// condition registers that can be used to store the results of comparisons
1366   /// for use by selects and conditional branches. With multiple condition
1367   /// registers, the code generator will not aggressively sink comparisons into
1368   /// the blocks of their users.
1369   bool HasMultipleConditionRegisters;
1370
1371   /// Tells the code generator not to expand integer divides by constants into a
1372   /// sequence of muls, adds, and shifts.  This is a hack until a real cost
1373   /// model is in place.  If we ever optimize for size, this will be set to true
1374   /// unconditionally.
1375   bool IntDivIsCheap;
1376
1377   /// Tells the code generator to bypass slow divide or remainder
1378   /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
1379   /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
1380   /// div/rem when the operands are positive and less than 256.
1381   DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
1382
1383   /// Tells the code generator that it shouldn't generate srl/add/sra for a
1384   /// signed divide by power of two, and let the target handle it.
1385   bool Pow2DivIsCheap;
1386
1387   /// Tells the code generator that it shouldn't generate extra flow control
1388   /// instructions and should attempt to combine flow control instructions via
1389   /// predication.
1390   bool JumpIsExpensive;
1391
1392   /// This target prefers to use _setjmp to implement llvm.setjmp.
1393   ///
1394   /// Defaults to false.
1395   bool UseUnderscoreSetJmp;
1396
1397   /// This target prefers to use _longjmp to implement llvm.longjmp.
1398   ///
1399   /// Defaults to false.
1400   bool UseUnderscoreLongJmp;
1401
1402   /// Whether the target can generate code for jumptables.  If it's not true,
1403   /// then each jumptable must be lowered into if-then-else's.
1404   bool SupportJumpTables;
1405
1406   /// Number of blocks threshold to use jump tables.
1407   int MinimumJumpTableEntries;
1408
1409   /// Information about the contents of the high-bits in boolean values held in
1410   /// a type wider than i1. See getBooleanContents.
1411   BooleanContent BooleanContents;
1412
1413   /// Information about the contents of the high-bits in boolean vector values
1414   /// when the element type is wider than i1. See getBooleanContents.
1415   BooleanContent BooleanVectorContents;
1416
1417   /// The target scheduling preference: shortest possible total cycles or lowest
1418   /// register usage.
1419   Sched::Preference SchedPreferenceInfo;
1420
1421   /// The size, in bytes, of the target's jmp_buf buffers
1422   unsigned JumpBufSize;
1423
1424   /// The alignment, in bytes, of the target's jmp_buf buffers
1425   unsigned JumpBufAlignment;
1426
1427   /// The minimum alignment that any argument on the stack needs to have.
1428   unsigned MinStackArgumentAlignment;
1429
1430   /// The minimum function alignment (used when optimizing for size, and to
1431   /// prevent explicitly provided alignment from leading to incorrect code).
1432   unsigned MinFunctionAlignment;
1433
1434   /// The preferred function alignment (used when alignment unspecified and
1435   /// optimizing for speed).
1436   unsigned PrefFunctionAlignment;
1437
1438   /// The preferred loop alignment.
1439   unsigned PrefLoopAlignment;
1440
1441   /// Whether the DAG builder should automatically insert fences and reduce
1442   /// ordering for atomics.  (This will be set for for most architectures with
1443   /// weak memory ordering.)
1444   bool InsertFencesForAtomic;
1445
1446   /// If set to a physical register, this specifies the register that
1447   /// llvm.savestack/llvm.restorestack should save and restore.
1448   unsigned StackPointerRegisterToSaveRestore;
1449
1450   /// If set to a physical register, this specifies the register that receives
1451   /// the exception address on entry to a landing pad.
1452   unsigned ExceptionPointerRegister;
1453
1454   /// If set to a physical register, this specifies the register that receives
1455   /// the exception typeid on entry to a landing pad.
1456   unsigned ExceptionSelectorRegister;
1457
1458   /// This indicates the default register class to use for each ValueType the
1459   /// target supports natively.
1460   const TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
1461   unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
1462   MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
1463
1464   /// This indicates the "representative" register class to use for each
1465   /// ValueType the target supports natively. This information is used by the
1466   /// scheduler to track register pressure. By default, the representative
1467   /// register class is the largest legal super-reg register class of the
1468   /// register class of the specified type. e.g. On x86, i8, i16, and i32's
1469   /// representative class would be GR32.
1470   const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
1471
1472   /// This indicates the "cost" of the "representative" register class for each
1473   /// ValueType. The cost is used by the scheduler to approximate register
1474   /// pressure.
1475   uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
1476
1477   /// For any value types we are promoting or expanding, this contains the value
1478   /// type that we are changing to.  For Expanded types, this contains one step
1479   /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
1480   /// (e.g. i64 -> i16).  For types natively supported by the system, this holds
1481   /// the same type (e.g. i32 -> i32).
1482   MVT TransformToType[MVT::LAST_VALUETYPE];
1483
1484   /// For each operation and each value type, keep a LegalizeAction that
1485   /// indicates how instruction selection should deal with the operation.  Most
1486   /// operations are Legal (aka, supported natively by the target), but
1487   /// operations that are not should be described.  Note that operations on
1488   /// non-legal value types are not described here.
1489   uint8_t OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END];
1490
1491   /// For each load extension type and each value type, keep a LegalizeAction
1492   /// that indicates how instruction selection should deal with a load of a
1493   /// specific value type and extension type.
1494   uint8_t LoadExtActions[MVT::LAST_VALUETYPE][ISD::LAST_LOADEXT_TYPE];
1495
1496   /// For each value type pair keep a LegalizeAction that indicates whether a
1497   /// truncating store of a specific value type and truncating type is legal.
1498   uint8_t TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
1499
1500   /// For each indexed mode and each value type, keep a pair of LegalizeAction
1501   /// that indicates how instruction selection should deal with the load /
1502   /// store.
1503   ///
1504   /// The first dimension is the value_type for the reference. The second
1505   /// dimension represents the various modes for load store.
1506   uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
1507
1508   /// For each condition code (ISD::CondCode) keep a LegalizeAction that
1509   /// indicates how instruction selection should deal with the condition code.
1510   ///
1511   /// Because each CC action takes up 2 bits, we need to have the array size be
1512   /// large enough to fit all of the value types. This can be done by rounding
1513   /// up the MVT::LAST_VALUETYPE value to the next multiple of 16.
1514   uint32_t CondCodeActions[ISD::SETCC_INVALID][(MVT::LAST_VALUETYPE + 15) / 16];
1515
1516   ValueTypeActionImpl ValueTypeActions;
1517
1518 public:
1519   LegalizeKind
1520   getTypeConversion(LLVMContext &Context, EVT VT) const {
1521     // If this is a simple type, use the ComputeRegisterProp mechanism.
1522     if (VT.isSimple()) {
1523       MVT SVT = VT.getSimpleVT();
1524       assert((unsigned)SVT.SimpleTy < array_lengthof(TransformToType));
1525       MVT NVT = TransformToType[SVT.SimpleTy];
1526       LegalizeTypeAction LA = ValueTypeActions.getTypeAction(SVT);
1527
1528       assert(
1529         (LA == TypeLegal ||
1530          ValueTypeActions.getTypeAction(NVT) != TypePromoteInteger)
1531          && "Promote may not follow Expand or Promote");
1532
1533       if (LA == TypeSplitVector)
1534         return LegalizeKind(LA, EVT::getVectorVT(Context,
1535                                                  SVT.getVectorElementType(),
1536                                                  SVT.getVectorNumElements()/2));
1537       if (LA == TypeScalarizeVector)
1538         return LegalizeKind(LA, SVT.getVectorElementType());
1539       return LegalizeKind(LA, NVT);
1540     }
1541
1542     // Handle Extended Scalar Types.
1543     if (!VT.isVector()) {
1544       assert(VT.isInteger() && "Float types must be simple");
1545       unsigned BitSize = VT.getSizeInBits();
1546       // First promote to a power-of-two size, then expand if necessary.
1547       if (BitSize < 8 || !isPowerOf2_32(BitSize)) {
1548         EVT NVT = VT.getRoundIntegerType(Context);
1549         assert(NVT != VT && "Unable to round integer VT");
1550         LegalizeKind NextStep = getTypeConversion(Context, NVT);
1551         // Avoid multi-step promotion.
1552         if (NextStep.first == TypePromoteInteger) return NextStep;
1553         // Return rounded integer type.
1554         return LegalizeKind(TypePromoteInteger, NVT);
1555       }
1556
1557       return LegalizeKind(TypeExpandInteger,
1558                           EVT::getIntegerVT(Context, VT.getSizeInBits()/2));
1559     }
1560
1561     // Handle vector types.
1562     unsigned NumElts = VT.getVectorNumElements();
1563     EVT EltVT = VT.getVectorElementType();
1564
1565     // Vectors with only one element are always scalarized.
1566     if (NumElts == 1)
1567       return LegalizeKind(TypeScalarizeVector, EltVT);
1568
1569     // Try to widen vector elements until the element type is a power of two and
1570     // promote it to a legal type later on, for example:
1571     // <3 x i8> -> <4 x i8> -> <4 x i32>
1572     if (EltVT.isInteger()) {
1573       // Vectors with a number of elements that is not a power of two are always
1574       // widened, for example <3 x i8> -> <4 x i8>.
1575       if (!VT.isPow2VectorType()) {
1576         NumElts = (unsigned)NextPowerOf2(NumElts);
1577         EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts);
1578         return LegalizeKind(TypeWidenVector, NVT);
1579       }
1580
1581       // Examine the element type.
1582       LegalizeKind LK = getTypeConversion(Context, EltVT);
1583
1584       // If type is to be expanded, split the vector.
1585       //  <4 x i140> -> <2 x i140>
1586       if (LK.first == TypeExpandInteger)
1587         return LegalizeKind(TypeSplitVector,
1588                             EVT::getVectorVT(Context, EltVT, NumElts / 2));
1589
1590       // Promote the integer element types until a legal vector type is found
1591       // or until the element integer type is too big. If a legal type was not
1592       // found, fallback to the usual mechanism of widening/splitting the
1593       // vector.
1594       EVT OldEltVT = EltVT;
1595       while (1) {
1596         // Increase the bitwidth of the element to the next pow-of-two
1597         // (which is greater than 8 bits).
1598         EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits()
1599                                  ).getRoundIntegerType(Context);
1600
1601         // Stop trying when getting a non-simple element type.
1602         // Note that vector elements may be greater than legal vector element
1603         // types. Example: X86 XMM registers hold 64bit element on 32bit
1604         // systems.
1605         if (!EltVT.isSimple()) break;
1606
1607         // Build a new vector type and check if it is legal.
1608         MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1609         // Found a legal promoted vector type.
1610         if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal)
1611           return LegalizeKind(TypePromoteInteger,
1612                               EVT::getVectorVT(Context, EltVT, NumElts));
1613       }
1614
1615       // Reset the type to the unexpanded type if we did not find a legal vector
1616       // type with a promoted vector element type.
1617       EltVT = OldEltVT;
1618     }
1619
1620     // Try to widen the vector until a legal type is found.
1621     // If there is no wider legal type, split the vector.
1622     while (1) {
1623       // Round up to the next power of 2.
1624       NumElts = (unsigned)NextPowerOf2(NumElts);
1625
1626       // If there is no simple vector type with this many elements then there
1627       // cannot be a larger legal vector type.  Note that this assumes that
1628       // there are no skipped intermediate vector types in the simple types.
1629       if (!EltVT.isSimple()) break;
1630       MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1631       if (LargerVector == MVT()) break;
1632
1633       // If this type is legal then widen the vector.
1634       if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal)
1635         return LegalizeKind(TypeWidenVector, LargerVector);
1636     }
1637
1638     // Widen odd vectors to next power of two.
1639     if (!VT.isPow2VectorType()) {
1640       EVT NVT = VT.getPow2VectorType(Context);
1641       return LegalizeKind(TypeWidenVector, NVT);
1642     }
1643
1644     // Vectors with illegal element types are expanded.
1645     EVT NVT = EVT::getVectorVT(Context, EltVT, VT.getVectorNumElements() / 2);
1646     return LegalizeKind(TypeSplitVector, NVT);
1647   }
1648
1649 private:
1650   std::vector<std::pair<MVT, const TargetRegisterClass*> > AvailableRegClasses;
1651
1652   /// Targets can specify ISD nodes that they would like PerformDAGCombine
1653   /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
1654   /// array.
1655   unsigned char
1656   TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
1657
1658   /// For operations that must be promoted to a specific type, this holds the
1659   /// destination type.  This map should be sparse, so don't hold it as an
1660   /// array.
1661   ///
1662   /// Targets add entries to this map with AddPromotedToType(..), clients access
1663   /// this with getTypeToPromoteTo(..).
1664   std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
1665     PromoteToType;
1666
1667   /// Stores the name each libcall.
1668   const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
1669
1670   /// The ISD::CondCode that should be used to test the result of each of the
1671   /// comparison libcall against zero.
1672   ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
1673
1674   /// Stores the CallingConv that should be used for each libcall.
1675   CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
1676
1677 protected:
1678   /// \brief Specify maximum number of store instructions per memset call.
1679   ///
1680   /// When lowering \@llvm.memset this field specifies the maximum number of
1681   /// store operations that may be substituted for the call to memset. Targets
1682   /// must set this value based on the cost threshold for that target. Targets
1683   /// should assume that the memset will be done using as many of the largest
1684   /// store operations first, followed by smaller ones, if necessary, per
1685   /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
1686   /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
1687   /// store.  This only applies to setting a constant array of a constant size.
1688   unsigned MaxStoresPerMemset;
1689
1690   /// Maximum number of stores operations that may be substituted for the call
1691   /// to memset, used for functions with OptSize attribute.
1692   unsigned MaxStoresPerMemsetOptSize;
1693
1694   /// \brief Specify maximum bytes of store instructions per memcpy call.
1695   ///
1696   /// When lowering \@llvm.memcpy this field specifies the maximum number of
1697   /// store operations that may be substituted for a call to memcpy. Targets
1698   /// must set this value based on the cost threshold for that target. Targets
1699   /// should assume that the memcpy will be done using as many of the largest
1700   /// store operations first, followed by smaller ones, if necessary, per
1701   /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
1702   /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
1703   /// and one 1-byte store. This only applies to copying a constant array of
1704   /// constant size.
1705   unsigned MaxStoresPerMemcpy;
1706
1707   /// Maximum number of store operations that may be substituted for a call to
1708   /// memcpy, used for functions with OptSize attribute.
1709   unsigned MaxStoresPerMemcpyOptSize;
1710
1711   /// \brief Specify maximum bytes of store instructions per memmove call.
1712   ///
1713   /// When lowering \@llvm.memmove this field specifies the maximum number of
1714   /// store instructions that may be substituted for a call to memmove. Targets
1715   /// must set this value based on the cost threshold for that target. Targets
1716   /// should assume that the memmove will be done using as many of the largest
1717   /// store operations first, followed by smaller ones, if necessary, per
1718   /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
1719   /// with 8-bit alignment would result in nine 1-byte stores.  This only
1720   /// applies to copying a constant array of constant size.
1721   unsigned MaxStoresPerMemmove;
1722
1723   /// Maximum number of store instructions that may be substituted for a call to
1724   /// memmove, used for functions with OpSize attribute.
1725   unsigned MaxStoresPerMemmoveOptSize;
1726
1727   /// Tells the code generator that select is more expensive than a branch if
1728   /// the branch is usually predicted right.
1729   bool PredictableSelectIsExpensive;
1730
1731 protected:
1732   /// Return true if the value types that can be represented by the specified
1733   /// register class are all legal.
1734   bool isLegalRC(const TargetRegisterClass *RC) const;
1735
1736   /// Replace/modify any TargetFrameIndex operands with a targte-dependent
1737   /// sequence of memory operands that is recognized by PrologEpilogInserter.
1738   MachineBasicBlock *emitPatchPoint(MachineInstr *MI, MachineBasicBlock *MBB) const;
1739 };
1740
1741 /// This class defines information used to lower LLVM code to legal SelectionDAG
1742 /// operators that the target instruction selector can accept natively.
1743 ///
1744 /// This class also defines callbacks that targets must implement to lower
1745 /// target-specific constructs to SelectionDAG operators.
1746 class TargetLowering : public TargetLoweringBase {
1747   TargetLowering(const TargetLowering&) LLVM_DELETED_FUNCTION;
1748   void operator=(const TargetLowering&) LLVM_DELETED_FUNCTION;
1749
1750 public:
1751   /// NOTE: The constructor takes ownership of TLOF.
1752   explicit TargetLowering(const TargetMachine &TM,
1753                           const TargetLoweringObjectFile *TLOF);
1754
1755   /// Returns true by value, base pointer and offset pointer and addressing mode
1756   /// by reference if the node's address can be legally represented as
1757   /// pre-indexed load / store address.
1758   virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
1759                                          SDValue &/*Offset*/,
1760                                          ISD::MemIndexedMode &/*AM*/,
1761                                          SelectionDAG &/*DAG*/) const {
1762     return false;
1763   }
1764
1765   /// Returns true by value, base pointer and offset pointer and addressing mode
1766   /// by reference if this node can be combined with a load / store to form a
1767   /// post-indexed load / store.
1768   virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
1769                                           SDValue &/*Base*/,
1770                                           SDValue &/*Offset*/,
1771                                           ISD::MemIndexedMode &/*AM*/,
1772                                           SelectionDAG &/*DAG*/) const {
1773     return false;
1774   }
1775
1776   /// Return the entry encoding for a jump table in the current function.  The
1777   /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
1778   virtual unsigned getJumpTableEncoding() const;
1779
1780   virtual const MCExpr *
1781   LowerCustomJumpTableEntry(const MachineJumpTableInfo * /*MJTI*/,
1782                             const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
1783                             MCContext &/*Ctx*/) const {
1784     llvm_unreachable("Need to implement this hook if target has custom JTIs");
1785   }
1786
1787   /// Returns relocation base for the given PIC jumptable.
1788   virtual SDValue getPICJumpTableRelocBase(SDValue Table,
1789                                            SelectionDAG &DAG) const;
1790
1791   /// This returns the relocation base for the given PIC jumptable, the same as
1792   /// getPICJumpTableRelocBase, but as an MCExpr.
1793   virtual const MCExpr *
1794   getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
1795                                unsigned JTI, MCContext &Ctx) const;
1796
1797   /// Return true if folding a constant offset with the given GlobalAddress is
1798   /// legal.  It is frequently not legal in PIC relocation models.
1799   virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
1800
1801   bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
1802                             SDValue &Chain) const;
1803
1804   void softenSetCCOperands(SelectionDAG &DAG, EVT VT,
1805                            SDValue &NewLHS, SDValue &NewRHS,
1806                            ISD::CondCode &CCCode, SDLoc DL) const;
1807
1808   /// Returns a pair of (return value, chain).
1809   std::pair<SDValue, SDValue> makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC,
1810                                           EVT RetVT, const SDValue *Ops,
1811                                           unsigned NumOps, bool isSigned,
1812                                           SDLoc dl, bool doesNotReturn = false,
1813                                           bool isReturnValueUsed = true) const;
1814
1815   //===--------------------------------------------------------------------===//
1816   // TargetLowering Optimization Methods
1817   //
1818
1819   /// A convenience struct that encapsulates a DAG, and two SDValues for
1820   /// returning information from TargetLowering to its clients that want to
1821   /// combine.
1822   struct TargetLoweringOpt {
1823     SelectionDAG &DAG;
1824     bool LegalTys;
1825     bool LegalOps;
1826     SDValue Old;
1827     SDValue New;
1828
1829     explicit TargetLoweringOpt(SelectionDAG &InDAG,
1830                                bool LT, bool LO) :
1831       DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
1832
1833     bool LegalTypes() const { return LegalTys; }
1834     bool LegalOperations() const { return LegalOps; }
1835
1836     bool CombineTo(SDValue O, SDValue N) {
1837       Old = O;
1838       New = N;
1839       return true;
1840     }
1841
1842     /// Check to see if the specified operand of the specified instruction is a
1843     /// constant integer.  If so, check to see if there are any bits set in the
1844     /// constant that are not demanded.  If so, shrink the constant and return
1845     /// true.
1846     bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded);
1847
1848     /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.  This
1849     /// uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
1850     /// generalized for targets with other types of implicit widening casts.
1851     bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
1852                           SDLoc dl);
1853   };
1854
1855   /// Look at Op.  At this point, we know that only the DemandedMask bits of the
1856   /// result of Op are ever used downstream.  If we can use this information to
1857   /// simplify Op, create a new simplified DAG node and return true, returning
1858   /// the original and new nodes in Old and New.  Otherwise, analyze the
1859   /// expression and return a mask of KnownOne and KnownZero bits for the
1860   /// expression (used to simplify the caller).  The KnownZero/One bits may only
1861   /// be accurate for those bits in the DemandedMask.
1862   bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
1863                             APInt &KnownZero, APInt &KnownOne,
1864                             TargetLoweringOpt &TLO, unsigned Depth = 0) const;
1865
1866   /// Determine which of the bits specified in Mask are known to be either zero
1867   /// or one and return them in the KnownZero/KnownOne bitsets.
1868   virtual void computeMaskedBitsForTargetNode(const SDValue Op,
1869                                               APInt &KnownZero,
1870                                               APInt &KnownOne,
1871                                               const SelectionDAG &DAG,
1872                                               unsigned Depth = 0) const;
1873
1874   /// This method can be implemented by targets that want to expose additional
1875   /// information about sign bits to the DAG Combiner.
1876   virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
1877                                                    unsigned Depth = 0) const;
1878
1879   struct DAGCombinerInfo {
1880     void *DC;  // The DAG Combiner object.
1881     CombineLevel Level;
1882     bool CalledByLegalizer;
1883   public:
1884     SelectionDAG &DAG;
1885
1886     DAGCombinerInfo(SelectionDAG &dag, CombineLevel level,  bool cl, void *dc)
1887       : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
1888
1889     bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
1890     bool isBeforeLegalizeOps() const { return Level < AfterLegalizeVectorOps; }
1891     bool isAfterLegalizeVectorOps() const {
1892       return Level == AfterLegalizeDAG;
1893     }
1894     CombineLevel getDAGCombineLevel() { return Level; }
1895     bool isCalledByLegalizer() const { return CalledByLegalizer; }
1896
1897     void AddToWorklist(SDNode *N);
1898     void RemoveFromWorklist(SDNode *N);
1899     SDValue CombineTo(SDNode *N, const std::vector<SDValue> &To,
1900                       bool AddTo = true);
1901     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
1902     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
1903
1904     void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
1905   };
1906
1907   /// Try to simplify a setcc built with the specified operands and cc. If it is
1908   /// unable to simplify it, return a null SDValue.
1909   SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
1910                           ISD::CondCode Cond, bool foldBooleans,
1911                           DAGCombinerInfo &DCI, SDLoc dl) const;
1912
1913   /// Returns true (and the GlobalValue and the offset) if the node is a
1914   /// GlobalAddress + offset.
1915   virtual bool
1916   isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
1917
1918   /// This method will be invoked for all target nodes and for any
1919   /// target-independent nodes that the target has registered with invoke it
1920   /// for.
1921   ///
1922   /// The semantics are as follows:
1923   /// Return Value:
1924   ///   SDValue.Val == 0   - No change was made
1925   ///   SDValue.Val == N   - N was replaced, is dead, and is already handled.
1926   ///   otherwise          - N should be replaced by the returned Operand.
1927   ///
1928   /// In addition, methods provided by DAGCombinerInfo may be used to perform
1929   /// more complex transformations.
1930   ///
1931   virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
1932
1933   /// Return true if the target has native support for the specified value type
1934   /// and it is 'desirable' to use the type for the given node type. e.g. On x86
1935   /// i16 is legal, but undesirable since i16 instruction encodings are longer
1936   /// and some i16 instructions are slow.
1937   virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
1938     // By default, assume all legal types are desirable.
1939     return isTypeLegal(VT);
1940   }
1941
1942   /// Return true if it is profitable for dag combiner to transform a floating
1943   /// point op of specified opcode to a equivalent op of an integer
1944   /// type. e.g. f32 load -> i32 load can be profitable on ARM.
1945   virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
1946                                                  EVT /*VT*/) const {
1947     return false;
1948   }
1949
1950   /// This method query the target whether it is beneficial for dag combiner to
1951   /// promote the specified node. If true, it should return the desired
1952   /// promotion type by reference.
1953   virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
1954     return false;
1955   }
1956
1957   //===--------------------------------------------------------------------===//
1958   // Lowering methods - These methods must be implemented by targets so that
1959   // the SelectionDAGBuilder code knows how to lower these.
1960   //
1961
1962   /// This hook must be implemented to lower the incoming (formal) arguments,
1963   /// described by the Ins array, into the specified DAG. The implementation
1964   /// should fill in the InVals array with legal-type argument values, and
1965   /// return the resulting token chain value.
1966   ///
1967   virtual SDValue
1968     LowerFormalArguments(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
1969                          bool /*isVarArg*/,
1970                          const SmallVectorImpl<ISD::InputArg> &/*Ins*/,
1971                          SDLoc /*dl*/, SelectionDAG &/*DAG*/,
1972                          SmallVectorImpl<SDValue> &/*InVals*/) const {
1973     llvm_unreachable("Not Implemented");
1974   }
1975
1976   struct ArgListEntry {
1977     SDValue Node;
1978     Type* Ty;
1979     bool isSExt     : 1;
1980     bool isZExt     : 1;
1981     bool isInReg    : 1;
1982     bool isSRet     : 1;
1983     bool isNest     : 1;
1984     bool isByVal    : 1;
1985     bool isInAlloca : 1;
1986     bool isReturned : 1;
1987     uint16_t Alignment;
1988
1989     ArgListEntry() : isSExt(false), isZExt(false), isInReg(false),
1990       isSRet(false), isNest(false), isByVal(false), isInAlloca(false),
1991       isReturned(false), Alignment(0) { }
1992
1993     void setAttributes(ImmutableCallSite *CS, unsigned AttrIdx);
1994   };
1995   typedef std::vector<ArgListEntry> ArgListTy;
1996
1997   /// This structure contains all information that is necessary for lowering
1998   /// calls. It is passed to TLI::LowerCallTo when the SelectionDAG builder
1999   /// needs to lower a call, and targets will see this struct in their LowerCall
2000   /// implementation.
2001   struct CallLoweringInfo {
2002     SDValue Chain;
2003     Type *RetTy;
2004     bool RetSExt           : 1;
2005     bool RetZExt           : 1;
2006     bool IsVarArg          : 1;
2007     bool IsInReg           : 1;
2008     bool DoesNotReturn     : 1;
2009     bool IsReturnValueUsed : 1;
2010
2011     // IsTailCall should be modified by implementations of
2012     // TargetLowering::LowerCall that perform tail call conversions.
2013     bool IsTailCall;
2014
2015     unsigned NumFixedArgs;
2016     CallingConv::ID CallConv;
2017     SDValue Callee;
2018     ArgListTy &Args;
2019     SelectionDAG &DAG;
2020     SDLoc DL;
2021     ImmutableCallSite *CS;
2022     SmallVector<ISD::OutputArg, 32> Outs;
2023     SmallVector<SDValue, 32> OutVals;
2024     SmallVector<ISD::InputArg, 32> Ins;
2025
2026
2027     /// Constructs a call lowering context based on the ImmutableCallSite \p cs.
2028     CallLoweringInfo(SDValue chain, Type *retTy,
2029                      FunctionType *FTy, bool isTailCall, SDValue callee,
2030                      ArgListTy &args, SelectionDAG &dag, SDLoc dl,
2031                      ImmutableCallSite &cs)
2032     : Chain(chain), RetTy(retTy), RetSExt(cs.paramHasAttr(0, Attribute::SExt)),
2033       RetZExt(cs.paramHasAttr(0, Attribute::ZExt)), IsVarArg(FTy->isVarArg()),
2034       IsInReg(cs.paramHasAttr(0, Attribute::InReg)),
2035       DoesNotReturn(cs.doesNotReturn()),
2036       IsReturnValueUsed(!cs.getInstruction()->use_empty()),
2037       IsTailCall(isTailCall), NumFixedArgs(FTy->getNumParams()),
2038       CallConv(cs.getCallingConv()), Callee(callee), Args(args), DAG(dag),
2039       DL(dl), CS(&cs) {}
2040
2041     /// Constructs a call lowering context based on the provided call
2042     /// information.
2043     CallLoweringInfo(SDValue chain, Type *retTy, bool retSExt, bool retZExt,
2044                      bool isVarArg, bool isInReg, unsigned numFixedArgs,
2045                      CallingConv::ID callConv, bool isTailCall,
2046                      bool doesNotReturn, bool isReturnValueUsed, SDValue callee,
2047                      ArgListTy &args, SelectionDAG &dag, SDLoc dl)
2048     : Chain(chain), RetTy(retTy), RetSExt(retSExt), RetZExt(retZExt),
2049       IsVarArg(isVarArg), IsInReg(isInReg), DoesNotReturn(doesNotReturn),
2050       IsReturnValueUsed(isReturnValueUsed), IsTailCall(isTailCall),
2051       NumFixedArgs(numFixedArgs), CallConv(callConv), Callee(callee),
2052       Args(args), DAG(dag), DL(dl), CS(NULL) {}
2053   };
2054
2055   /// This function lowers an abstract call to a function into an actual call.
2056   /// This returns a pair of operands.  The first element is the return value
2057   /// for the function (if RetTy is not VoidTy).  The second element is the
2058   /// outgoing token chain. It calls LowerCall to do the actual lowering.
2059   std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
2060
2061   /// This hook must be implemented to lower calls into the the specified
2062   /// DAG. The outgoing arguments to the call are described by the Outs array,
2063   /// and the values to be returned by the call are described by the Ins
2064   /// array. The implementation should fill in the InVals array with legal-type
2065   /// return values from the call, and return the resulting token chain value.
2066   virtual SDValue
2067     LowerCall(CallLoweringInfo &/*CLI*/,
2068               SmallVectorImpl<SDValue> &/*InVals*/) const {
2069     llvm_unreachable("Not Implemented");
2070   }
2071
2072   /// Target-specific cleanup for formal ByVal parameters.
2073   virtual void HandleByVal(CCState *, unsigned &, unsigned) const {}
2074
2075   /// This hook should be implemented to check whether the return values
2076   /// described by the Outs array can fit into the return registers.  If false
2077   /// is returned, an sret-demotion is performed.
2078   virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
2079                               MachineFunction &/*MF*/, bool /*isVarArg*/,
2080                const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
2081                LLVMContext &/*Context*/) const
2082   {
2083     // Return true by default to get preexisting behavior.
2084     return true;
2085   }
2086
2087   /// This hook must be implemented to lower outgoing return values, described
2088   /// by the Outs array, into the specified DAG. The implementation should
2089   /// return the resulting token chain value.
2090   virtual SDValue
2091     LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
2092                 bool /*isVarArg*/,
2093                 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
2094                 const SmallVectorImpl<SDValue> &/*OutVals*/,
2095                 SDLoc /*dl*/, SelectionDAG &/*DAG*/) const {
2096     llvm_unreachable("Not Implemented");
2097   }
2098
2099   /// Return true if result of the specified node is used by a return node
2100   /// only. It also compute and return the input chain for the tail call.
2101   ///
2102   /// This is used to determine whether it is possible to codegen a libcall as
2103   /// tail call at legalization time.
2104   virtual bool isUsedByReturnOnly(SDNode *, SDValue &/*Chain*/) const {
2105     return false;
2106   }
2107
2108   /// Return true if the target may be able emit the call instruction as a tail
2109   /// call. This is used by optimization passes to determine if it's profitable
2110   /// to duplicate return instructions to enable tailcall optimization.
2111   virtual bool mayBeEmittedAsTailCall(CallInst *) const {
2112     return false;
2113   }
2114
2115   /// Return the type that should be used to zero or sign extend a
2116   /// zeroext/signext integer argument or return value.  FIXME: Most C calling
2117   /// convention requires the return type to be promoted, but this is not true
2118   /// all the time, e.g. i1 on x86-64. It is also not necessary for non-C
2119   /// calling conventions. The frontend should handle this and include all of
2120   /// the necessary information.
2121   virtual MVT getTypeForExtArgOrReturn(MVT VT,
2122                                        ISD::NodeType /*ExtendKind*/) const {
2123     MVT MinVT = getRegisterType(MVT::i32);
2124     return VT.bitsLT(MinVT) ? MinVT : VT;
2125   }
2126
2127   /// Returns a 0 terminated array of registers that can be safely used as
2128   /// scratch registers.
2129   virtual const uint16_t *getScratchRegisters(CallingConv::ID CC) const {
2130     return NULL;
2131   }
2132
2133   /// This callback is used to prepare for a volatile or atomic load.
2134   /// It takes a chain node as input and returns the chain for the load itself.
2135   ///
2136   /// Having a callback like this is necessary for targets like SystemZ,
2137   /// which allows a CPU to reuse the result of a previous load indefinitely,
2138   /// even if a cache-coherent store is performed by another CPU.  The default
2139   /// implementation does nothing.
2140   virtual SDValue prepareVolatileOrAtomicLoad(SDValue Chain, SDLoc DL,
2141                                               SelectionDAG &DAG) const {
2142     return Chain;
2143   }
2144
2145   /// This callback is invoked by the type legalizer to legalize nodes with an
2146   /// illegal operand type but legal result types.  It replaces the
2147   /// LowerOperation callback in the type Legalizer.  The reason we can not do
2148   /// away with LowerOperation entirely is that LegalizeDAG isn't yet ready to
2149   /// use this callback.
2150   ///
2151   /// TODO: Consider merging with ReplaceNodeResults.
2152   ///
2153   /// The target places new result values for the node in Results (their number
2154   /// and types must exactly match those of the original return values of
2155   /// the node), or leaves Results empty, which indicates that the node is not
2156   /// to be custom lowered after all.
2157   /// The default implementation calls LowerOperation.
2158   virtual void LowerOperationWrapper(SDNode *N,
2159                                      SmallVectorImpl<SDValue> &Results,
2160                                      SelectionDAG &DAG) const;
2161
2162   /// This callback is invoked for operations that are unsupported by the
2163   /// target, which are registered to use 'custom' lowering, and whose defined
2164   /// values are all legal.  If the target has no operations that require custom
2165   /// lowering, it need not implement this.  The default implementation of this
2166   /// aborts.
2167   virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
2168
2169   /// This callback is invoked when a node result type is illegal for the
2170   /// target, and the operation was registered to use 'custom' lowering for that
2171   /// result type.  The target places new result values for the node in Results
2172   /// (their number and types must exactly match those of the original return
2173   /// values of the node), or leaves Results empty, which indicates that the
2174   /// node is not to be custom lowered after all.
2175   ///
2176   /// If the target has no operations that require custom lowering, it need not
2177   /// implement this.  The default implementation aborts.
2178   virtual void ReplaceNodeResults(SDNode * /*N*/,
2179                                   SmallVectorImpl<SDValue> &/*Results*/,
2180                                   SelectionDAG &/*DAG*/) const {
2181     llvm_unreachable("ReplaceNodeResults not implemented for this target!");
2182   }
2183
2184   /// This method returns the name of a target specific DAG node.
2185   virtual const char *getTargetNodeName(unsigned Opcode) const;
2186
2187   /// This method returns a target specific FastISel object, or null if the
2188   /// target does not support "fast" ISel.
2189   virtual FastISel *createFastISel(FunctionLoweringInfo &,
2190                                    const TargetLibraryInfo *) const {
2191     return 0;
2192   }
2193
2194
2195   bool verifyReturnAddressArgumentIsConstant(SDValue Op,
2196                                              SelectionDAG &DAG) const;
2197
2198   //===--------------------------------------------------------------------===//
2199   // Inline Asm Support hooks
2200   //
2201
2202   /// This hook allows the target to expand an inline asm call to be explicit
2203   /// llvm code if it wants to.  This is useful for turning simple inline asms
2204   /// into LLVM intrinsics, which gives the compiler more information about the
2205   /// behavior of the code.
2206   virtual bool ExpandInlineAsm(CallInst *) const {
2207     return false;
2208   }
2209
2210   enum ConstraintType {
2211     C_Register,            // Constraint represents specific register(s).
2212     C_RegisterClass,       // Constraint represents any of register(s) in class.
2213     C_Memory,              // Memory constraint.
2214     C_Other,               // Something else.
2215     C_Unknown              // Unsupported constraint.
2216   };
2217
2218   enum ConstraintWeight {
2219     // Generic weights.
2220     CW_Invalid  = -1,     // No match.
2221     CW_Okay     = 0,      // Acceptable.
2222     CW_Good     = 1,      // Good weight.
2223     CW_Better   = 2,      // Better weight.
2224     CW_Best     = 3,      // Best weight.
2225
2226     // Well-known weights.
2227     CW_SpecificReg  = CW_Okay,    // Specific register operands.
2228     CW_Register     = CW_Good,    // Register operands.
2229     CW_Memory       = CW_Better,  // Memory operands.
2230     CW_Constant     = CW_Best,    // Constant operand.
2231     CW_Default      = CW_Okay     // Default or don't know type.
2232   };
2233
2234   /// This contains information for each constraint that we are lowering.
2235   struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
2236     /// This contains the actual string for the code, like "m".  TargetLowering
2237     /// picks the 'best' code from ConstraintInfo::Codes that most closely
2238     /// matches the operand.
2239     std::string ConstraintCode;
2240
2241     /// Information about the constraint code, e.g. Register, RegisterClass,
2242     /// Memory, Other, Unknown.
2243     TargetLowering::ConstraintType ConstraintType;
2244
2245     /// If this is the result output operand or a clobber, this is null,
2246     /// otherwise it is the incoming operand to the CallInst.  This gets
2247     /// modified as the asm is processed.
2248     Value *CallOperandVal;
2249
2250     /// The ValueType for the operand value.
2251     MVT ConstraintVT;
2252
2253     /// Return true of this is an input operand that is a matching constraint
2254     /// like "4".
2255     bool isMatchingInputConstraint() const;
2256
2257     /// If this is an input matching constraint, this method returns the output
2258     /// operand it matches.
2259     unsigned getMatchedOperand() const;
2260
2261     /// Copy constructor for copying from an AsmOperandInfo.
2262     AsmOperandInfo(const AsmOperandInfo &info)
2263       : InlineAsm::ConstraintInfo(info),
2264         ConstraintCode(info.ConstraintCode),
2265         ConstraintType(info.ConstraintType),
2266         CallOperandVal(info.CallOperandVal),
2267         ConstraintVT(info.ConstraintVT) {
2268     }
2269
2270     /// Copy constructor for copying from a ConstraintInfo.
2271     AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
2272       : InlineAsm::ConstraintInfo(info),
2273         ConstraintType(TargetLowering::C_Unknown),
2274         CallOperandVal(0), ConstraintVT(MVT::Other) {
2275     }
2276   };
2277
2278   typedef std::vector<AsmOperandInfo> AsmOperandInfoVector;
2279
2280   /// Split up the constraint string from the inline assembly value into the
2281   /// specific constraints and their prefixes, and also tie in the associated
2282   /// operand values.  If this returns an empty vector, and if the constraint
2283   /// string itself isn't empty, there was an error parsing.
2284   virtual AsmOperandInfoVector ParseConstraints(ImmutableCallSite CS) const;
2285
2286   /// Examine constraint type and operand type and determine a weight value.
2287   /// The operand object must already have been set up with the operand type.
2288   virtual ConstraintWeight getMultipleConstraintMatchWeight(
2289       AsmOperandInfo &info, int maIndex) const;
2290
2291   /// Examine constraint string and operand type and determine a weight value.
2292   /// The operand object must already have been set up with the operand type.
2293   virtual ConstraintWeight getSingleConstraintMatchWeight(
2294       AsmOperandInfo &info, const char *constraint) const;
2295
2296   /// Determines the constraint code and constraint type to use for the specific
2297   /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
2298   /// If the actual operand being passed in is available, it can be passed in as
2299   /// Op, otherwise an empty SDValue can be passed.
2300   virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
2301                                       SDValue Op,
2302                                       SelectionDAG *DAG = 0) const;
2303
2304   /// Given a constraint, return the type of constraint it is for this target.
2305   virtual ConstraintType getConstraintType(const std::string &Constraint) const;
2306
2307   /// Given a physical register constraint (e.g.  {edx}), return the register
2308   /// number and the register class for the register.
2309   ///
2310   /// Given a register class constraint, like 'r', if this corresponds directly
2311   /// to an LLVM register class, return a register of 0 and the register class
2312   /// pointer.
2313   ///
2314   /// This should only be used for C_Register constraints.  On error, this
2315   /// returns a register number of 0 and a null register class pointer..
2316   virtual std::pair<unsigned, const TargetRegisterClass*>
2317     getRegForInlineAsmConstraint(const std::string &Constraint,
2318                                  MVT VT) const;
2319
2320   /// Try to replace an X constraint, which matches anything, with another that
2321   /// has more specific requirements based on the type of the corresponding
2322   /// operand.  This returns null if there is no replacement to make.
2323   virtual const char *LowerXConstraint(EVT ConstraintVT) const;
2324
2325   /// Lower the specified operand into the Ops vector.  If it is invalid, don't
2326   /// add anything to Ops.
2327   virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
2328                                             std::vector<SDValue> &Ops,
2329                                             SelectionDAG &DAG) const;
2330
2331   //===--------------------------------------------------------------------===//
2332   // Div utility functions
2333   //
2334   SDValue BuildExactSDIV(SDValue Op1, SDValue Op2, SDLoc dl,
2335                          SelectionDAG &DAG) const;
2336   SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
2337                       std::vector<SDNode*> *Created) const;
2338   SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
2339                       std::vector<SDNode*> *Created) const;
2340
2341   //===--------------------------------------------------------------------===//
2342   // Instruction Emitting Hooks
2343   //
2344
2345   /// This method should be implemented by targets that mark instructions with
2346   /// the 'usesCustomInserter' flag.  These instructions are special in various
2347   /// ways, which require special support to insert.  The specified MachineInstr
2348   /// is created but not inserted into any basic blocks, and this method is
2349   /// called to expand it into a sequence of instructions, potentially also
2350   /// creating new basic blocks and control flow.
2351   virtual MachineBasicBlock *
2352     EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const;
2353
2354   /// This method should be implemented by targets that mark instructions with
2355   /// the 'hasPostISelHook' flag. These instructions must be adjusted after
2356   /// instruction selection by target hooks.  e.g. To fill in optional defs for
2357   /// ARM 's' setting instructions.
2358   virtual void
2359   AdjustInstrPostInstrSelection(MachineInstr *MI, SDNode *Node) const;
2360 };
2361
2362 /// Given an LLVM IR type and return type attributes, compute the return value
2363 /// EVTs and flags, and optionally also the offsets, if the return value is
2364 /// being lowered to memory.
2365 void GetReturnInfo(Type* ReturnType, AttributeSet attr,
2366                    SmallVectorImpl<ISD::OutputArg> &Outs,
2367                    const TargetLowering &TLI);
2368
2369 } // end llvm namespace
2370
2371 #endif