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