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