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