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