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