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