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