1 //===- llvm/CodeGen/TargetLowering.h - Target Lowering Info -----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file describes how to lower LLVM code to machine code.  This has two
11 /// main components:
12 ///
13 ///  1. Which ValueTypes are natively supported by the target.
14 ///  2. Which operations are supported for supported ValueTypes.
15 ///  3. Cost thresholds for alternative implementations of certain operations.
16 ///
17 /// In addition it has a few other components, like information about FP
18 /// immediates.
19 ///
20 //===----------------------------------------------------------------------===//
21 
22 #ifndef LLVM_CODEGEN_TARGETLOWERING_H
23 #define LLVM_CODEGEN_TARGETLOWERING_H
24 
25 #include "llvm/ADT/APInt.h"
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/RuntimeLibcalls.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/CodeGen/SelectionDAGNodes.h"
36 #include "llvm/CodeGen/TargetCallingConv.h"
37 #include "llvm/CodeGen/ValueTypes.h"
38 #include "llvm/IR/Attributes.h"
39 #include "llvm/IR/CallingConv.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Function.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/Support/Alignment.h"
49 #include "llvm/Support/AtomicOrdering.h"
50 #include "llvm/Support/Casting.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MachineValueType.h"
53 #include <algorithm>
54 #include <cassert>
55 #include <climits>
56 #include <cstdint>
57 #include <iterator>
58 #include <map>
59 #include <string>
60 #include <utility>
61 #include <vector>
62 
63 namespace llvm {
64 
65 class BranchProbability;
66 class CCState;
67 class CCValAssign;
68 class Constant;
69 class FastISel;
70 class FunctionLoweringInfo;
71 class GlobalValue;
72 class GISelKnownBits;
73 class IntrinsicInst;
74 struct KnownBits;
75 class LegacyDivergenceAnalysis;
76 class LLVMContext;
77 class MachineBasicBlock;
78 class MachineFunction;
79 class MachineInstr;
80 class MachineJumpTableInfo;
81 class MachineLoop;
82 class MachineRegisterInfo;
83 class MCContext;
84 class MCExpr;
85 class Module;
86 class ProfileSummaryInfo;
87 class TargetLibraryInfo;
88 class TargetMachine;
89 class TargetRegisterClass;
90 class TargetRegisterInfo;
91 class TargetTransformInfo;
92 class Value;
93 
94 namespace Sched {
95 
96   enum Preference {
97     None,             // No preference
98     Source,           // Follow source order.
99     RegPressure,      // Scheduling for lowest register pressure.
100     Hybrid,           // Scheduling for both latency and register pressure.
101     ILP,              // Scheduling for ILP in low register pressure mode.
102     VLIW              // Scheduling for VLIW targets.
103   };
104 
105 } // end namespace Sched
106 
107 // MemOp models a memory operation, either memset or memcpy/memmove.
108 struct MemOp {
109 private:
110   // Shared
111   uint64_t Size;
112   bool DstAlignCanChange; // true if destination alignment can satisfy any
113                           // constraint.
114   Align DstAlign;         // Specified alignment of the memory operation.
115 
116   bool AllowOverlap;
117   // memset only
118   bool IsMemset;   // If setthis memory operation is a memset.
119   bool ZeroMemset; // If set clears out memory with zeros.
120   // memcpy only
121   bool MemcpyStrSrc; // Indicates whether the memcpy source is an in-register
122                      // constant so it does not need to be loaded.
123   Align SrcAlign;    // Inferred alignment of the source or default value if the
124                      // memory operation does not need to load the value.
125 public:
126   static MemOp Copy(uint64_t Size, bool DstAlignCanChange, Align DstAlign,
127                     Align SrcAlign, bool IsVolatile,
128                     bool MemcpyStrSrc = false) {
129     MemOp Op;
130     Op.Size = Size;
131     Op.DstAlignCanChange = DstAlignCanChange;
132     Op.DstAlign = DstAlign;
133     Op.AllowOverlap = !IsVolatile;
134     Op.IsMemset = false;
135     Op.ZeroMemset = false;
136     Op.MemcpyStrSrc = MemcpyStrSrc;
137     Op.SrcAlign = SrcAlign;
138     return Op;
139   }
140 
141   static MemOp Set(uint64_t Size, bool DstAlignCanChange, Align DstAlign,
142                    bool IsZeroMemset, bool IsVolatile) {
143     MemOp Op;
144     Op.Size = Size;
145     Op.DstAlignCanChange = DstAlignCanChange;
146     Op.DstAlign = DstAlign;
147     Op.AllowOverlap = !IsVolatile;
148     Op.IsMemset = true;
149     Op.ZeroMemset = IsZeroMemset;
150     Op.MemcpyStrSrc = false;
151     return Op;
152   }
153 
154   uint64_t size() const { return Size; }
155   Align getDstAlign() const {
156     assert(!DstAlignCanChange);
157     return DstAlign;
158   }
159   bool isFixedDstAlign() const { return !DstAlignCanChange; }
160   bool allowOverlap() const { return AllowOverlap; }
161   bool isMemset() const { return IsMemset; }
162   bool isMemcpy() const { return !IsMemset; }
163   bool isMemcpyWithFixedDstAlign() const {
164     return isMemcpy() && !DstAlignCanChange;
165   }
166   bool isZeroMemset() const { return isMemset() && ZeroMemset; }
167   bool isMemcpyStrSrc() const {
168     assert(isMemcpy() && "Must be a memcpy");
169     return MemcpyStrSrc;
170   }
171   Align getSrcAlign() const {
172     assert(isMemcpy() && "Must be a memcpy");
173     return SrcAlign;
174   }
175   bool isSrcAligned(Align AlignCheck) const {
176     return isMemset() || llvm::isAligned(AlignCheck, SrcAlign.value());
177   }
178   bool isDstAligned(Align AlignCheck) const {
179     return DstAlignCanChange || llvm::isAligned(AlignCheck, DstAlign.value());
180   }
181   bool isAligned(Align AlignCheck) const {
182     return isSrcAligned(AlignCheck) && isDstAligned(AlignCheck);
183   }
184 };
185 
186 /// This base class for TargetLowering contains the SelectionDAG-independent
187 /// parts that can be used from the rest of CodeGen.
188 class TargetLoweringBase {
189 public:
190   /// This enum indicates whether operations are valid for a target, and if not,
191   /// what action should be used to make them valid.
192   enum LegalizeAction : uint8_t {
193     Legal,      // The target natively supports this operation.
194     Promote,    // This operation should be executed in a larger type.
195     Expand,     // Try to expand this to other ops, otherwise use a libcall.
196     LibCall,    // Don't try to expand this to other ops, always use a libcall.
197     Custom      // Use the LowerOperation hook to implement custom lowering.
198   };
199 
200   /// This enum indicates whether a types are legal for a target, and if not,
201   /// what action should be used to make them valid.
202   enum LegalizeTypeAction : uint8_t {
203     TypeLegal,           // The target natively supports this type.
204     TypePromoteInteger,  // Replace this integer with a larger one.
205     TypeExpandInteger,   // Split this integer into two of half the size.
206     TypeSoftenFloat,     // Convert this float to a same size integer type.
207     TypeExpandFloat,     // Split this float into two of half the size.
208     TypeScalarizeVector, // Replace this one-element vector with its element.
209     TypeSplitVector,     // Split this vector into two of half the size.
210     TypeWidenVector,     // This vector should be widened into a larger vector.
211     TypePromoteFloat,    // Replace this float with a larger one.
212     TypeSoftPromoteHalf, // Soften half to i16 and use float to do arithmetic.
213     TypeScalarizeScalableVector, // This action is explicitly left unimplemented.
214                                  // While it is theoretically possible to
215                                  // legalize operations on scalable types with a
216                                  // loop that handles the vscale * #lanes of the
217                                  // vector, this is non-trivial at SelectionDAG
218                                  // level and these types are better to be
219                                  // widened or promoted.
220   };
221 
222   /// LegalizeKind holds the legalization kind that needs to happen to EVT
223   /// in order to type-legalize it.
224   using LegalizeKind = std::pair<LegalizeTypeAction, EVT>;
225 
226   /// Enum that describes how the target represents true/false values.
227   enum BooleanContent {
228     UndefinedBooleanContent,    // Only bit 0 counts, the rest can hold garbage.
229     ZeroOrOneBooleanContent,        // All bits zero except for bit 0.
230     ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
231   };
232 
233   /// Enum that describes what type of support for selects the target has.
234   enum SelectSupportKind {
235     ScalarValSelect,      // The target supports scalar selects (ex: cmov).
236     ScalarCondVectorVal,  // The target supports selects with a scalar condition
237                           // and vector values (ex: cmov).
238     VectorMaskSelect      // The target supports vector selects with a vector
239                           // mask (ex: x86 blends).
240   };
241 
242   /// Enum that specifies what an atomic load/AtomicRMWInst is expanded
243   /// to, if at all. Exists because different targets have different levels of
244   /// support for these atomic instructions, and also have different options
245   /// w.r.t. what they should expand to.
246   enum class AtomicExpansionKind {
247     None,    // Don't expand the instruction.
248     LLSC,    // Expand the instruction into loadlinked/storeconditional; used
249              // by ARM/AArch64.
250     LLOnly,  // Expand the (load) instruction into just a load-linked, which has
251              // greater atomic guarantees than a normal load.
252     CmpXChg, // Expand the instruction into cmpxchg; used by at least X86.
253     MaskedIntrinsic, // Use a target-specific intrinsic for the LL/SC loop.
254   };
255 
256   /// Enum that specifies when a multiplication should be expanded.
257   enum class MulExpansionKind {
258     Always,            // Always expand the instruction.
259     OnlyLegalOrCustom, // Only expand when the resulting instructions are legal
260                        // or custom.
261   };
262 
263   /// Enum that specifies when a float negation is beneficial.
264   enum class NegatibleCost {
265     Cheaper = 0,    // Negated expression is cheaper.
266     Neutral = 1,    // Negated expression has the same cost.
267     Expensive = 2   // Negated expression is more expensive.
268   };
269 
270   class ArgListEntry {
271   public:
272     Value *Val = nullptr;
273     SDValue Node = SDValue();
274     Type *Ty = nullptr;
275     bool IsSExt : 1;
276     bool IsZExt : 1;
277     bool IsInReg : 1;
278     bool IsSRet : 1;
279     bool IsNest : 1;
280     bool IsByVal : 1;
281     bool IsByRef : 1;
282     bool IsInAlloca : 1;
283     bool IsPreallocated : 1;
284     bool IsReturned : 1;
285     bool IsSwiftSelf : 1;
286     bool IsSwiftError : 1;
287     bool IsCFGuardTarget : 1;
288     MaybeAlign Alignment = None;
289     Type *ByValType = nullptr;
290     Type *PreallocatedType = nullptr;
291 
292     ArgListEntry()
293         : IsSExt(false), IsZExt(false), IsInReg(false), IsSRet(false),
294           IsNest(false), IsByVal(false), IsByRef(false), IsInAlloca(false),
295           IsPreallocated(false), IsReturned(false), IsSwiftSelf(false),
296           IsSwiftError(false), IsCFGuardTarget(false) {}
297 
298     void setAttributes(const CallBase *Call, unsigned ArgIdx);
299   };
300   using ArgListTy = std::vector<ArgListEntry>;
301 
302   virtual void markLibCallAttributes(MachineFunction *MF, unsigned CC,
303                                      ArgListTy &Args) const {};
304 
305   static ISD::NodeType getExtendForContent(BooleanContent Content) {
306     switch (Content) {
307     case UndefinedBooleanContent:
308       // Extend by adding rubbish bits.
309       return ISD::ANY_EXTEND;
310     case ZeroOrOneBooleanContent:
311       // Extend by adding zero bits.
312       return ISD::ZERO_EXTEND;
313     case ZeroOrNegativeOneBooleanContent:
314       // Extend by copying the sign bit.
315       return ISD::SIGN_EXTEND;
316     }
317     llvm_unreachable("Invalid content kind");
318   }
319 
320   explicit TargetLoweringBase(const TargetMachine &TM);
321   TargetLoweringBase(const TargetLoweringBase &) = delete;
322   TargetLoweringBase &operator=(const TargetLoweringBase &) = delete;
323   virtual ~TargetLoweringBase() = default;
324 
325   /// Return true if the target support strict float operation
326   bool isStrictFPEnabled() const {
327     return IsStrictFPEnabled;
328   }
329 
330 protected:
331   /// Initialize all of the actions to default values.
332   void initActions();
333 
334 public:
335   const TargetMachine &getTargetMachine() const { return TM; }
336 
337   virtual bool useSoftFloat() const { return false; }
338 
339   /// Return the pointer type for the given address space, defaults to
340   /// the pointer type from the data layout.
341   /// FIXME: The default needs to be removed once all the code is updated.
342   virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS = 0) const {
343     return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
344   }
345 
346   /// Return the in-memory pointer type for the given address space, defaults to
347   /// the pointer type from the data layout.  FIXME: The default needs to be
348   /// removed once all the code is updated.
349   MVT getPointerMemTy(const DataLayout &DL, uint32_t AS = 0) const {
350     return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
351   }
352 
353   /// Return the type for frame index, which is determined by
354   /// the alloca address space specified through the data layout.
355   MVT getFrameIndexTy(const DataLayout &DL) const {
356     return getPointerTy(DL, DL.getAllocaAddrSpace());
357   }
358 
359   /// Return the type for code pointers, which is determined by the program
360   /// address space specified through the data layout.
361   MVT getProgramPointerTy(const DataLayout &DL) const {
362     return getPointerTy(DL, DL.getProgramAddressSpace());
363   }
364 
365   /// Return the type for operands of fence.
366   /// TODO: Let fence operands be of i32 type and remove this.
367   virtual MVT getFenceOperandTy(const DataLayout &DL) const {
368     return getPointerTy(DL);
369   }
370 
371   /// EVT is not used in-tree, but is used by out-of-tree target.
372   /// A documentation for this function would be nice...
373   virtual MVT getScalarShiftAmountTy(const DataLayout &, EVT) const;
374 
375   EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL,
376                        bool LegalTypes = true) const;
377 
378   /// Return the preferred type to use for a shift opcode, given the shifted
379   /// amount type is \p ShiftValueTy.
380   LLVM_READONLY
381   virtual LLT getPreferredShiftAmountTy(LLT ShiftValueTy) const {
382     return ShiftValueTy;
383   }
384 
385   /// Returns the type to be used for the index operand of:
386   /// ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
387   /// ISD::INSERT_SUBVECTOR, and ISD::EXTRACT_SUBVECTOR
388   virtual MVT getVectorIdxTy(const DataLayout &DL) const {
389     return getPointerTy(DL);
390   }
391 
392   /// This callback is used to inspect load/store instructions and add
393   /// target-specific MachineMemOperand flags to them.  The default
394   /// implementation does nothing.
395   virtual MachineMemOperand::Flags getTargetMMOFlags(const Instruction &I) const {
396     return MachineMemOperand::MONone;
397   }
398 
399   MachineMemOperand::Flags getLoadMemOperandFlags(const LoadInst &LI,
400                                                   const DataLayout &DL) const;
401   MachineMemOperand::Flags getStoreMemOperandFlags(const StoreInst &SI,
402                                                    const DataLayout &DL) const;
403   MachineMemOperand::Flags getAtomicMemOperandFlags(const Instruction &AI,
404                                                     const DataLayout &DL) const;
405 
406   virtual bool isSelectSupported(SelectSupportKind /*kind*/) const {
407     return true;
408   }
409 
410   /// Return true if it is profitable to convert a select of FP constants into
411   /// a constant pool load whose address depends on the select condition. The
412   /// parameter may be used to differentiate a select with FP compare from
413   /// integer compare.
414   virtual bool reduceSelectOfFPConstantLoads(EVT CmpOpVT) const {
415     return true;
416   }
417 
418   /// Return true if multiple condition registers are available.
419   bool hasMultipleConditionRegisters() const {
420     return HasMultipleConditionRegisters;
421   }
422 
423   /// Return true if the target has BitExtract instructions.
424   bool hasExtractBitsInsn() const { return HasExtractBitsInsn; }
425 
426   /// Return the preferred vector type legalization action.
427   virtual TargetLoweringBase::LegalizeTypeAction
428   getPreferredVectorAction(MVT VT) const {
429     // The default action for one element vectors is to scalarize
430     if (VT.getVectorElementCount().isScalar())
431       return TypeScalarizeVector;
432     // The default action for an odd-width vector is to widen.
433     if (!VT.isPow2VectorType())
434       return TypeWidenVector;
435     // The default action for other vectors is to promote
436     return TypePromoteInteger;
437   }
438 
439   // Return true if the half type should be passed around as i16, but promoted
440   // to float around arithmetic. The default behavior is to pass around as
441   // float and convert around loads/stores/bitcasts and other places where
442   // the size matters.
443   virtual bool softPromoteHalfType() const { return false; }
444 
445   // There are two general methods for expanding a BUILD_VECTOR node:
446   //  1. Use SCALAR_TO_VECTOR on the defined scalar values and then shuffle
447   //     them together.
448   //  2. Build the vector on the stack and then load it.
449   // If this function returns true, then method (1) will be used, subject to
450   // the constraint that all of the necessary shuffles are legal (as determined
451   // by isShuffleMaskLegal). If this function returns false, then method (2) is
452   // always used. The vector type, and the number of defined values, are
453   // provided.
454   virtual bool
455   shouldExpandBuildVectorWithShuffles(EVT /* VT */,
456                                       unsigned DefinedValues) const {
457     return DefinedValues < 3;
458   }
459 
460   /// Return true if integer divide is usually cheaper than a sequence of
461   /// several shifts, adds, and multiplies for this target.
462   /// The definition of "cheaper" may depend on whether we're optimizing
463   /// for speed or for size.
464   virtual bool isIntDivCheap(EVT VT, AttributeList Attr) const { return false; }
465 
466   /// Return true if the target can handle a standalone remainder operation.
467   virtual bool hasStandaloneRem(EVT VT) const {
468     return true;
469   }
470 
471   /// Return true if SQRT(X) shouldn't be replaced with X*RSQRT(X).
472   virtual bool isFsqrtCheap(SDValue X, SelectionDAG &DAG) const {
473     // Default behavior is to replace SQRT(X) with X*RSQRT(X).
474     return false;
475   }
476 
477   /// Reciprocal estimate status values used by the functions below.
478   enum ReciprocalEstimate : int {
479     Unspecified = -1,
480     Disabled = 0,
481     Enabled = 1
482   };
483 
484   /// Return a ReciprocalEstimate enum value for a square root of the given type
485   /// based on the function's attributes. If the operation is not overridden by
486   /// the function's attributes, "Unspecified" is returned and target defaults
487   /// are expected to be used for instruction selection.
488   int getRecipEstimateSqrtEnabled(EVT VT, MachineFunction &MF) const;
489 
490   /// Return a ReciprocalEstimate enum value for a division of the given type
491   /// based on the function's attributes. If the operation is not overridden by
492   /// the function's attributes, "Unspecified" is returned and target defaults
493   /// are expected to be used for instruction selection.
494   int getRecipEstimateDivEnabled(EVT VT, MachineFunction &MF) const;
495 
496   /// Return the refinement step count for a square root of the given type based
497   /// on the function's attributes. If the operation is not overridden by
498   /// the function's attributes, "Unspecified" is returned and target defaults
499   /// are expected to be used for instruction selection.
500   int getSqrtRefinementSteps(EVT VT, MachineFunction &MF) const;
501 
502   /// Return the refinement step count for a division of the given type based
503   /// on the function's attributes. If the operation is not overridden by
504   /// the function's attributes, "Unspecified" is returned and target defaults
505   /// are expected to be used for instruction selection.
506   int getDivRefinementSteps(EVT VT, MachineFunction &MF) const;
507 
508   /// Returns true if target has indicated at least one type should be bypassed.
509   bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
510 
511   /// Returns map of slow types for division or remainder with corresponding
512   /// fast types
513   const DenseMap<unsigned int, unsigned int> &getBypassSlowDivWidths() const {
514     return BypassSlowDivWidths;
515   }
516 
517   /// Return true if Flow Control is an expensive operation that should be
518   /// avoided.
519   bool isJumpExpensive() const { return JumpIsExpensive; }
520 
521   /// Return true if selects are only cheaper than branches if the branch is
522   /// unlikely to be predicted right.
523   bool isPredictableSelectExpensive() const {
524     return PredictableSelectIsExpensive;
525   }
526 
527   virtual bool fallBackToDAGISel(const Instruction &Inst) const {
528     return false;
529   }
530 
531   /// If a branch or a select condition is skewed in one direction by more than
532   /// this factor, it is very likely to be predicted correctly.
533   virtual BranchProbability getPredictableBranchThreshold() const;
534 
535   /// Return true if the following transform is beneficial:
536   /// fold (conv (load x)) -> (load (conv*)x)
537   /// On architectures that don't natively support some vector loads
538   /// efficiently, casting the load to a smaller vector of larger types and
539   /// loading is more efficient, however, this can be undone by optimizations in
540   /// dag combiner.
541   virtual bool isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT,
542                                        const SelectionDAG &DAG,
543                                        const MachineMemOperand &MMO) const {
544     // Don't do if we could do an indexed load on the original type, but not on
545     // the new one.
546     if (!LoadVT.isSimple() || !BitcastVT.isSimple())
547       return true;
548 
549     MVT LoadMVT = LoadVT.getSimpleVT();
550 
551     // Don't bother doing this if it's just going to be promoted again later, as
552     // doing so might interfere with other combines.
553     if (getOperationAction(ISD::LOAD, LoadMVT) == Promote &&
554         getTypeToPromoteTo(ISD::LOAD, LoadMVT) == BitcastVT.getSimpleVT())
555       return false;
556 
557     bool Fast = false;
558     return allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), BitcastVT,
559                               MMO, &Fast) && Fast;
560   }
561 
562   /// Return true if the following transform is beneficial:
563   /// (store (y (conv x)), y*)) -> (store x, (x*))
564   virtual bool isStoreBitCastBeneficial(EVT StoreVT, EVT BitcastVT,
565                                         const SelectionDAG &DAG,
566                                         const MachineMemOperand &MMO) const {
567     // Default to the same logic as loads.
568     return isLoadBitCastBeneficial(StoreVT, BitcastVT, DAG, MMO);
569   }
570 
571   /// Return true if it is expected to be cheaper to do a store of a non-zero
572   /// vector constant with the given size and type for the address space than to
573   /// store the individual scalar element constants.
574   virtual bool storeOfVectorConstantIsCheap(EVT MemVT,
575                                             unsigned NumElem,
576                                             unsigned AddrSpace) const {
577     return false;
578   }
579 
580   /// Allow store merging for the specified type after legalization in addition
581   /// to before legalization. This may transform stores that do not exist
582   /// earlier (for example, stores created from intrinsics).
583   virtual bool mergeStoresAfterLegalization(EVT MemVT) const {
584     return true;
585   }
586 
587   /// Returns if it's reasonable to merge stores to MemVT size.
588   virtual bool canMergeStoresTo(unsigned AS, EVT MemVT,
589                                 const SelectionDAG &DAG) const {
590     return true;
591   }
592 
593   /// Return true if it is cheap to speculate a call to intrinsic cttz.
594   virtual bool isCheapToSpeculateCttz() const {
595     return false;
596   }
597 
598   /// Return true if it is cheap to speculate a call to intrinsic ctlz.
599   virtual bool isCheapToSpeculateCtlz() const {
600     return false;
601   }
602 
603   /// Return true if ctlz instruction is fast.
604   virtual bool isCtlzFast() const {
605     return false;
606   }
607 
608   /// Return the maximum number of "x & (x - 1)" operations that can be done
609   /// instead of deferring to a custom CTPOP.
610   virtual unsigned getCustomCtpopCost(EVT VT, ISD::CondCode Cond) const {
611     return 1;
612   }
613 
614   /// Return true if instruction generated for equality comparison is folded
615   /// with instruction generated for signed comparison.
616   virtual bool isEqualityCmpFoldedWithSignedCmp() const { return true; }
617 
618   /// Return true if it is safe to transform an integer-domain bitwise operation
619   /// into the equivalent floating-point operation. This should be set to true
620   /// if the target has IEEE-754-compliant fabs/fneg operations for the input
621   /// type.
622   virtual bool hasBitPreservingFPLogic(EVT VT) const {
623     return false;
624   }
625 
626   /// Return true if it is cheaper to split the store of a merged int val
627   /// from a pair of smaller values into multiple stores.
628   virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const {
629     return false;
630   }
631 
632   /// Return if the target supports combining a
633   /// chain like:
634   /// \code
635   ///   %andResult = and %val1, #mask
636   ///   %icmpResult = icmp %andResult, 0
637   /// \endcode
638   /// into a single machine instruction of a form like:
639   /// \code
640   ///   cc = test %register, #mask
641   /// \endcode
642   virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
643     return false;
644   }
645 
646   /// Use bitwise logic to make pairs of compares more efficient. For example:
647   /// and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
648   /// This should be true when it takes more than one instruction to lower
649   /// setcc (cmp+set on x86 scalar), when bitwise ops are faster than logic on
650   /// condition bits (crand on PowerPC), and/or when reducing cmp+br is a win.
651   virtual bool convertSetCCLogicToBitwiseLogic(EVT VT) const {
652     return false;
653   }
654 
655   /// Return the preferred operand type if the target has a quick way to compare
656   /// integer values of the given size. Assume that any legal integer type can
657   /// be compared efficiently. Targets may override this to allow illegal wide
658   /// types to return a vector type if there is support to compare that type.
659   virtual MVT hasFastEqualityCompare(unsigned NumBits) const {
660     MVT VT = MVT::getIntegerVT(NumBits);
661     return isTypeLegal(VT) ? VT : MVT::INVALID_SIMPLE_VALUE_TYPE;
662   }
663 
664   /// Return true if the target should transform:
665   /// (X & Y) == Y ---> (~X & Y) == 0
666   /// (X & Y) != Y ---> (~X & Y) != 0
667   ///
668   /// This may be profitable if the target has a bitwise and-not operation that
669   /// sets comparison flags. A target may want to limit the transformation based
670   /// on the type of Y or if Y is a constant.
671   ///
672   /// Note that the transform will not occur if Y is known to be a power-of-2
673   /// because a mask and compare of a single bit can be handled by inverting the
674   /// predicate, for example:
675   /// (X & 8) == 8 ---> (X & 8) != 0
676   virtual bool hasAndNotCompare(SDValue Y) const {
677     return false;
678   }
679 
680   /// Return true if the target has a bitwise and-not operation:
681   /// X = ~A & B
682   /// This can be used to simplify select or other instructions.
683   virtual bool hasAndNot(SDValue X) const {
684     // If the target has the more complex version of this operation, assume that
685     // it has this operation too.
686     return hasAndNotCompare(X);
687   }
688 
689   /// Return true if the target has a bit-test instruction:
690   ///   (X & (1 << Y)) ==/!= 0
691   /// This knowledge can be used to prevent breaking the pattern,
692   /// or creating it if it could be recognized.
693   virtual bool hasBitTest(SDValue X, SDValue Y) const { return false; }
694 
695   /// There are two ways to clear extreme bits (either low or high):
696   /// Mask:    x &  (-1 << y)  (the instcombine canonical form)
697   /// Shifts:  x >> y << y
698   /// Return true if the variant with 2 variable shifts is preferred.
699   /// Return false if there is no preference.
700   virtual bool shouldFoldMaskToVariableShiftPair(SDValue X) const {
701     // By default, let's assume that no one prefers shifts.
702     return false;
703   }
704 
705   /// Return true if it is profitable to fold a pair of shifts into a mask.
706   /// This is usually true on most targets. But some targets, like Thumb1,
707   /// have immediate shift instructions, but no immediate "and" instruction;
708   /// this makes the fold unprofitable.
709   virtual bool shouldFoldConstantShiftPairToMask(const SDNode *N,
710                                                  CombineLevel Level) const {
711     return true;
712   }
713 
714   /// Should we tranform the IR-optimal check for whether given truncation
715   /// down into KeptBits would be truncating or not:
716   ///   (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
717   /// Into it's more traditional form:
718   ///   ((%x << C) a>> C) dstcond %x
719   /// Return true if we should transform.
720   /// Return false if there is no preference.
721   virtual bool shouldTransformSignedTruncationCheck(EVT XVT,
722                                                     unsigned KeptBits) const {
723     // By default, let's assume that no one prefers shifts.
724     return false;
725   }
726 
727   /// Given the pattern
728   ///   (X & (C l>>/<< Y)) ==/!= 0
729   /// return true if it should be transformed into:
730   ///   ((X <</l>> Y) & C) ==/!= 0
731   /// WARNING: if 'X' is a constant, the fold may deadlock!
732   /// FIXME: we could avoid passing XC, but we can't use isConstOrConstSplat()
733   ///        here because it can end up being not linked in.
734   virtual bool shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
735       SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
736       unsigned OldShiftOpcode, unsigned NewShiftOpcode,
737       SelectionDAG &DAG) const {
738     if (hasBitTest(X, Y)) {
739       // One interesting pattern that we'd want to form is 'bit test':
740       //   ((1 << Y) & C) ==/!= 0
741       // But we also need to be careful not to try to reverse that fold.
742 
743       // Is this '1 << Y' ?
744       if (OldShiftOpcode == ISD::SHL && CC->isOne())
745         return false; // Keep the 'bit test' pattern.
746 
747       // Will it be '1 << Y' after the transform ?
748       if (XC && NewShiftOpcode == ISD::SHL && XC->isOne())
749         return true; // Do form the 'bit test' pattern.
750     }
751 
752     // If 'X' is a constant, and we transform, then we will immediately
753     // try to undo the fold, thus causing endless combine loop.
754     // So by default, let's assume everyone prefers the fold
755     // iff 'X' is not a constant.
756     return !XC;
757   }
758 
759   /// These two forms are equivalent:
760   ///   sub %y, (xor %x, -1)
761   ///   add (add %x, 1), %y
762   /// The variant with two add's is IR-canonical.
763   /// Some targets may prefer one to the other.
764   virtual bool preferIncOfAddToSubOfNot(EVT VT) const {
765     // By default, let's assume that everyone prefers the form with two add's.
766     return true;
767   }
768 
769   /// Return true if the target wants to use the optimization that
770   /// turns ext(promotableInst1(...(promotableInstN(load)))) into
771   /// promotedInst1(...(promotedInstN(ext(load)))).
772   bool enableExtLdPromotion() const { return EnableExtLdPromotion; }
773 
774   /// Return true if the target can combine store(extractelement VectorTy,
775   /// Idx).
776   /// \p Cost[out] gives the cost of that transformation when this is true.
777   virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
778                                          unsigned &Cost) const {
779     return false;
780   }
781 
782   /// Return true if inserting a scalar into a variable element of an undef
783   /// vector is more efficiently handled by splatting the scalar instead.
784   virtual bool shouldSplatInsEltVarIndex(EVT) const {
785     return false;
786   }
787 
788   /// Return true if target always beneficiates from combining into FMA for a
789   /// given value type. This must typically return false on targets where FMA
790   /// takes more cycles to execute than FADD.
791   virtual bool enableAggressiveFMAFusion(EVT VT) const {
792     return false;
793   }
794 
795   /// Return the ValueType of the result of SETCC operations.
796   virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context,
797                                  EVT VT) const;
798 
799   /// Return the ValueType for comparison libcalls. Comparions libcalls include
800   /// floating point comparion calls, and Ordered/Unordered check calls on
801   /// floating point numbers.
802   virtual
803   MVT::SimpleValueType getCmpLibcallReturnType() const;
804 
805   /// For targets without i1 registers, this gives the nature of the high-bits
806   /// of boolean values held in types wider than i1.
807   ///
808   /// "Boolean values" are special true/false values produced by nodes like
809   /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
810   /// Not to be confused with general values promoted from i1.  Some cpus
811   /// distinguish between vectors of boolean and scalars; the isVec parameter
812   /// selects between the two kinds.  For example on X86 a scalar boolean should
813   /// be zero extended from i1, while the elements of a vector of booleans
814   /// should be sign extended from i1.
815   ///
816   /// Some cpus also treat floating point types the same way as they treat
817   /// vectors instead of the way they treat scalars.
818   BooleanContent getBooleanContents(bool isVec, bool isFloat) const {
819     if (isVec)
820       return BooleanVectorContents;
821     return isFloat ? BooleanFloatContents : BooleanContents;
822   }
823 
824   BooleanContent getBooleanContents(EVT Type) const {
825     return getBooleanContents(Type.isVector(), Type.isFloatingPoint());
826   }
827 
828   /// Return target scheduling preference.
829   Sched::Preference getSchedulingPreference() const {
830     return SchedPreferenceInfo;
831   }
832 
833   /// Some scheduler, e.g. hybrid, can switch to different scheduling heuristics
834   /// for different nodes. This function returns the preference (or none) for
835   /// the given node.
836   virtual Sched::Preference getSchedulingPreference(SDNode *) const {
837     return Sched::None;
838   }
839 
840   /// Return the register class that should be used for the specified value
841   /// type.
842   virtual const TargetRegisterClass *getRegClassFor(MVT VT, bool isDivergent = false) const {
843     (void)isDivergent;
844     const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
845     assert(RC && "This value type is not natively supported!");
846     return RC;
847   }
848 
849   /// Allows target to decide about the register class of the
850   /// specific value that is live outside the defining block.
851   /// Returns true if the value needs uniform register class.
852   virtual bool requiresUniformRegister(MachineFunction &MF,
853                                        const Value *) const {
854     return false;
855   }
856 
857   /// Return the 'representative' register class for the specified value
858   /// type.
859   ///
860   /// The 'representative' register class is the largest legal super-reg
861   /// register class for the register class of the value type.  For example, on
862   /// i386 the rep register class for i8, i16, and i32 are GR32; while the rep
863   /// register class is GR64 on x86_64.
864   virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
865     const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
866     return RC;
867   }
868 
869   /// Return the cost of the 'representative' register class for the specified
870   /// value type.
871   virtual uint8_t getRepRegClassCostFor(MVT VT) const {
872     return RepRegClassCostForVT[VT.SimpleTy];
873   }
874 
875   /// Return true if SHIFT instructions should be expanded to SHIFT_PARTS
876   /// instructions, and false if a library call is preferred (e.g for code-size
877   /// reasons).
878   virtual bool shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
879     return true;
880   }
881 
882   /// Return true if the target has native support for the specified value type.
883   /// This means that it has a register that directly holds it without
884   /// promotions or expansions.
885   bool isTypeLegal(EVT VT) const {
886     assert(!VT.isSimple() ||
887            (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
888     return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != nullptr;
889   }
890 
891   class ValueTypeActionImpl {
892     /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
893     /// that indicates how instruction selection should deal with the type.
894     LegalizeTypeAction ValueTypeActions[MVT::LAST_VALUETYPE];
895 
896   public:
897     ValueTypeActionImpl() {
898       std::fill(std::begin(ValueTypeActions), std::end(ValueTypeActions),
899                 TypeLegal);
900     }
901 
902     LegalizeTypeAction getTypeAction(MVT VT) const {
903       return ValueTypeActions[VT.SimpleTy];
904     }
905 
906     void setTypeAction(MVT VT, LegalizeTypeAction Action) {
907       ValueTypeActions[VT.SimpleTy] = Action;
908     }
909   };
910 
911   const ValueTypeActionImpl &getValueTypeActions() const {
912     return ValueTypeActions;
913   }
914 
915   /// Return how we should legalize values of this type, either it is already
916   /// legal (return 'Legal') or we need to promote it to a larger type (return
917   /// 'Promote'), or we need to expand it into multiple registers of smaller
918   /// integer type (return 'Expand').  'Custom' is not an option.
919   LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const {
920     return getTypeConversion(Context, VT).first;
921   }
922   LegalizeTypeAction getTypeAction(MVT VT) const {
923     return ValueTypeActions.getTypeAction(VT);
924   }
925 
926   /// For types supported by the target, this is an identity function.  For
927   /// types that must be promoted to larger types, this returns the larger type
928   /// to promote to.  For integer types that are larger than the largest integer
929   /// register, this contains one step in the expansion to get to the smaller
930   /// register. For illegal floating point types, this returns the integer type
931   /// to transform to.
932   EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
933     return getTypeConversion(Context, VT).second;
934   }
935 
936   /// For types supported by the target, this is an identity function.  For
937   /// types that must be expanded (i.e. integer types that are larger than the
938   /// largest integer register or illegal floating point types), this returns
939   /// the largest legal type it will be expanded to.
940   EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
941     assert(!VT.isVector());
942     while (true) {
943       switch (getTypeAction(Context, VT)) {
944       case TypeLegal:
945         return VT;
946       case TypeExpandInteger:
947         VT = getTypeToTransformTo(Context, VT);
948         break;
949       default:
950         llvm_unreachable("Type is not legal nor is it to be expanded!");
951       }
952     }
953   }
954 
955   /// Vector types are broken down into some number of legal first class types.
956   /// For example, EVT::v8f32 maps to 2 EVT::v4f32 with Altivec or SSE1, or 8
957   /// promoted EVT::f64 values with the X86 FP stack.  Similarly, EVT::v2i64
958   /// turns into 4 EVT::i32 values with both PPC and X86.
959   ///
960   /// This method returns the number of registers needed, and the VT for each
961   /// register.  It also returns the VT and quantity of the intermediate values
962   /// before they are promoted/expanded.
963   unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
964                                   EVT &IntermediateVT,
965                                   unsigned &NumIntermediates,
966                                   MVT &RegisterVT) const;
967 
968   /// Certain targets such as MIPS require that some types such as vectors are
969   /// always broken down into scalars in some contexts. This occurs even if the
970   /// vector type is legal.
971   virtual unsigned getVectorTypeBreakdownForCallingConv(
972       LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
973       unsigned &NumIntermediates, MVT &RegisterVT) const {
974     return getVectorTypeBreakdown(Context, VT, IntermediateVT, NumIntermediates,
975                                   RegisterVT);
976   }
977 
978   struct IntrinsicInfo {
979     unsigned     opc = 0;          // target opcode
980     EVT          memVT;            // memory VT
981 
982     // value representing memory location
983     PointerUnion<const Value *, const PseudoSourceValue *> ptrVal;
984 
985     int          offset = 0;       // offset off of ptrVal
986     uint64_t     size = 0;         // the size of the memory location
987                                    // (taken from memVT if zero)
988     MaybeAlign align = Align(1);   // alignment
989 
990     MachineMemOperand::Flags flags = MachineMemOperand::MONone;
991     IntrinsicInfo() = default;
992   };
993 
994   /// Given an intrinsic, checks if on the target the intrinsic will need to map
995   /// to a MemIntrinsicNode (touches memory). If this is the case, it returns
996   /// true and store the intrinsic information into the IntrinsicInfo that was
997   /// passed to the function.
998   virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
999                                   MachineFunction &,
1000                                   unsigned /*Intrinsic*/) const {
1001     return false;
1002   }
1003 
1004   /// Returns true if the target can instruction select the specified FP
1005   /// immediate natively. If false, the legalizer will materialize the FP
1006   /// immediate as a load from a constant pool.
1007   virtual bool isFPImmLegal(const APFloat & /*Imm*/, EVT /*VT*/,
1008                             bool ForCodeSize = false) const {
1009     return false;
1010   }
1011 
1012   /// Targets can use this to indicate that they only support *some*
1013   /// VECTOR_SHUFFLE operations, those with specific masks.  By default, if a
1014   /// target supports the VECTOR_SHUFFLE node, all mask values are assumed to be
1015   /// legal.
1016   virtual bool isShuffleMaskLegal(ArrayRef<int> /*Mask*/, EVT /*VT*/) const {
1017     return true;
1018   }
1019 
1020   /// Returns true if the operation can trap for the value type.
1021   ///
1022   /// VT must be a legal type. By default, we optimistically assume most
1023   /// operations don't trap except for integer divide and remainder.
1024   virtual bool canOpTrap(unsigned Op, EVT VT) const;
1025 
1026   /// Similar to isShuffleMaskLegal. Targets can use this to indicate if there
1027   /// is a suitable VECTOR_SHUFFLE that can be used to replace a VAND with a
1028   /// constant pool entry.
1029   virtual bool isVectorClearMaskLegal(ArrayRef<int> /*Mask*/,
1030                                       EVT /*VT*/) const {
1031     return false;
1032   }
1033 
1034   /// Return how this operation should be treated: either it is legal, needs to
1035   /// be promoted to a larger size, needs to be expanded to some other code
1036   /// sequence, or the target has a custom expander for it.
1037   LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
1038     if (VT.isExtended()) return Expand;
1039     // If a target-specific SDNode requires legalization, require the target
1040     // to provide custom legalization for it.
1041     if (Op >= array_lengthof(OpActions[0])) return Custom;
1042     return OpActions[(unsigned)VT.getSimpleVT().SimpleTy][Op];
1043   }
1044 
1045   /// Custom method defined by each target to indicate if an operation which
1046   /// may require a scale is supported natively by the target.
1047   /// If not, the operation is illegal.
1048   virtual bool isSupportedFixedPointOperation(unsigned Op, EVT VT,
1049                                               unsigned Scale) const {
1050     return false;
1051   }
1052 
1053   /// Some fixed point operations may be natively supported by the target but
1054   /// only for specific scales. This method allows for checking
1055   /// if the width is supported by the target for a given operation that may
1056   /// depend on scale.
1057   LegalizeAction getFixedPointOperationAction(unsigned Op, EVT VT,
1058                                               unsigned Scale) const {
1059     auto Action = getOperationAction(Op, VT);
1060     if (Action != Legal)
1061       return Action;
1062 
1063     // This operation is supported in this type but may only work on specific
1064     // scales.
1065     bool Supported;
1066     switch (Op) {
1067     default:
1068       llvm_unreachable("Unexpected fixed point operation.");
1069     case ISD::SMULFIX:
1070     case ISD::SMULFIXSAT:
1071     case ISD::UMULFIX:
1072     case ISD::UMULFIXSAT:
1073     case ISD::SDIVFIX:
1074     case ISD::SDIVFIXSAT:
1075     case ISD::UDIVFIX:
1076     case ISD::UDIVFIXSAT:
1077       Supported = isSupportedFixedPointOperation(Op, VT, Scale);
1078       break;
1079     }
1080 
1081     return Supported ? Action : Expand;
1082   }
1083 
1084   // If Op is a strict floating-point operation, return the result
1085   // of getOperationAction for the equivalent non-strict operation.
1086   LegalizeAction getStrictFPOperationAction(unsigned Op, EVT VT) const {
1087     unsigned EqOpc;
1088     switch (Op) {
1089       default: llvm_unreachable("Unexpected FP pseudo-opcode");
1090 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
1091       case ISD::STRICT_##DAGN: EqOpc = ISD::DAGN; break;
1092 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
1093       case ISD::STRICT_##DAGN: EqOpc = ISD::SETCC; break;
1094 #include "llvm/IR/ConstrainedOps.def"
1095     }
1096 
1097     return getOperationAction(EqOpc, VT);
1098   }
1099 
1100   /// Return true if the specified operation is legal on this target or can be
1101   /// made legal with custom lowering. This is used to help guide high-level
1102   /// lowering decisions. LegalOnly is an optional convenience for code paths
1103   /// traversed pre and post legalisation.
1104   bool isOperationLegalOrCustom(unsigned Op, EVT VT,
1105                                 bool LegalOnly = false) const {
1106     if (LegalOnly)
1107       return isOperationLegal(Op, VT);
1108 
1109     return (VT == MVT::Other || isTypeLegal(VT)) &&
1110       (getOperationAction(Op, VT) == Legal ||
1111        getOperationAction(Op, VT) == Custom);
1112   }
1113 
1114   /// Return true if the specified operation is legal on this target or can be
1115   /// made legal using promotion. This is used to help guide high-level lowering
1116   /// decisions. LegalOnly is an optional convenience for code paths traversed
1117   /// pre and post legalisation.
1118   bool isOperationLegalOrPromote(unsigned Op, EVT VT,
1119                                  bool LegalOnly = false) const {
1120     if (LegalOnly)
1121       return isOperationLegal(Op, VT);
1122 
1123     return (VT == MVT::Other || isTypeLegal(VT)) &&
1124       (getOperationAction(Op, VT) == Legal ||
1125        getOperationAction(Op, VT) == Promote);
1126   }
1127 
1128   /// Return true if the specified operation is legal on this target or can be
1129   /// made legal with custom lowering or using promotion. This is used to help
1130   /// guide high-level lowering decisions. LegalOnly is an optional convenience
1131   /// for code paths traversed pre and post legalisation.
1132   bool isOperationLegalOrCustomOrPromote(unsigned Op, EVT VT,
1133                                          bool LegalOnly = false) const {
1134     if (LegalOnly)
1135       return isOperationLegal(Op, VT);
1136 
1137     return (VT == MVT::Other || isTypeLegal(VT)) &&
1138       (getOperationAction(Op, VT) == Legal ||
1139        getOperationAction(Op, VT) == Custom ||
1140        getOperationAction(Op, VT) == Promote);
1141   }
1142 
1143   /// Return true if the operation uses custom lowering, regardless of whether
1144   /// the type is legal or not.
1145   bool isOperationCustom(unsigned Op, EVT VT) const {
1146     return getOperationAction(Op, VT) == Custom;
1147   }
1148 
1149   /// Return true if lowering to a jump table is allowed.
1150   virtual bool areJTsAllowed(const Function *Fn) const {
1151     if (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true")
1152       return false;
1153 
1154     return isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1155            isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
1156   }
1157 
1158   /// Check whether the range [Low,High] fits in a machine word.
1159   bool rangeFitsInWord(const APInt &Low, const APInt &High,
1160                        const DataLayout &DL) const {
1161     // FIXME: Using the pointer type doesn't seem ideal.
1162     uint64_t BW = DL.getIndexSizeInBits(0u);
1163     uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1;
1164     return Range <= BW;
1165   }
1166 
1167   /// Return true if lowering to a jump table is suitable for a set of case
1168   /// clusters which may contain \p NumCases cases, \p Range range of values.
1169   virtual bool isSuitableForJumpTable(const SwitchInst *SI, uint64_t NumCases,
1170                                       uint64_t Range, ProfileSummaryInfo *PSI,
1171                                       BlockFrequencyInfo *BFI) const;
1172 
1173   /// Return true if lowering to a bit test is suitable for a set of case
1174   /// clusters which contains \p NumDests unique destinations, \p Low and
1175   /// \p High as its lowest and highest case values, and expects \p NumCmps
1176   /// case value comparisons. Check if the number of destinations, comparison
1177   /// metric, and range are all suitable.
1178   bool isSuitableForBitTests(unsigned NumDests, unsigned NumCmps,
1179                              const APInt &Low, const APInt &High,
1180                              const DataLayout &DL) const {
1181     // FIXME: I don't think NumCmps is the correct metric: a single case and a
1182     // range of cases both require only one branch to lower. Just looking at the
1183     // number of clusters and destinations should be enough to decide whether to
1184     // build bit tests.
1185 
1186     // To lower a range with bit tests, the range must fit the bitwidth of a
1187     // machine word.
1188     if (!rangeFitsInWord(Low, High, DL))
1189       return false;
1190 
1191     // Decide whether it's profitable to lower this range with bit tests. Each
1192     // destination requires a bit test and branch, and there is an overall range
1193     // check branch. For a small number of clusters, separate comparisons might
1194     // be cheaper, and for many destinations, splitting the range might be
1195     // better.
1196     return (NumDests == 1 && NumCmps >= 3) || (NumDests == 2 && NumCmps >= 5) ||
1197            (NumDests == 3 && NumCmps >= 6);
1198   }
1199 
1200   /// Return true if the specified operation is illegal on this target or
1201   /// unlikely to be made legal with custom lowering. This is used to help guide
1202   /// high-level lowering decisions.
1203   bool isOperationExpand(unsigned Op, EVT VT) const {
1204     return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
1205   }
1206 
1207   /// Return true if the specified operation is legal on this target.
1208   bool isOperationLegal(unsigned Op, EVT VT) const {
1209     return (VT == MVT::Other || isTypeLegal(VT)) &&
1210            getOperationAction(Op, VT) == Legal;
1211   }
1212 
1213   /// Return how this load with extension should be treated: either it is legal,
1214   /// needs to be promoted to a larger size, needs to be expanded to some other
1215   /// code sequence, or the target has a custom expander for it.
1216   LegalizeAction getLoadExtAction(unsigned ExtType, EVT ValVT,
1217                                   EVT MemVT) const {
1218     if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
1219     unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
1220     unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
1221     assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValI < MVT::LAST_VALUETYPE &&
1222            MemI < MVT::LAST_VALUETYPE && "Table isn't big enough!");
1223     unsigned Shift = 4 * ExtType;
1224     return (LegalizeAction)((LoadExtActions[ValI][MemI] >> Shift) & 0xf);
1225   }
1226 
1227   /// Return true if the specified load with extension is legal on this target.
1228   bool isLoadExtLegal(unsigned ExtType, EVT ValVT, EVT MemVT) const {
1229     return getLoadExtAction(ExtType, ValVT, MemVT) == Legal;
1230   }
1231 
1232   /// Return true if the specified load with extension is legal or custom
1233   /// on this target.
1234   bool isLoadExtLegalOrCustom(unsigned ExtType, EVT ValVT, EVT MemVT) const {
1235     return getLoadExtAction(ExtType, ValVT, MemVT) == Legal ||
1236            getLoadExtAction(ExtType, ValVT, MemVT) == Custom;
1237   }
1238 
1239   /// Return how this store with truncation should be treated: either it is
1240   /// legal, needs to be promoted to a larger size, needs to be expanded to some
1241   /// other code sequence, or the target has a custom expander for it.
1242   LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT) const {
1243     if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
1244     unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
1245     unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
1246     assert(ValI < MVT::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE &&
1247            "Table isn't big enough!");
1248     return TruncStoreActions[ValI][MemI];
1249   }
1250 
1251   /// Return true if the specified store with truncation is legal on this
1252   /// target.
1253   bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
1254     return isTypeLegal(ValVT) && getTruncStoreAction(ValVT, MemVT) == Legal;
1255   }
1256 
1257   /// Return true if the specified store with truncation has solution on this
1258   /// target.
1259   bool isTruncStoreLegalOrCustom(EVT ValVT, EVT MemVT) const {
1260     return isTypeLegal(ValVT) &&
1261       (getTruncStoreAction(ValVT, MemVT) == Legal ||
1262        getTruncStoreAction(ValVT, MemVT) == Custom);
1263   }
1264 
1265   /// Return how the indexed load should be treated: either it is legal, needs
1266   /// to be promoted to a larger size, needs to be expanded to some other code
1267   /// sequence, or the target has a custom expander for it.
1268   LegalizeAction getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
1269     return getIndexedModeAction(IdxMode, VT, IMAB_Load);
1270   }
1271 
1272   /// Return true if the specified indexed load is legal on this target.
1273   bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
1274     return VT.isSimple() &&
1275       (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
1276        getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
1277   }
1278 
1279   /// Return how the indexed store should be treated: either it is legal, needs
1280   /// to be promoted to a larger size, needs to be expanded to some other code
1281   /// sequence, or the target has a custom expander for it.
1282   LegalizeAction getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
1283     return getIndexedModeAction(IdxMode, VT, IMAB_Store);
1284   }
1285 
1286   /// Return true if the specified indexed load is legal on this target.
1287   bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
1288     return VT.isSimple() &&
1289       (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
1290        getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
1291   }
1292 
1293   /// Return how the indexed load should be treated: either it is legal, needs
1294   /// to be promoted to a larger size, needs to be expanded to some other code
1295   /// sequence, or the target has a custom expander for it.
1296   LegalizeAction getIndexedMaskedLoadAction(unsigned IdxMode, MVT VT) const {
1297     return getIndexedModeAction(IdxMode, VT, IMAB_MaskedLoad);
1298   }
1299 
1300   /// Return true if the specified indexed load is legal on this target.
1301   bool isIndexedMaskedLoadLegal(unsigned IdxMode, EVT VT) const {
1302     return VT.isSimple() &&
1303            (getIndexedMaskedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
1304             getIndexedMaskedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
1305   }
1306 
1307   /// Return how the indexed store should be treated: either it is legal, needs
1308   /// to be promoted to a larger size, needs to be expanded to some other code
1309   /// sequence, or the target has a custom expander for it.
1310   LegalizeAction getIndexedMaskedStoreAction(unsigned IdxMode, MVT VT) const {
1311     return getIndexedModeAction(IdxMode, VT, IMAB_MaskedStore);
1312   }
1313 
1314   /// Return true if the specified indexed load is legal on this target.
1315   bool isIndexedMaskedStoreLegal(unsigned IdxMode, EVT VT) const {
1316     return VT.isSimple() &&
1317            (getIndexedMaskedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
1318             getIndexedMaskedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
1319   }
1320 
1321   // Returns true if VT is a legal index type for masked gathers/scatters
1322   // on this target
1323   virtual bool shouldRemoveExtendFromGSIndex(EVT VT) const { return false; }
1324 
1325   /// Return how the condition code should be treated: either it is legal, needs
1326   /// to be expanded to some other code sequence, or the target has a custom
1327   /// expander for it.
1328   LegalizeAction
1329   getCondCodeAction(ISD::CondCode CC, MVT VT) const {
1330     assert((unsigned)CC < array_lengthof(CondCodeActions) &&
1331            ((unsigned)VT.SimpleTy >> 3) < array_lengthof(CondCodeActions[0]) &&
1332            "Table isn't big enough!");
1333     // See setCondCodeAction for how this is encoded.
1334     uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
1335     uint32_t Value = CondCodeActions[CC][VT.SimpleTy >> 3];
1336     LegalizeAction Action = (LegalizeAction) ((Value >> Shift) & 0xF);
1337     assert(Action != Promote && "Can't promote condition code!");
1338     return Action;
1339   }
1340 
1341   /// Return true if the specified condition code is legal on this target.
1342   bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
1343     return getCondCodeAction(CC, VT) == Legal;
1344   }
1345 
1346   /// Return true if the specified condition code is legal or custom on this
1347   /// target.
1348   bool isCondCodeLegalOrCustom(ISD::CondCode CC, MVT VT) const {
1349     return getCondCodeAction(CC, VT) == Legal ||
1350            getCondCodeAction(CC, VT) == Custom;
1351   }
1352 
1353   /// If the action for this operation is to promote, this method returns the
1354   /// ValueType to promote to.
1355   MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
1356     assert(getOperationAction(Op, VT) == Promote &&
1357            "This operation isn't promoted!");
1358 
1359     // See if this has an explicit type specified.
1360     std::map<std::pair<unsigned, MVT::SimpleValueType>,
1361              MVT::SimpleValueType>::const_iterator PTTI =
1362       PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
1363     if (PTTI != PromoteToType.end()) return PTTI->second;
1364 
1365     assert((VT.isInteger() || VT.isFloatingPoint()) &&
1366            "Cannot autopromote this type, add it with AddPromotedToType.");
1367 
1368     MVT NVT = VT;
1369     do {
1370       NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
1371       assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
1372              "Didn't find type to promote to!");
1373     } while (!isTypeLegal(NVT) ||
1374               getOperationAction(Op, NVT) == Promote);
1375     return NVT;
1376   }
1377 
1378   /// Return the EVT corresponding to this LLVM type.  This is fixed by the LLVM
1379   /// operations except for the pointer size.  If AllowUnknown is true, this
1380   /// will return MVT::Other for types with no EVT counterpart (e.g. structs),
1381   /// otherwise it will assert.
1382   EVT getValueType(const DataLayout &DL, Type *Ty,
1383                    bool AllowUnknown = false) const {
1384     // Lower scalar pointers to native pointer types.
1385     if (auto *PTy = dyn_cast<PointerType>(Ty))
1386       return getPointerTy(DL, PTy->getAddressSpace());
1387 
1388     if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1389       Type *EltTy = VTy->getElementType();
1390       // Lower vectors of pointers to native pointer types.
1391       if (auto *PTy = dyn_cast<PointerType>(EltTy)) {
1392         EVT PointerTy(getPointerTy(DL, PTy->getAddressSpace()));
1393         EltTy = PointerTy.getTypeForEVT(Ty->getContext());
1394       }
1395       return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(EltTy, false),
1396                               VTy->getElementCount());
1397     }
1398 
1399     return EVT::getEVT(Ty, AllowUnknown);
1400   }
1401 
1402   EVT getMemValueType(const DataLayout &DL, Type *Ty,
1403                       bool AllowUnknown = false) const {
1404     // Lower scalar pointers to native pointer types.
1405     if (PointerType *PTy = dyn_cast<PointerType>(Ty))
1406       return getPointerMemTy(DL, PTy->getAddressSpace());
1407     else if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1408       Type *Elm = VTy->getElementType();
1409       if (PointerType *PT = dyn_cast<PointerType>(Elm)) {
1410         EVT PointerTy(getPointerMemTy(DL, PT->getAddressSpace()));
1411         Elm = PointerTy.getTypeForEVT(Ty->getContext());
1412       }
1413       return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
1414                               VTy->getElementCount());
1415     }
1416 
1417     return getValueType(DL, Ty, AllowUnknown);
1418   }
1419 
1420 
1421   /// Return the MVT corresponding to this LLVM type. See getValueType.
1422   MVT getSimpleValueType(const DataLayout &DL, Type *Ty,
1423                          bool AllowUnknown = false) const {
1424     return getValueType(DL, Ty, AllowUnknown).getSimpleVT();
1425   }
1426 
1427   /// Return the desired alignment for ByVal or InAlloca aggregate function
1428   /// arguments in the caller parameter area.  This is the actual alignment, not
1429   /// its logarithm.
1430   virtual unsigned getByValTypeAlignment(Type *Ty, const DataLayout &DL) const;
1431 
1432   /// Return the type of registers that this ValueType will eventually require.
1433   MVT getRegisterType(MVT VT) const {
1434     assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
1435     return RegisterTypeForVT[VT.SimpleTy];
1436   }
1437 
1438   /// Return the type of registers that this ValueType will eventually require.
1439   MVT getRegisterType(LLVMContext &Context, EVT VT) const {
1440     if (VT.isSimple()) {
1441       assert((unsigned)VT.getSimpleVT().SimpleTy <
1442                 array_lengthof(RegisterTypeForVT));
1443       return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
1444     }
1445     if (VT.isVector()) {
1446       EVT VT1;
1447       MVT RegisterVT;
1448       unsigned NumIntermediates;
1449       (void)getVectorTypeBreakdown(Context, VT, VT1,
1450                                    NumIntermediates, RegisterVT);
1451       return RegisterVT;
1452     }
1453     if (VT.isInteger()) {
1454       return getRegisterType(Context, getTypeToTransformTo(Context, VT));
1455     }
1456     llvm_unreachable("Unsupported extended type!");
1457   }
1458 
1459   /// Return the number of registers that this ValueType will eventually
1460   /// require.
1461   ///
1462   /// This is one for any types promoted to live in larger registers, but may be
1463   /// more than one for types (like i64) that are split into pieces.  For types
1464   /// like i140, which are first promoted then expanded, it is the number of
1465   /// registers needed to hold all the bits of the original type.  For an i140
1466   /// on a 32 bit machine this means 5 registers.
1467   unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
1468     if (VT.isSimple()) {
1469       assert((unsigned)VT.getSimpleVT().SimpleTy <
1470                 array_lengthof(NumRegistersForVT));
1471       return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
1472     }
1473     if (VT.isVector()) {
1474       EVT VT1;
1475       MVT VT2;
1476       unsigned NumIntermediates;
1477       return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
1478     }
1479     if (VT.isInteger()) {
1480       unsigned BitWidth = VT.getSizeInBits();
1481       unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
1482       return (BitWidth + RegWidth - 1) / RegWidth;
1483     }
1484     llvm_unreachable("Unsupported extended type!");
1485   }
1486 
1487   /// Certain combinations of ABIs, Targets and features require that types
1488   /// are legal for some operations and not for other operations.
1489   /// For MIPS all vector types must be passed through the integer register set.
1490   virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context,
1491                                             CallingConv::ID CC, EVT VT) const {
1492     return getRegisterType(Context, VT);
1493   }
1494 
1495   /// Certain targets require unusual breakdowns of certain types. For MIPS,
1496   /// this occurs when a vector type is used, as vector are passed through the
1497   /// integer register set.
1498   virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context,
1499                                                  CallingConv::ID CC,
1500                                                  EVT VT) const {
1501     return getNumRegisters(Context, VT);
1502   }
1503 
1504   /// Certain targets have context senstive alignment requirements, where one
1505   /// type has the alignment requirement of another type.
1506   virtual Align getABIAlignmentForCallingConv(Type *ArgTy,
1507                                               DataLayout DL) const {
1508     return DL.getABITypeAlign(ArgTy);
1509   }
1510 
1511   /// If true, then instruction selection should seek to shrink the FP constant
1512   /// of the specified type to a smaller type in order to save space and / or
1513   /// reduce runtime.
1514   virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
1515 
1516   /// Return true if it is profitable to reduce a load to a smaller type.
1517   /// Example: (i16 (trunc (i32 (load x))) -> i16 load x
1518   virtual bool shouldReduceLoadWidth(SDNode *Load, ISD::LoadExtType ExtTy,
1519                                      EVT NewVT) const {
1520     // By default, assume that it is cheaper to extract a subvector from a wide
1521     // vector load rather than creating multiple narrow vector loads.
1522     if (NewVT.isVector() && !Load->hasOneUse())
1523       return false;
1524 
1525     return true;
1526   }
1527 
1528   /// When splitting a value of the specified type into parts, does the Lo
1529   /// or Hi part come first?  This usually follows the endianness, except
1530   /// for ppcf128, where the Hi part always comes first.
1531   bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const {
1532     return DL.isBigEndian() || VT == MVT::ppcf128;
1533   }
1534 
1535   /// If true, the target has custom DAG combine transformations that it can
1536   /// perform for the specified node.
1537   bool hasTargetDAGCombine(ISD::NodeType NT) const {
1538     assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1539     return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
1540   }
1541 
1542   unsigned getGatherAllAliasesMaxDepth() const {
1543     return GatherAllAliasesMaxDepth;
1544   }
1545 
1546   /// Returns the size of the platform's va_list object.
1547   virtual unsigned getVaListSizeInBits(const DataLayout &DL) const {
1548     return getPointerTy(DL).getSizeInBits();
1549   }
1550 
1551   /// Get maximum # of store operations permitted for llvm.memset
1552   ///
1553   /// This function returns the maximum number of store operations permitted
1554   /// to replace a call to llvm.memset. The value is set by the target at the
1555   /// performance threshold for such a replacement. If OptSize is true,
1556   /// return the limit for functions that have OptSize attribute.
1557   unsigned getMaxStoresPerMemset(bool OptSize) const {
1558     return OptSize ? MaxStoresPerMemsetOptSize : MaxStoresPerMemset;
1559   }
1560 
1561   /// Get maximum # of store operations permitted for llvm.memcpy
1562   ///
1563   /// This function returns the maximum number of store operations permitted
1564   /// to replace a call to llvm.memcpy. The value is set by the target at the
1565   /// performance threshold for such a replacement. If OptSize is true,
1566   /// return the limit for functions that have OptSize attribute.
1567   unsigned getMaxStoresPerMemcpy(bool OptSize) const {
1568     return OptSize ? MaxStoresPerMemcpyOptSize : MaxStoresPerMemcpy;
1569   }
1570 
1571   /// \brief Get maximum # of store operations to be glued together
1572   ///
1573   /// This function returns the maximum number of store operations permitted
1574   /// to glue together during lowering of llvm.memcpy. The value is set by
1575   //  the target at the performance threshold for such a replacement.
1576   virtual unsigned getMaxGluedStoresPerMemcpy() const {
1577     return MaxGluedStoresPerMemcpy;
1578   }
1579 
1580   /// Get maximum # of load operations permitted for memcmp
1581   ///
1582   /// This function returns the maximum number of load operations permitted
1583   /// to replace a call to memcmp. The value is set by the target at the
1584   /// performance threshold for such a replacement. If OptSize is true,
1585   /// return the limit for functions that have OptSize attribute.
1586   unsigned getMaxExpandSizeMemcmp(bool OptSize) const {
1587     return OptSize ? MaxLoadsPerMemcmpOptSize : MaxLoadsPerMemcmp;
1588   }
1589 
1590   /// Get maximum # of store operations permitted for llvm.memmove
1591   ///
1592   /// This function returns the maximum number of store operations permitted
1593   /// to replace a call to llvm.memmove. The value is set by the target at the
1594   /// performance threshold for such a replacement. If OptSize is true,
1595   /// return the limit for functions that have OptSize attribute.
1596   unsigned getMaxStoresPerMemmove(bool OptSize) const {
1597     return OptSize ? MaxStoresPerMemmoveOptSize : MaxStoresPerMemmove;
1598   }
1599 
1600   /// Determine if the target supports unaligned memory accesses.
1601   ///
1602   /// This function returns true if the target allows unaligned memory accesses
1603   /// of the specified type in the given address space. If true, it also returns
1604   /// whether the unaligned memory access is "fast" in the last argument by
1605   /// reference. This is used, for example, in situations where an array
1606   /// copy/move/set is converted to a sequence of store operations. Its use
1607   /// helps to ensure that such replacements don't generate code that causes an
1608   /// alignment error (trap) on the target machine.
1609   virtual bool allowsMisalignedMemoryAccesses(
1610       EVT, unsigned AddrSpace = 0, unsigned Align = 1,
1611       MachineMemOperand::Flags Flags = MachineMemOperand::MONone,
1612       bool * /*Fast*/ = nullptr) const {
1613     return false;
1614   }
1615 
1616   /// LLT handling variant.
1617   virtual bool allowsMisalignedMemoryAccesses(
1618       LLT, unsigned AddrSpace = 0, Align Alignment = Align(1),
1619       MachineMemOperand::Flags Flags = MachineMemOperand::MONone,
1620       bool * /*Fast*/ = nullptr) const {
1621     return false;
1622   }
1623 
1624   /// This function returns true if the memory access is aligned or if the
1625   /// target allows this specific unaligned memory access. If the access is
1626   /// allowed, the optional final parameter returns if the access is also fast
1627   /// (as defined by the target).
1628   bool allowsMemoryAccessForAlignment(
1629       LLVMContext &Context, const DataLayout &DL, EVT VT,
1630       unsigned AddrSpace = 0, Align Alignment = Align(1),
1631       MachineMemOperand::Flags Flags = MachineMemOperand::MONone,
1632       bool *Fast = nullptr) const;
1633 
1634   /// Return true if the memory access of this type is aligned or if the target
1635   /// allows this specific unaligned access for the given MachineMemOperand.
1636   /// If the access is allowed, the optional final parameter returns if the
1637   /// access is also fast (as defined by the target).
1638   bool allowsMemoryAccessForAlignment(LLVMContext &Context,
1639                                       const DataLayout &DL, EVT VT,
1640                                       const MachineMemOperand &MMO,
1641                                       bool *Fast = nullptr) const;
1642 
1643   /// Return true if the target supports a memory access of this type for the
1644   /// given address space and alignment. If the access is allowed, the optional
1645   /// final parameter returns if the access is also fast (as defined by the
1646   /// target).
1647   virtual bool
1648   allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT,
1649                      unsigned AddrSpace = 0, Align Alignment = Align(1),
1650                      MachineMemOperand::Flags Flags = MachineMemOperand::MONone,
1651                      bool *Fast = nullptr) const;
1652 
1653   /// Return true if the target supports a memory access of this type for the
1654   /// given MachineMemOperand. If the access is allowed, the optional
1655   /// final parameter returns if the access is also fast (as defined by the
1656   /// target).
1657   bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT,
1658                           const MachineMemOperand &MMO,
1659                           bool *Fast = nullptr) const;
1660 
1661   /// LLT handling variant.
1662   bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, LLT Ty,
1663                           const MachineMemOperand &MMO,
1664                           bool *Fast = nullptr) const;
1665 
1666   /// Returns the target specific optimal type for load and store operations as
1667   /// a result of memset, memcpy, and memmove lowering.
1668   /// It returns EVT::Other if the type should be determined using generic
1669   /// target-independent logic.
1670   virtual EVT
1671   getOptimalMemOpType(const MemOp &Op,
1672                       const AttributeList & /*FuncAttributes*/) const {
1673     return MVT::Other;
1674   }
1675 
1676   /// LLT returning variant.
1677   virtual LLT
1678   getOptimalMemOpLLT(const MemOp &Op,
1679                      const AttributeList & /*FuncAttributes*/) const {
1680     return LLT();
1681   }
1682 
1683   /// Returns true if it's safe to use load / store of the specified type to
1684   /// expand memcpy / memset inline.
1685   ///
1686   /// This is mostly true for all types except for some special cases. For
1687   /// example, on X86 targets without SSE2 f64 load / store are done with fldl /
1688   /// fstpl which also does type conversion. Note the specified type doesn't
1689   /// have to be legal as the hook is used before type legalization.
1690   virtual bool isSafeMemOpType(MVT /*VT*/) const { return true; }
1691 
1692   /// Return lower limit for number of blocks in a jump table.
1693   virtual unsigned getMinimumJumpTableEntries() const;
1694 
1695   /// Return lower limit of the density in a jump table.
1696   unsigned getMinimumJumpTableDensity(bool OptForSize) const;
1697 
1698   /// Return upper limit for number of entries in a jump table.
1699   /// Zero if no limit.
1700   unsigned getMaximumJumpTableSize() const;
1701 
1702   virtual bool isJumpTableRelative() const;
1703 
1704   /// If a physical register, this specifies the register that
1705   /// llvm.savestack/llvm.restorestack should save and restore.
1706   Register getStackPointerRegisterToSaveRestore() const {
1707     return StackPointerRegisterToSaveRestore;
1708   }
1709 
1710   /// If a physical register, this returns the register that receives the
1711   /// exception address on entry to an EH pad.
1712   virtual Register
1713   getExceptionPointerRegister(const Constant *PersonalityFn) const {
1714     return Register();
1715   }
1716 
1717   /// If a physical register, this returns the register that receives the
1718   /// exception typeid on entry to a landing pad.
1719   virtual Register
1720   getExceptionSelectorRegister(const Constant *PersonalityFn) const {
1721     return Register();
1722   }
1723 
1724   virtual bool needsFixedCatchObjects() const {
1725     report_fatal_error("Funclet EH is not implemented for this target");
1726   }
1727 
1728   /// Return the minimum stack alignment of an argument.
1729   Align getMinStackArgumentAlignment() const {
1730     return MinStackArgumentAlignment;
1731   }
1732 
1733   /// Return the minimum function alignment.
1734   Align getMinFunctionAlignment() const { return MinFunctionAlignment; }
1735 
1736   /// Return the preferred function alignment.
1737   Align getPrefFunctionAlignment() const { return PrefFunctionAlignment; }
1738 
1739   /// Return the preferred loop alignment.
1740   virtual Align getPrefLoopAlignment(MachineLoop *ML = nullptr) const {
1741     return PrefLoopAlignment;
1742   }
1743 
1744   /// Should loops be aligned even when the function is marked OptSize (but not
1745   /// MinSize).
1746   virtual bool alignLoopsWithOptSize() const {
1747     return false;
1748   }
1749 
1750   /// If the target has a standard location for the stack protector guard,
1751   /// returns the address of that location. Otherwise, returns nullptr.
1752   /// DEPRECATED: please override useLoadStackGuardNode and customize
1753   ///             LOAD_STACK_GUARD, or customize \@llvm.stackguard().
1754   virtual Value *getIRStackGuard(IRBuilder<> &IRB) const;
1755 
1756   /// Inserts necessary declarations for SSP (stack protection) purpose.
1757   /// Should be used only when getIRStackGuard returns nullptr.
1758   virtual void insertSSPDeclarations(Module &M) const;
1759 
1760   /// Return the variable that's previously inserted by insertSSPDeclarations,
1761   /// if any, otherwise return nullptr. Should be used only when
1762   /// getIRStackGuard returns nullptr.
1763   virtual Value *getSDagStackGuard(const Module &M) const;
1764 
1765   /// If this function returns true, stack protection checks should XOR the
1766   /// frame pointer (or whichever pointer is used to address locals) into the
1767   /// stack guard value before checking it. getIRStackGuard must return nullptr
1768   /// if this returns true.
1769   virtual bool useStackGuardXorFP() const { return false; }
1770 
1771   /// If the target has a standard stack protection check function that
1772   /// performs validation and error handling, returns the function. Otherwise,
1773   /// returns nullptr. Must be previously inserted by insertSSPDeclarations.
1774   /// Should be used only when getIRStackGuard returns nullptr.
1775   virtual Function *getSSPStackGuardCheck(const Module &M) const;
1776 
1777 protected:
1778   Value *getDefaultSafeStackPointerLocation(IRBuilder<> &IRB,
1779                                             bool UseTLS) const;
1780 
1781 public:
1782   /// Returns the target-specific address of the unsafe stack pointer.
1783   virtual Value *getSafeStackPointerLocation(IRBuilder<> &IRB) const;
1784 
1785   /// Returns the name of the symbol used to emit stack probes or the empty
1786   /// string if not applicable.
1787   virtual bool hasStackProbeSymbol(MachineFunction &MF) const { return false; }
1788 
1789   virtual bool hasInlineStackProbe(MachineFunction &MF) const { return false; }
1790 
1791   virtual StringRef getStackProbeSymbolName(MachineFunction &MF) const {
1792     return "";
1793   }
1794 
1795   /// Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g. we
1796   /// are happy to sink it into basic blocks. A cast may be free, but not
1797   /// necessarily a no-op. e.g. a free truncate from a 64-bit to 32-bit pointer.
1798   virtual bool isFreeAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const;
1799 
1800   /// Return true if the pointer arguments to CI should be aligned by aligning
1801   /// the object whose address is being passed. If so then MinSize is set to the
1802   /// minimum size the object must be to be aligned and PrefAlign is set to the
1803   /// preferred alignment.
1804   virtual bool shouldAlignPointerArgs(CallInst * /*CI*/, unsigned & /*MinSize*/,
1805                                       unsigned & /*PrefAlign*/) const {
1806     return false;
1807   }
1808 
1809   //===--------------------------------------------------------------------===//
1810   /// \name Helpers for TargetTransformInfo implementations
1811   /// @{
1812 
1813   /// Get the ISD node that corresponds to the Instruction class opcode.
1814   int InstructionOpcodeToISD(unsigned Opcode) const;
1815 
1816   /// Estimate the cost of type-legalization and the legalized type.
1817   std::pair<int, MVT> getTypeLegalizationCost(const DataLayout &DL,
1818                                               Type *Ty) const;
1819 
1820   /// @}
1821 
1822   //===--------------------------------------------------------------------===//
1823   /// \name Helpers for atomic expansion.
1824   /// @{
1825 
1826   /// Returns the maximum atomic operation size (in bits) supported by
1827   /// the backend. Atomic operations greater than this size (as well
1828   /// as ones that are not naturally aligned), will be expanded by
1829   /// AtomicExpandPass into an __atomic_* library call.
1830   unsigned getMaxAtomicSizeInBitsSupported() const {
1831     return MaxAtomicSizeInBitsSupported;
1832   }
1833 
1834   /// Returns the size of the smallest cmpxchg or ll/sc instruction
1835   /// the backend supports.  Any smaller operations are widened in
1836   /// AtomicExpandPass.
1837   ///
1838   /// Note that *unlike* operations above the maximum size, atomic ops
1839   /// are still natively supported below the minimum; they just
1840   /// require a more complex expansion.
1841   unsigned getMinCmpXchgSizeInBits() const { return MinCmpXchgSizeInBits; }
1842 
1843   /// Whether the target supports unaligned atomic operations.
1844   bool supportsUnalignedAtomics() const { return SupportsUnalignedAtomics; }
1845 
1846   /// Whether AtomicExpandPass should automatically insert fences and reduce
1847   /// ordering for this atomic. This should be true for most architectures with
1848   /// weak memory ordering. Defaults to false.
1849   virtual bool shouldInsertFencesForAtomic(const Instruction *I) const {
1850     return false;
1851   }
1852 
1853   /// Perform a load-linked operation on Addr, returning a "Value *" with the
1854   /// corresponding pointee type. This may entail some non-trivial operations to
1855   /// truncate or reconstruct types that will be illegal in the backend. See
1856   /// ARMISelLowering for an example implementation.
1857   virtual Value *emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
1858                                 AtomicOrdering Ord) const {
1859     llvm_unreachable("Load linked unimplemented on this target");
1860   }
1861 
1862   /// Perform a store-conditional operation to Addr. Return the status of the
1863   /// store. This should be 0 if the store succeeded, non-zero otherwise.
1864   virtual Value *emitStoreConditional(IRBuilder<> &Builder, Value *Val,
1865                                       Value *Addr, AtomicOrdering Ord) const {
1866     llvm_unreachable("Store conditional unimplemented on this target");
1867   }
1868 
1869   /// Perform a masked atomicrmw using a target-specific intrinsic. This
1870   /// represents the core LL/SC loop which will be lowered at a late stage by
1871   /// the backend.
1872   virtual Value *emitMaskedAtomicRMWIntrinsic(IRBuilder<> &Builder,
1873                                               AtomicRMWInst *AI,
1874                                               Value *AlignedAddr, Value *Incr,
1875                                               Value *Mask, Value *ShiftAmt,
1876                                               AtomicOrdering Ord) const {
1877     llvm_unreachable("Masked atomicrmw expansion unimplemented on this target");
1878   }
1879 
1880   /// Perform a masked cmpxchg using a target-specific intrinsic. This
1881   /// represents the core LL/SC loop which will be lowered at a late stage by
1882   /// the backend.
1883   virtual Value *emitMaskedAtomicCmpXchgIntrinsic(
1884       IRBuilder<> &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
1885       Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
1886     llvm_unreachable("Masked cmpxchg expansion unimplemented on this target");
1887   }
1888 
1889   /// Inserts in the IR a target-specific intrinsic specifying a fence.
1890   /// It is called by AtomicExpandPass before expanding an
1891   ///   AtomicRMW/AtomicCmpXchg/AtomicStore/AtomicLoad
1892   ///   if shouldInsertFencesForAtomic returns true.
1893   ///
1894   /// Inst is the original atomic instruction, prior to other expansions that
1895   /// may be performed.
1896   ///
1897   /// This function should either return a nullptr, or a pointer to an IR-level
1898   ///   Instruction*. Even complex fence sequences can be represented by a
1899   ///   single Instruction* through an intrinsic to be lowered later.
1900   /// Backends should override this method to produce target-specific intrinsic
1901   ///   for their fences.
1902   /// FIXME: Please note that the default implementation here in terms of
1903   ///   IR-level fences exists for historical/compatibility reasons and is
1904   ///   *unsound* ! Fences cannot, in general, be used to restore sequential
1905   ///   consistency. For example, consider the following example:
1906   /// atomic<int> x = y = 0;
1907   /// int r1, r2, r3, r4;
1908   /// Thread 0:
1909   ///   x.store(1);
1910   /// Thread 1:
1911   ///   y.store(1);
1912   /// Thread 2:
1913   ///   r1 = x.load();
1914   ///   r2 = y.load();
1915   /// Thread 3:
1916   ///   r3 = y.load();
1917   ///   r4 = x.load();
1918   ///  r1 = r3 = 1 and r2 = r4 = 0 is impossible as long as the accesses are all
1919   ///  seq_cst. But if they are lowered to monotonic accesses, no amount of
1920   ///  IR-level fences can prevent it.
1921   /// @{
1922   virtual Instruction *emitLeadingFence(IRBuilder<> &Builder, Instruction *Inst,
1923                                         AtomicOrdering Ord) const {
1924     if (isReleaseOrStronger(Ord) && Inst->hasAtomicStore())
1925       return Builder.CreateFence(Ord);
1926     else
1927       return nullptr;
1928   }
1929 
1930   virtual Instruction *emitTrailingFence(IRBuilder<> &Builder,
1931                                          Instruction *Inst,
1932                                          AtomicOrdering Ord) const {
1933     if (isAcquireOrStronger(Ord))
1934       return Builder.CreateFence(Ord);
1935     else
1936       return nullptr;
1937   }
1938   /// @}
1939 
1940   // Emits code that executes when the comparison result in the ll/sc
1941   // expansion of a cmpxchg instruction is such that the store-conditional will
1942   // not execute.  This makes it possible to balance out the load-linked with
1943   // a dedicated instruction, if desired.
1944   // E.g., on ARM, if ldrex isn't followed by strex, the exclusive monitor would
1945   // be unnecessarily held, except if clrex, inserted by this hook, is executed.
1946   virtual void emitAtomicCmpXchgNoStoreLLBalance(IRBuilder<> &Builder) const {}
1947 
1948   /// Returns true if the given (atomic) store should be expanded by the
1949   /// IR-level AtomicExpand pass into an "atomic xchg" which ignores its input.
1950   virtual bool shouldExpandAtomicStoreInIR(StoreInst *SI) const {
1951     return false;
1952   }
1953 
1954   /// Returns true if arguments should be sign-extended in lib calls.
1955   virtual bool shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
1956     return IsSigned;
1957   }
1958 
1959   /// Returns true if arguments should be extended in lib calls.
1960   virtual bool shouldExtendTypeInLibCall(EVT Type) const {
1961     return true;
1962   }
1963 
1964   /// Returns how the given (atomic) load should be expanded by the
1965   /// IR-level AtomicExpand pass.
1966   virtual AtomicExpansionKind shouldExpandAtomicLoadInIR(LoadInst *LI) const {
1967     return AtomicExpansionKind::None;
1968   }
1969 
1970   /// Returns how the given atomic cmpxchg should be expanded by the IR-level
1971   /// AtomicExpand pass.
1972   virtual AtomicExpansionKind
1973   shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
1974     return AtomicExpansionKind::None;
1975   }
1976 
1977   /// Returns how the IR-level AtomicExpand pass should expand the given
1978   /// AtomicRMW, if at all. Default is to never expand.
1979   virtual AtomicExpansionKind shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
1980     return RMW->isFloatingPointOperation() ?
1981       AtomicExpansionKind::CmpXChg : AtomicExpansionKind::None;
1982   }
1983 
1984   /// On some platforms, an AtomicRMW that never actually modifies the value
1985   /// (such as fetch_add of 0) can be turned into a fence followed by an
1986   /// atomic load. This may sound useless, but it makes it possible for the
1987   /// processor to keep the cacheline shared, dramatically improving
1988   /// performance. And such idempotent RMWs are useful for implementing some
1989   /// kinds of locks, see for example (justification + benchmarks):
1990   /// http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf
1991   /// This method tries doing that transformation, returning the atomic load if
1992   /// it succeeds, and nullptr otherwise.
1993   /// If shouldExpandAtomicLoadInIR returns true on that load, it will undergo
1994   /// another round of expansion.
1995   virtual LoadInst *
1996   lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *RMWI) const {
1997     return nullptr;
1998   }
1999 
2000   /// Returns how the platform's atomic operations are extended (ZERO_EXTEND,
2001   /// SIGN_EXTEND, or ANY_EXTEND).
2002   virtual ISD::NodeType getExtendForAtomicOps() const {
2003     return ISD::ZERO_EXTEND;
2004   }
2005 
2006   /// Returns how the platform's atomic compare and swap expects its comparison
2007   /// value to be extended (ZERO_EXTEND, SIGN_EXTEND, or ANY_EXTEND). This is
2008   /// separate from getExtendForAtomicOps, which is concerned with the
2009   /// sign-extension of the instruction's output, whereas here we are concerned
2010   /// with the sign-extension of the input. For targets with compare-and-swap
2011   /// instructions (or sub-word comparisons in their LL/SC loop expansions),
2012   /// the input can be ANY_EXTEND, but the output will still have a specific
2013   /// extension.
2014   virtual ISD::NodeType getExtendForAtomicCmpSwapArg() const {
2015     return ISD::ANY_EXTEND;
2016   }
2017 
2018   /// @}
2019 
2020   /// Returns true if we should normalize
2021   /// select(N0&N1, X, Y) => select(N0, select(N1, X, Y), Y) and
2022   /// select(N0|N1, X, Y) => select(N0, select(N1, X, Y, Y)) if it is likely
2023   /// that it saves us from materializing N0 and N1 in an integer register.
2024   /// Targets that are able to perform and/or on flags should return false here.
2025   virtual bool shouldNormalizeToSelectSequence(LLVMContext &Context,
2026                                                EVT VT) const {
2027     // If a target has multiple condition registers, then it likely has logical
2028     // operations on those registers.
2029     if (hasMultipleConditionRegisters())
2030       return false;
2031     // Only do the transform if the value won't be split into multiple
2032     // registers.
2033     LegalizeTypeAction Action = getTypeAction(Context, VT);
2034     return Action != TypeExpandInteger && Action != TypeExpandFloat &&
2035       Action != TypeSplitVector;
2036   }
2037 
2038   virtual bool isProfitableToCombineMinNumMaxNum(EVT VT) const { return true; }
2039 
2040   /// Return true if a select of constants (select Cond, C1, C2) should be
2041   /// transformed into simple math ops with the condition value. For example:
2042   /// select Cond, C1, C1-1 --> add (zext Cond), C1-1
2043   virtual bool convertSelectOfConstantsToMath(EVT VT) const {
2044     return false;
2045   }
2046 
2047   /// Return true if it is profitable to transform an integer
2048   /// multiplication-by-constant into simpler operations like shifts and adds.
2049   /// This may be true if the target does not directly support the
2050   /// multiplication operation for the specified type or the sequence of simpler
2051   /// ops is faster than the multiply.
2052   virtual bool decomposeMulByConstant(LLVMContext &Context,
2053                                       EVT VT, SDValue C) const {
2054     return false;
2055   }
2056 
2057   /// Return true if it is more correct/profitable to use strict FP_TO_INT
2058   /// conversion operations - canonicalizing the FP source value instead of
2059   /// converting all cases and then selecting based on value.
2060   /// This may be true if the target throws exceptions for out of bounds
2061   /// conversions or has fast FP CMOV.
2062   virtual bool shouldUseStrictFP_TO_INT(EVT FpVT, EVT IntVT,
2063                                         bool IsSigned) const {
2064     return false;
2065   }
2066 
2067   //===--------------------------------------------------------------------===//
2068   // TargetLowering Configuration Methods - These methods should be invoked by
2069   // the derived class constructor to configure this object for the target.
2070   //
2071 protected:
2072   /// Specify how the target extends the result of integer and floating point
2073   /// boolean values from i1 to a wider type.  See getBooleanContents.
2074   void setBooleanContents(BooleanContent Ty) {
2075     BooleanContents = Ty;
2076     BooleanFloatContents = Ty;
2077   }
2078 
2079   /// Specify how the target extends the result of integer and floating point
2080   /// boolean values from i1 to a wider type.  See getBooleanContents.
2081   void setBooleanContents(BooleanContent IntTy, BooleanContent FloatTy) {
2082     BooleanContents = IntTy;
2083     BooleanFloatContents = FloatTy;
2084   }
2085 
2086   /// Specify how the target extends the result of a vector boolean value from a
2087   /// vector of i1 to a wider type.  See getBooleanContents.
2088   void setBooleanVectorContents(BooleanContent Ty) {
2089     BooleanVectorContents = Ty;
2090   }
2091 
2092   /// Specify the target scheduling preference.
2093   void setSchedulingPreference(Sched::Preference Pref) {
2094     SchedPreferenceInfo = Pref;
2095   }
2096 
2097   /// Indicate the minimum number of blocks to generate jump tables.
2098   void setMinimumJumpTableEntries(unsigned Val);
2099 
2100   /// Indicate the maximum number of entries in jump tables.
2101   /// Set to zero to generate unlimited jump tables.
2102   void setMaximumJumpTableSize(unsigned);
2103 
2104   /// If set to a physical register, this specifies the register that
2105   /// llvm.savestack/llvm.restorestack should save and restore.
2106   void setStackPointerRegisterToSaveRestore(Register R) {
2107     StackPointerRegisterToSaveRestore = R;
2108   }
2109 
2110   /// Tells the code generator that the target has multiple (allocatable)
2111   /// condition registers that can be used to store the results of comparisons
2112   /// for use by selects and conditional branches. With multiple condition
2113   /// registers, the code generator will not aggressively sink comparisons into
2114   /// the blocks of their users.
2115   void setHasMultipleConditionRegisters(bool hasManyRegs = true) {
2116     HasMultipleConditionRegisters = hasManyRegs;
2117   }
2118 
2119   /// Tells the code generator that the target has BitExtract instructions.
2120   /// The code generator will aggressively sink "shift"s into the blocks of
2121   /// their users if the users will generate "and" instructions which can be
2122   /// combined with "shift" to BitExtract instructions.
2123   void setHasExtractBitsInsn(bool hasExtractInsn = true) {
2124     HasExtractBitsInsn = hasExtractInsn;
2125   }
2126 
2127   /// Tells the code generator not to expand logic operations on comparison
2128   /// predicates into separate sequences that increase the amount of flow
2129   /// control.
2130   void setJumpIsExpensive(bool isExpensive = true);
2131 
2132   /// Tells the code generator which bitwidths to bypass.
2133   void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
2134     BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
2135   }
2136 
2137   /// Add the specified register class as an available regclass for the
2138   /// specified value type. This indicates the selector can handle values of
2139   /// that class natively.
2140   void addRegisterClass(MVT VT, const TargetRegisterClass *RC) {
2141     assert((unsigned)VT.SimpleTy < array_lengthof(RegClassForVT));
2142     RegClassForVT[VT.SimpleTy] = RC;
2143   }
2144 
2145   /// Return the largest legal super-reg register class of the register class
2146   /// for the specified type and its associated "cost".
2147   virtual std::pair<const TargetRegisterClass *, uint8_t>
2148   findRepresentativeClass(const TargetRegisterInfo *TRI, MVT VT) const;
2149 
2150   /// Once all of the register classes are added, this allows us to compute
2151   /// derived properties we expose.
2152   void computeRegisterProperties(const TargetRegisterInfo *TRI);
2153 
2154   /// Indicate that the specified operation does not work with the specified
2155   /// type and indicate what to do about it. Note that VT may refer to either
2156   /// the type of a result or that of an operand of Op.
2157   void setOperationAction(unsigned Op, MVT VT,
2158                           LegalizeAction Action) {
2159     assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
2160     OpActions[(unsigned)VT.SimpleTy][Op] = Action;
2161   }
2162 
2163   /// Indicate that the specified load with extension does not work with the
2164   /// specified type and indicate what to do about it.
2165   void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT,
2166                         LegalizeAction Action) {
2167     assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() &&
2168            MemVT.isValid() && "Table isn't big enough!");
2169     assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
2170     unsigned Shift = 4 * ExtType;
2171     LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] &= ~((uint16_t)0xF << Shift);
2172     LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] |= (uint16_t)Action << Shift;
2173   }
2174 
2175   /// Indicate that the specified truncating store does not work with the
2176   /// specified type and indicate what to do about it.
2177   void setTruncStoreAction(MVT ValVT, MVT MemVT,
2178                            LegalizeAction Action) {
2179     assert(ValVT.isValid() && MemVT.isValid() && "Table isn't big enough!");
2180     TruncStoreActions[(unsigned)ValVT.SimpleTy][MemVT.SimpleTy] = Action;
2181   }
2182 
2183   /// Indicate that the specified indexed load does or does not work with the
2184   /// specified type and indicate what to do abort it.
2185   ///
2186   /// NOTE: All indexed mode loads are initialized to Expand in
2187   /// TargetLowering.cpp
2188   void setIndexedLoadAction(unsigned IdxMode, MVT VT, LegalizeAction Action) {
2189     setIndexedModeAction(IdxMode, VT, IMAB_Load, Action);
2190   }
2191 
2192   /// Indicate that the specified indexed store does or does not work with the
2193   /// specified type and indicate what to do about it.
2194   ///
2195   /// NOTE: All indexed mode stores are initialized to Expand in
2196   /// TargetLowering.cpp
2197   void setIndexedStoreAction(unsigned IdxMode, MVT VT, LegalizeAction Action) {
2198     setIndexedModeAction(IdxMode, VT, IMAB_Store, Action);
2199   }
2200 
2201   /// Indicate that the specified indexed masked load does or does not work with
2202   /// the specified type and indicate what to do about it.
2203   ///
2204   /// NOTE: All indexed mode masked loads are initialized to Expand in
2205   /// TargetLowering.cpp
2206   void setIndexedMaskedLoadAction(unsigned IdxMode, MVT VT,
2207                                   LegalizeAction Action) {
2208     setIndexedModeAction(IdxMode, VT, IMAB_MaskedLoad, Action);
2209   }
2210 
2211   /// Indicate that the specified indexed masked store does or does not work
2212   /// with the specified type and indicate what to do about it.
2213   ///
2214   /// NOTE: All indexed mode masked stores are initialized to Expand in
2215   /// TargetLowering.cpp
2216   void setIndexedMaskedStoreAction(unsigned IdxMode, MVT VT,
2217                                    LegalizeAction Action) {
2218     setIndexedModeAction(IdxMode, VT, IMAB_MaskedStore, Action);
2219   }
2220 
2221   /// Indicate that the specified condition code is or isn't supported on the
2222   /// target and indicate what to do about it.
2223   void setCondCodeAction(ISD::CondCode CC, MVT VT,
2224                          LegalizeAction Action) {
2225     assert(VT.isValid() && (unsigned)CC < array_lengthof(CondCodeActions) &&
2226            "Table isn't big enough!");
2227     assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
2228     /// The lower 3 bits of the SimpleTy index into Nth 4bit set from the 32-bit
2229     /// value and the upper 29 bits index into the second dimension of the array
2230     /// to select what 32-bit value to use.
2231     uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
2232     CondCodeActions[CC][VT.SimpleTy >> 3] &= ~((uint32_t)0xF << Shift);
2233     CondCodeActions[CC][VT.SimpleTy >> 3] |= (uint32_t)Action << Shift;
2234   }
2235 
2236   /// If Opc/OrigVT is specified as being promoted, the promotion code defaults
2237   /// to trying a larger integer/fp until it can find one that works. If that
2238   /// default is insufficient, this method can be used by the target to override
2239   /// the default.
2240   void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
2241     PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
2242   }
2243 
2244   /// Convenience method to set an operation to Promote and specify the type
2245   /// in a single call.
2246   void setOperationPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
2247     setOperationAction(Opc, OrigVT, Promote);
2248     AddPromotedToType(Opc, OrigVT, DestVT);
2249   }
2250 
2251   /// Targets should invoke this method for each target independent node that
2252   /// they want to provide a custom DAG combiner for by implementing the
2253   /// PerformDAGCombine virtual method.
2254   void setTargetDAGCombine(ISD::NodeType NT) {
2255     assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
2256     TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
2257   }
2258 
2259   /// Set the target's minimum function alignment.
2260   void setMinFunctionAlignment(Align Alignment) {
2261     MinFunctionAlignment = Alignment;
2262   }
2263 
2264   /// Set the target's preferred function alignment.  This should be set if
2265   /// there is a performance benefit to higher-than-minimum alignment
2266   void setPrefFunctionAlignment(Align Alignment) {
2267     PrefFunctionAlignment = Alignment;
2268   }
2269 
2270   /// Set the target's preferred loop alignment. Default alignment is one, it
2271   /// means the target does not care about loop alignment. The target may also
2272   /// override getPrefLoopAlignment to provide per-loop values.
2273   void setPrefLoopAlignment(Align Alignment) { PrefLoopAlignment = Alignment; }
2274 
2275   /// Set the minimum stack alignment of an argument.
2276   void setMinStackArgumentAlignment(Align Alignment) {
2277     MinStackArgumentAlignment = Alignment;
2278   }
2279 
2280   /// Set the maximum atomic operation size supported by the
2281   /// backend. Atomic operations greater than this size (as well as
2282   /// ones that are not naturally aligned), will be expanded by
2283   /// AtomicExpandPass into an __atomic_* library call.
2284   void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits) {
2285     MaxAtomicSizeInBitsSupported = SizeInBits;
2286   }
2287 
2288   /// Sets the minimum cmpxchg or ll/sc size supported by the backend.
2289   void setMinCmpXchgSizeInBits(unsigned SizeInBits) {
2290     MinCmpXchgSizeInBits = SizeInBits;
2291   }
2292 
2293   /// Sets whether unaligned atomic operations are supported.
2294   void setSupportsUnalignedAtomics(bool UnalignedSupported) {
2295     SupportsUnalignedAtomics = UnalignedSupported;
2296   }
2297 
2298 public:
2299   //===--------------------------------------------------------------------===//
2300   // Addressing mode description hooks (used by LSR etc).
2301   //
2302 
2303   /// CodeGenPrepare sinks address calculations into the same BB as Load/Store
2304   /// instructions reading the address. This allows as much computation as
2305   /// possible to be done in the address mode for that operand. This hook lets
2306   /// targets also pass back when this should be done on intrinsics which
2307   /// load/store.
2308   virtual bool getAddrModeArguments(IntrinsicInst * /*I*/,
2309                                     SmallVectorImpl<Value*> &/*Ops*/,
2310                                     Type *&/*AccessTy*/) const {
2311     return false;
2312   }
2313 
2314   /// This represents an addressing mode of:
2315   ///    BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
2316   /// If BaseGV is null,  there is no BaseGV.
2317   /// If BaseOffs is zero, there is no base offset.
2318   /// If HasBaseReg is false, there is no base register.
2319   /// If Scale is zero, there is no ScaleReg.  Scale of 1 indicates a reg with
2320   /// no scale.
2321   struct AddrMode {
2322     GlobalValue *BaseGV = nullptr;
2323     int64_t      BaseOffs = 0;
2324     bool         HasBaseReg = false;
2325     int64_t      Scale = 0;
2326     AddrMode() = default;
2327   };
2328 
2329   /// Return true if the addressing mode represented by AM is legal for this
2330   /// target, for a load/store of the specified type.
2331   ///
2332   /// The type may be VoidTy, in which case only return true if the addressing
2333   /// mode is legal for a load/store of any legal type.  TODO: Handle
2334   /// pre/postinc as well.
2335   ///
2336   /// If the address space cannot be determined, it will be -1.
2337   ///
2338   /// TODO: Remove default argument
2339   virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM,
2340                                      Type *Ty, unsigned AddrSpace,
2341                                      Instruction *I = nullptr) const;
2342 
2343   /// Return the cost of the scaling factor used in the addressing mode
2344   /// represented by AM for this target, for a load/store of the specified type.
2345   ///
2346   /// If the AM is supported, the return value must be >= 0.
2347   /// If the AM is not supported, it returns a negative value.
2348   /// TODO: Handle pre/postinc as well.
2349   /// TODO: Remove default argument
2350   virtual int getScalingFactorCost(const DataLayout &DL, const AddrMode &AM,
2351                                    Type *Ty, unsigned AS = 0) const {
2352     // Default: assume that any scaling factor used in a legal AM is free.
2353     if (isLegalAddressingMode(DL, AM, Ty, AS))
2354       return 0;
2355     return -1;
2356   }
2357 
2358   /// Return true if the specified immediate is legal icmp immediate, that is
2359   /// the target has icmp instructions which can compare a register against the
2360   /// immediate without having to materialize the immediate into a register.
2361   virtual bool isLegalICmpImmediate(int64_t) const {
2362     return true;
2363   }
2364 
2365   /// Return true if the specified immediate is legal add immediate, that is the
2366   /// target has add instructions which can add a register with the immediate
2367   /// without having to materialize the immediate into a register.
2368   virtual bool isLegalAddImmediate(int64_t) const {
2369     return true;
2370   }
2371 
2372   /// Return true if the specified immediate is legal for the value input of a
2373   /// store instruction.
2374   virtual bool isLegalStoreImmediate(int64_t Value) const {
2375     // Default implementation assumes that at least 0 works since it is likely
2376     // that a zero register exists or a zero immediate is allowed.
2377     return Value == 0;
2378   }
2379 
2380   /// Return true if it's significantly cheaper to shift a vector by a uniform
2381   /// scalar than by an amount which will vary across each lane. On x86 before
2382   /// AVX2 for example, there is a "psllw" instruction for the former case, but
2383   /// no simple instruction for a general "a << b" operation on vectors.
2384   /// This should also apply to lowering for vector funnel shifts (rotates).
2385   virtual bool isVectorShiftByScalarCheap(Type *Ty) const {
2386     return false;
2387   }
2388 
2389   /// Given a shuffle vector SVI representing a vector splat, return a new
2390   /// scalar type of size equal to SVI's scalar type if the new type is more
2391   /// profitable. Returns nullptr otherwise. For example under MVE float splats
2392   /// are converted to integer to prevent the need to move from SPR to GPR
2393   /// registers.
2394   virtual Type* shouldConvertSplatType(ShuffleVectorInst* SVI) const {
2395     return nullptr;
2396   }
2397 
2398   /// Given a set in interconnected phis of type 'From' that are loaded/stored
2399   /// or bitcast to type 'To', return true if the set should be converted to
2400   /// 'To'.
2401   virtual bool shouldConvertPhiType(Type *From, Type *To) const {
2402     return (From->isIntegerTy() || From->isFloatingPointTy()) &&
2403            (To->isIntegerTy() || To->isFloatingPointTy());
2404   }
2405 
2406   /// Returns true if the opcode is a commutative binary operation.
2407   virtual bool isCommutativeBinOp(unsigned Opcode) const {
2408     // FIXME: This should get its info from the td file.
2409     switch (Opcode) {
2410     case ISD::ADD:
2411     case ISD::SMIN:
2412     case ISD::SMAX:
2413     case ISD::UMIN:
2414     case ISD::UMAX:
2415     case ISD::MUL:
2416     case ISD::MULHU:
2417     case ISD::MULHS:
2418     case ISD::SMUL_LOHI:
2419     case ISD::UMUL_LOHI:
2420     case ISD::FADD:
2421     case ISD::FMUL:
2422     case ISD::AND:
2423     case ISD::OR:
2424     case ISD::XOR:
2425     case ISD::SADDO:
2426     case ISD::UADDO:
2427     case ISD::ADDC:
2428     case ISD::ADDE:
2429     case ISD::SADDSAT:
2430     case ISD::UADDSAT:
2431     case ISD::FMINNUM:
2432     case ISD::FMAXNUM:
2433     case ISD::FMINNUM_IEEE:
2434     case ISD::FMAXNUM_IEEE:
2435     case ISD::FMINIMUM:
2436     case ISD::FMAXIMUM:
2437       return true;
2438     default: return false;
2439     }
2440   }
2441 
2442   /// Return true if the node is a math/logic binary operator.
2443   virtual bool isBinOp(unsigned Opcode) const {
2444     // A commutative binop must be a binop.
2445     if (isCommutativeBinOp(Opcode))
2446       return true;
2447     // These are non-commutative binops.
2448     switch (Opcode) {
2449     case ISD::SUB:
2450     case ISD::SHL:
2451     case ISD::SRL:
2452     case ISD::SRA:
2453     case ISD::SDIV:
2454     case ISD::UDIV:
2455     case ISD::SREM:
2456     case ISD::UREM:
2457     case ISD::FSUB:
2458     case ISD::FDIV:
2459     case ISD::FREM:
2460       return true;
2461     default:
2462       return false;
2463     }
2464   }
2465 
2466   /// Return true if it's free to truncate a value of type FromTy to type
2467   /// ToTy. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
2468   /// by referencing its sub-register AX.
2469   /// Targets must return false when FromTy <= ToTy.
2470   virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const {
2471     return false;
2472   }
2473 
2474   /// Return true if a truncation from FromTy to ToTy is permitted when deciding
2475   /// whether a call is in tail position. Typically this means that both results
2476   /// would be assigned to the same register or stack slot, but it could mean
2477   /// the target performs adequate checks of its own before proceeding with the
2478   /// tail call.  Targets must return false when FromTy <= ToTy.
2479   virtual bool allowTruncateForTailCall(Type *FromTy, Type *ToTy) const {
2480     return false;
2481   }
2482 
2483   virtual bool isTruncateFree(EVT FromVT, EVT ToVT) const {
2484     return false;
2485   }
2486 
2487   virtual bool isProfitableToHoist(Instruction *I) const { return true; }
2488 
2489   /// Return true if the extension represented by \p I is free.
2490   /// Unlikely the is[Z|FP]ExtFree family which is based on types,
2491   /// this method can use the context provided by \p I to decide
2492   /// whether or not \p I is free.
2493   /// This method extends the behavior of the is[Z|FP]ExtFree family.
2494   /// In other words, if is[Z|FP]Free returns true, then this method
2495   /// returns true as well. The converse is not true.
2496   /// The target can perform the adequate checks by overriding isExtFreeImpl.
2497   /// \pre \p I must be a sign, zero, or fp extension.
2498   bool isExtFree(const Instruction *I) const {
2499     switch (I->getOpcode()) {
2500     case Instruction::FPExt:
2501       if (isFPExtFree(EVT::getEVT(I->getType()),
2502                       EVT::getEVT(I->getOperand(0)->getType())))
2503         return true;
2504       break;
2505     case Instruction::ZExt:
2506       if (isZExtFree(I->getOperand(0)->getType(), I->getType()))
2507         return true;
2508       break;
2509     case Instruction::SExt:
2510       break;
2511     default:
2512       llvm_unreachable("Instruction is not an extension");
2513     }
2514     return isExtFreeImpl(I);
2515   }
2516 
2517   /// Return true if \p Load and \p Ext can form an ExtLoad.
2518   /// For example, in AArch64
2519   ///   %L = load i8, i8* %ptr
2520   ///   %E = zext i8 %L to i32
2521   /// can be lowered into one load instruction
2522   ///   ldrb w0, [x0]
2523   bool isExtLoad(const LoadInst *Load, const Instruction *Ext,
2524                  const DataLayout &DL) const {
2525     EVT VT = getValueType(DL, Ext->getType());
2526     EVT LoadVT = getValueType(DL, Load->getType());
2527 
2528     // If the load has other users and the truncate is not free, the ext
2529     // probably isn't free.
2530     if (!Load->hasOneUse() && (isTypeLegal(LoadVT) || !isTypeLegal(VT)) &&
2531         !isTruncateFree(Ext->getType(), Load->getType()))
2532       return false;
2533 
2534     // Check whether the target supports casts folded into loads.
2535     unsigned LType;
2536     if (isa<ZExtInst>(Ext))
2537       LType = ISD::ZEXTLOAD;
2538     else {
2539       assert(isa<SExtInst>(Ext) && "Unexpected ext type!");
2540       LType = ISD::SEXTLOAD;
2541     }
2542 
2543     return isLoadExtLegal(LType, VT, LoadVT);
2544   }
2545 
2546   /// Return true if any actual instruction that defines a value of type FromTy
2547   /// implicitly zero-extends the value to ToTy in the result register.
2548   ///
2549   /// The function should return true when it is likely that the truncate can
2550   /// be freely folded with an instruction defining a value of FromTy. If
2551   /// the defining instruction is unknown (because you're looking at a
2552   /// function argument, PHI, etc.) then the target may require an
2553   /// explicit truncate, which is not necessarily free, but this function
2554   /// does not deal with those cases.
2555   /// Targets must return false when FromTy >= ToTy.
2556   virtual bool isZExtFree(Type *FromTy, Type *ToTy) const {
2557     return false;
2558   }
2559 
2560   virtual bool isZExtFree(EVT FromTy, EVT ToTy) const {
2561     return false;
2562   }
2563 
2564   /// Return true if sign-extension from FromTy to ToTy is cheaper than
2565   /// zero-extension.
2566   virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const {
2567     return false;
2568   }
2569 
2570   /// Return true if sinking I's operands to the same basic block as I is
2571   /// profitable, e.g. because the operands can be folded into a target
2572   /// instruction during instruction selection. After calling the function
2573   /// \p Ops contains the Uses to sink ordered by dominance (dominating users
2574   /// come first).
2575   virtual bool shouldSinkOperands(Instruction *I,
2576                                   SmallVectorImpl<Use *> &Ops) const {
2577     return false;
2578   }
2579 
2580   /// Return true if the target supplies and combines to a paired load
2581   /// two loaded values of type LoadedType next to each other in memory.
2582   /// RequiredAlignment gives the minimal alignment constraints that must be met
2583   /// to be able to select this paired load.
2584   ///
2585   /// This information is *not* used to generate actual paired loads, but it is
2586   /// used to generate a sequence of loads that is easier to combine into a
2587   /// paired load.
2588   /// For instance, something like this:
2589   /// a = load i64* addr
2590   /// b = trunc i64 a to i32
2591   /// c = lshr i64 a, 32
2592   /// d = trunc i64 c to i32
2593   /// will be optimized into:
2594   /// b = load i32* addr1
2595   /// d = load i32* addr2
2596   /// Where addr1 = addr2 +/- sizeof(i32).
2597   ///
2598   /// In other words, unless the target performs a post-isel load combining,
2599   /// this information should not be provided because it will generate more
2600   /// loads.
2601   virtual bool hasPairedLoad(EVT /*LoadedType*/,
2602                              Align & /*RequiredAlignment*/) const {
2603     return false;
2604   }
2605 
2606   /// Return true if the target has a vector blend instruction.
2607   virtual bool hasVectorBlend() const { return false; }
2608 
2609   /// Get the maximum supported factor for interleaved memory accesses.
2610   /// Default to be the minimum interleave factor: 2.
2611   virtual unsigned getMaxSupportedInterleaveFactor() const { return 2; }
2612 
2613   /// Lower an interleaved load to target specific intrinsics. Return
2614   /// true on success.
2615   ///
2616   /// \p LI is the vector load instruction.
2617   /// \p Shuffles is the shufflevector list to DE-interleave the loaded vector.
2618   /// \p Indices is the corresponding indices for each shufflevector.
2619   /// \p Factor is the interleave factor.
2620   virtual bool lowerInterleavedLoad(LoadInst *LI,
2621                                     ArrayRef<ShuffleVectorInst *> Shuffles,
2622                                     ArrayRef<unsigned> Indices,
2623                                     unsigned Factor) const {
2624     return false;
2625   }
2626 
2627   /// Lower an interleaved store to target specific intrinsics. Return
2628   /// true on success.
2629   ///
2630   /// \p SI is the vector store instruction.
2631   /// \p SVI is the shufflevector to RE-interleave the stored vector.
2632   /// \p Factor is the interleave factor.
2633   virtual bool lowerInterleavedStore(StoreInst *SI, ShuffleVectorInst *SVI,
2634                                      unsigned Factor) const {
2635     return false;
2636   }
2637 
2638   /// Return true if zero-extending the specific node Val to type VT2 is free
2639   /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
2640   /// because it's folded such as X86 zero-extending loads).
2641   virtual bool isZExtFree(SDValue Val, EVT VT2) const {
2642     return isZExtFree(Val.getValueType(), VT2);
2643   }
2644 
2645   /// Return true if an fpext operation is free (for instance, because
2646   /// single-precision floating-point numbers are implicitly extended to
2647   /// double-precision).
2648   virtual bool isFPExtFree(EVT DestVT, EVT SrcVT) const {
2649     assert(SrcVT.isFloatingPoint() && DestVT.isFloatingPoint() &&
2650            "invalid fpext types");
2651     return false;
2652   }
2653 
2654   /// Return true if an fpext operation input to an \p Opcode operation is free
2655   /// (for instance, because half-precision floating-point numbers are
2656   /// implicitly extended to float-precision) for an FMA instruction.
2657   virtual bool isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
2658                                EVT DestVT, EVT SrcVT) const {
2659     assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
2660            "invalid fpext types");
2661     return isFPExtFree(DestVT, SrcVT);
2662   }
2663 
2664   /// Return true if folding a vector load into ExtVal (a sign, zero, or any
2665   /// extend node) is profitable.
2666   virtual bool isVectorLoadExtDesirable(SDValue ExtVal) const { return false; }
2667 
2668   /// Return true if an fneg operation is free to the point where it is never
2669   /// worthwhile to replace it with a bitwise operation.
2670   virtual bool isFNegFree(EVT VT) const {
2671     assert(VT.isFloatingPoint());
2672     return false;
2673   }
2674 
2675   /// Return true if an fabs operation is free to the point where it is never
2676   /// worthwhile to replace it with a bitwise operation.
2677   virtual bool isFAbsFree(EVT VT) const {
2678     assert(VT.isFloatingPoint());
2679     return false;
2680   }
2681 
2682   /// Return true if an FMA operation is faster than a pair of fmul and fadd
2683   /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
2684   /// returns true, otherwise fmuladd is expanded to fmul + fadd.
2685   ///
2686   /// NOTE: This may be called before legalization on types for which FMAs are
2687   /// not legal, but should return true if those types will eventually legalize
2688   /// to types that support FMAs. After legalization, it will only be called on
2689   /// types that support FMAs (via Legal or Custom actions)
2690   virtual bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
2691                                           EVT) const {
2692     return false;
2693   }
2694 
2695   /// IR version
2696   virtual bool isFMAFasterThanFMulAndFAdd(const Function &F, Type *) const {
2697     return false;
2698   }
2699 
2700   /// Returns true if be combined with to form an ISD::FMAD. \p N may be an
2701   /// ISD::FADD, ISD::FSUB, or an ISD::FMUL which will be distributed into an
2702   /// fadd/fsub.
2703   virtual bool isFMADLegal(const SelectionDAG &DAG, const SDNode *N) const {
2704     assert((N->getOpcode() == ISD::FADD || N->getOpcode() == ISD::FSUB ||
2705             N->getOpcode() == ISD::FMUL) &&
2706            "unexpected node in FMAD forming combine");
2707     return isOperationLegal(ISD::FMAD, N->getValueType(0));
2708   }
2709 
2710   /// Return true if it's profitable to narrow operations of type VT1 to
2711   /// VT2. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
2712   /// i32 to i16.
2713   virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
2714     return false;
2715   }
2716 
2717   /// Return true if it is beneficial to convert a load of a constant to
2718   /// just the constant itself.
2719   /// On some targets it might be more efficient to use a combination of
2720   /// arithmetic instructions to materialize the constant instead of loading it
2721   /// from a constant pool.
2722   virtual bool shouldConvertConstantLoadToIntImm(const APInt &Imm,
2723                                                  Type *Ty) const {
2724     return false;
2725   }
2726 
2727   /// Return true if EXTRACT_SUBVECTOR is cheap for extracting this result type
2728   /// from this source type with this index. This is needed because
2729   /// EXTRACT_SUBVECTOR usually has custom lowering that depends on the index of
2730   /// the first element, and only the target knows which lowering is cheap.
2731   virtual bool isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
2732                                        unsigned Index) const {
2733     return false;
2734   }
2735 
2736   /// Try to convert an extract element of a vector binary operation into an
2737   /// extract element followed by a scalar operation.
2738   virtual bool shouldScalarizeBinop(SDValue VecOp) const {
2739     return false;
2740   }
2741 
2742   /// Return true if extraction of a scalar element from the given vector type
2743   /// at the given index is cheap. For example, if scalar operations occur on
2744   /// the same register file as vector operations, then an extract element may
2745   /// be a sub-register rename rather than an actual instruction.
2746   virtual bool isExtractVecEltCheap(EVT VT, unsigned Index) const {
2747     return false;
2748   }
2749 
2750   /// Try to convert math with an overflow comparison into the corresponding DAG
2751   /// node operation. Targets may want to override this independently of whether
2752   /// the operation is legal/custom for the given type because it may obscure
2753   /// matching of other patterns.
2754   virtual bool shouldFormOverflowOp(unsigned Opcode, EVT VT,
2755                                     bool MathUsed) const {
2756     // TODO: The default logic is inherited from code in CodeGenPrepare.
2757     // The opcode should not make a difference by default?
2758     if (Opcode != ISD::UADDO)
2759       return false;
2760 
2761     // Allow the transform as long as we have an integer type that is not
2762     // obviously illegal and unsupported and if the math result is used
2763     // besides the overflow check. On some targets (e.g. SPARC), it is
2764     // not profitable to form on overflow op if the math result has no
2765     // concrete users.
2766     if (VT.isVector())
2767       return false;
2768     return MathUsed && (VT.isSimple() || !isOperationExpand(Opcode, VT));
2769   }
2770 
2771   // Return true if it is profitable to use a scalar input to a BUILD_VECTOR
2772   // even if the vector itself has multiple uses.
2773   virtual bool aggressivelyPreferBuildVectorSources(EVT VecVT) const {
2774     return false;
2775   }
2776 
2777   // Return true if CodeGenPrepare should consider splitting large offset of a
2778   // GEP to make the GEP fit into the addressing mode and can be sunk into the
2779   // same blocks of its users.
2780   virtual bool shouldConsiderGEPOffsetSplit() const { return false; }
2781 
2782   /// Return true if creating a shift of the type by the given
2783   /// amount is not profitable.
2784   virtual bool shouldAvoidTransformToShift(EVT VT, unsigned Amount) const {
2785     return false;
2786   }
2787 
2788   /// Does this target require the clearing of high-order bits in a register
2789   /// passed to the fp16 to fp conversion library function.
2790   virtual bool shouldKeepZExtForFP16Conv() const { return false; }
2791 
2792   //===--------------------------------------------------------------------===//
2793   // Runtime Library hooks
2794   //
2795 
2796   /// Rename the default libcall routine name for the specified libcall.
2797   void setLibcallName(RTLIB::Libcall Call, const char *Name) {
2798     LibcallRoutineNames[Call] = Name;
2799   }
2800 
2801   /// Get the libcall routine name for the specified libcall.
2802   const char *getLibcallName(RTLIB::Libcall Call) const {
2803     return LibcallRoutineNames[Call];
2804   }
2805 
2806   /// Override the default CondCode to be used to test the result of the
2807   /// comparison libcall against zero.
2808   void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
2809     CmpLibcallCCs[Call] = CC;
2810   }
2811 
2812   /// Get the CondCode that's to be used to test the result of the comparison
2813   /// libcall against zero.
2814   ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
2815     return CmpLibcallCCs[Call];
2816   }
2817 
2818   /// Set the CallingConv that should be used for the specified libcall.
2819   void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
2820     LibcallCallingConvs[Call] = CC;
2821   }
2822 
2823   /// Get the CallingConv that should be used for the specified libcall.
2824   CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
2825     return LibcallCallingConvs[Call];
2826   }
2827 
2828   /// Execute target specific actions to finalize target lowering.
2829   /// This is used to set extra flags in MachineFrameInformation and freezing
2830   /// the set of reserved registers.
2831   /// The default implementation just freezes the set of reserved registers.
2832   virtual void finalizeLowering(MachineFunction &MF) const;
2833 
2834   //===----------------------------------------------------------------------===//
2835   //  GlobalISel Hooks
2836   //===----------------------------------------------------------------------===//
2837   /// Check whether or not \p MI needs to be moved close to its uses.
2838   virtual bool shouldLocalize(const MachineInstr &MI, const TargetTransformInfo *TTI) const;
2839 
2840 
2841 private:
2842   const TargetMachine &TM;
2843 
2844   /// Tells the code generator that the target has multiple (allocatable)
2845   /// condition registers that can be used to store the results of comparisons
2846   /// for use by selects and conditional branches. With multiple condition
2847   /// registers, the code generator will not aggressively sink comparisons into
2848   /// the blocks of their users.
2849   bool HasMultipleConditionRegisters;
2850 
2851   /// Tells the code generator that the target has BitExtract instructions.
2852   /// The code generator will aggressively sink "shift"s into the blocks of
2853   /// their users if the users will generate "and" instructions which can be
2854   /// combined with "shift" to BitExtract instructions.
2855   bool HasExtractBitsInsn;
2856 
2857   /// Tells the code generator to bypass slow divide or remainder
2858   /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
2859   /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
2860   /// div/rem when the operands are positive and less than 256.
2861   DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
2862 
2863   /// Tells the code generator that it shouldn't generate extra flow control
2864   /// instructions and should attempt to combine flow control instructions via
2865   /// predication.
2866   bool JumpIsExpensive;
2867 
2868   /// Information about the contents of the high-bits in boolean values held in
2869   /// a type wider than i1. See getBooleanContents.
2870   BooleanContent BooleanContents;
2871 
2872   /// Information about the contents of the high-bits in boolean values held in
2873   /// a type wider than i1. See getBooleanContents.
2874   BooleanContent BooleanFloatContents;
2875 
2876   /// Information about the contents of the high-bits in boolean vector values
2877   /// when the element type is wider than i1. See getBooleanContents.
2878   BooleanContent BooleanVectorContents;
2879 
2880   /// The target scheduling preference: shortest possible total cycles or lowest
2881   /// register usage.
2882   Sched::Preference SchedPreferenceInfo;
2883 
2884   /// The minimum alignment that any argument on the stack needs to have.
2885   Align MinStackArgumentAlignment;
2886 
2887   /// The minimum function alignment (used when optimizing for size, and to
2888   /// prevent explicitly provided alignment from leading to incorrect code).
2889   Align MinFunctionAlignment;
2890 
2891   /// The preferred function alignment (used when alignment unspecified and
2892   /// optimizing for speed).
2893   Align PrefFunctionAlignment;
2894 
2895   /// The preferred loop alignment (in log2 bot in bytes).
2896   Align PrefLoopAlignment;
2897 
2898   /// Size in bits of the maximum atomics size the backend supports.
2899   /// Accesses larger than this will be expanded by AtomicExpandPass.
2900   unsigned MaxAtomicSizeInBitsSupported;
2901 
2902   /// Size in bits of the minimum cmpxchg or ll/sc operation the
2903   /// backend supports.
2904   unsigned MinCmpXchgSizeInBits;
2905 
2906   /// This indicates if the target supports unaligned atomic operations.
2907   bool SupportsUnalignedAtomics;
2908 
2909   /// If set to a physical register, this specifies the register that
2910   /// llvm.savestack/llvm.restorestack should save and restore.
2911   Register StackPointerRegisterToSaveRestore;
2912 
2913   /// This indicates the default register class to use for each ValueType the
2914   /// target supports natively.
2915   const TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
2916   uint16_t NumRegistersForVT[MVT::LAST_VALUETYPE];
2917   MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
2918 
2919   /// This indicates the "representative" register class to use for each
2920   /// ValueType the target supports natively. This information is used by the
2921   /// scheduler to track register pressure. By default, the representative
2922   /// register class is the largest legal super-reg register class of the
2923   /// register class of the specified type. e.g. On x86, i8, i16, and i32's
2924   /// representative class would be GR32.
2925   const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
2926 
2927   /// This indicates the "cost" of the "representative" register class for each
2928   /// ValueType. The cost is used by the scheduler to approximate register
2929   /// pressure.
2930   uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
2931 
2932   /// For any value types we are promoting or expanding, this contains the value
2933   /// type that we are changing to.  For Expanded types, this contains one step
2934   /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
2935   /// (e.g. i64 -> i16).  For types natively supported by the system, this holds
2936   /// the same type (e.g. i32 -> i32).
2937   MVT TransformToType[MVT::LAST_VALUETYPE];
2938 
2939   /// For each operation and each value type, keep a LegalizeAction that
2940   /// indicates how instruction selection should deal with the operation.  Most
2941   /// operations are Legal (aka, supported natively by the target), but
2942   /// operations that are not should be described.  Note that operations on
2943   /// non-legal value types are not described here.
2944   LegalizeAction OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END];
2945 
2946   /// For each load extension type and each value type, keep a LegalizeAction
2947   /// that indicates how instruction selection should deal with a load of a
2948   /// specific value type and extension type. Uses 4-bits to store the action
2949   /// for each of the 4 load ext types.
2950   uint16_t LoadExtActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
2951 
2952   /// For each value type pair keep a LegalizeAction that indicates whether a
2953   /// truncating store of a specific value type and truncating type is legal.
2954   LegalizeAction TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
2955 
2956   /// For each indexed mode and each value type, keep a quad of LegalizeAction
2957   /// that indicates how instruction selection should deal with the load /
2958   /// store / maskedload / maskedstore.
2959   ///
2960   /// The first dimension is the value_type for the reference. The second
2961   /// dimension represents the various modes for load store.
2962   uint16_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
2963 
2964   /// For each condition code (ISD::CondCode) keep a LegalizeAction that
2965   /// indicates how instruction selection should deal with the condition code.
2966   ///
2967   /// Because each CC action takes up 4 bits, we need to have the array size be
2968   /// large enough to fit all of the value types. This can be done by rounding
2969   /// up the MVT::LAST_VALUETYPE value to the next multiple of 8.
2970   uint32_t CondCodeActions[ISD::SETCC_INVALID][(MVT::LAST_VALUETYPE + 7) / 8];
2971 
2972   ValueTypeActionImpl ValueTypeActions;
2973 
2974 private:
2975   LegalizeKind getTypeConversion(LLVMContext &Context, EVT VT) const;
2976 
2977   /// Targets can specify ISD nodes that they would like PerformDAGCombine
2978   /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
2979   /// array.
2980   unsigned char
2981   TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
2982 
2983   /// For operations that must be promoted to a specific type, this holds the
2984   /// destination type.  This map should be sparse, so don't hold it as an
2985   /// array.
2986   ///
2987   /// Targets add entries to this map with AddPromotedToType(..), clients access
2988   /// this with getTypeToPromoteTo(..).
2989   std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
2990     PromoteToType;
2991 
2992   /// Stores the name each libcall.
2993   const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL + 1];
2994 
2995   /// The ISD::CondCode that should be used to test the result of each of the
2996   /// comparison libcall against zero.
2997   ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
2998 
2999   /// Stores the CallingConv that should be used for each libcall.
3000   CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
3001 
3002   /// Set default libcall names and calling conventions.
3003   void InitLibcalls(const Triple &TT);
3004 
3005   /// The bits of IndexedModeActions used to store the legalisation actions
3006   /// We store the data as   | ML | MS |  L |  S | each taking 4 bits.
3007   enum IndexedModeActionsBits {
3008     IMAB_Store = 0,
3009     IMAB_Load = 4,
3010     IMAB_MaskedStore = 8,
3011     IMAB_MaskedLoad = 12
3012   };
3013 
3014   void setIndexedModeAction(unsigned IdxMode, MVT VT, unsigned Shift,
3015                             LegalizeAction Action) {
3016     assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&
3017            (unsigned)Action < 0xf && "Table isn't big enough!");
3018     unsigned Ty = (unsigned)VT.SimpleTy;
3019     IndexedModeActions[Ty][IdxMode] &= ~(0xf << Shift);
3020     IndexedModeActions[Ty][IdxMode] |= ((uint16_t)Action) << Shift;
3021   }
3022 
3023   LegalizeAction getIndexedModeAction(unsigned IdxMode, MVT VT,
3024                                       unsigned Shift) const {
3025     assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&
3026            "Table isn't big enough!");
3027     unsigned Ty = (unsigned)VT.SimpleTy;
3028     return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] >> Shift) & 0xf);
3029   }
3030 
3031 protected:
3032   /// Return true if the extension represented by \p I is free.
3033   /// \pre \p I is a sign, zero, or fp extension and
3034   ///      is[Z|FP]ExtFree of the related types is not true.
3035   virtual bool isExtFreeImpl(const Instruction *I) const { return false; }
3036 
3037   /// Depth that GatherAllAliases should should continue looking for chain
3038   /// dependencies when trying to find a more preferable chain. As an
3039   /// approximation, this should be more than the number of consecutive stores
3040   /// expected to be merged.
3041   unsigned GatherAllAliasesMaxDepth;
3042 
3043   /// \brief Specify maximum number of store instructions per memset call.
3044   ///
3045   /// When lowering \@llvm.memset this field specifies the maximum number of
3046   /// store operations that may be substituted for the call to memset. Targets
3047   /// must set this value based on the cost threshold for that target. Targets
3048   /// should assume that the memset will be done using as many of the largest
3049   /// store operations first, followed by smaller ones, if necessary, per
3050   /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
3051   /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
3052   /// store.  This only applies to setting a constant array of a constant size.
3053   unsigned MaxStoresPerMemset;
3054   /// Likewise for functions with the OptSize attribute.
3055   unsigned MaxStoresPerMemsetOptSize;
3056 
3057   /// \brief Specify maximum number of store instructions per memcpy call.
3058   ///
3059   /// When lowering \@llvm.memcpy this field specifies the maximum number of
3060   /// store operations that may be substituted for a call to memcpy. Targets
3061   /// must set this value based on the cost threshold for that target. Targets
3062   /// should assume that the memcpy will be done using as many of the largest
3063   /// store operations first, followed by smaller ones, if necessary, per
3064   /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
3065   /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
3066   /// and one 1-byte store. This only applies to copying a constant array of
3067   /// constant size.
3068   unsigned MaxStoresPerMemcpy;
3069   /// Likewise for functions with the OptSize attribute.
3070   unsigned MaxStoresPerMemcpyOptSize;
3071   /// \brief Specify max number of store instructions to glue in inlined memcpy.
3072   ///
3073   /// When memcpy is inlined based on MaxStoresPerMemcpy, specify maximum number
3074   /// of store instructions to keep together. This helps in pairing and
3075   //  vectorization later on.
3076   unsigned MaxGluedStoresPerMemcpy = 0;
3077 
3078   /// \brief Specify maximum number of load instructions per memcmp call.
3079   ///
3080   /// When lowering \@llvm.memcmp this field specifies the maximum number of
3081   /// pairs of load operations that may be substituted for a call to memcmp.
3082   /// Targets must set this value based on the cost threshold for that target.
3083   /// Targets should assume that the memcmp will be done using as many of the
3084   /// largest load operations first, followed by smaller ones, if necessary, per
3085   /// alignment restrictions. For example, loading 7 bytes on a 32-bit machine
3086   /// with 32-bit alignment would result in one 4-byte load, a one 2-byte load
3087   /// and one 1-byte load. This only applies to copying a constant array of
3088   /// constant size.
3089   unsigned MaxLoadsPerMemcmp;
3090   /// Likewise for functions with the OptSize attribute.
3091   unsigned MaxLoadsPerMemcmpOptSize;
3092 
3093   /// \brief Specify maximum number of store instructions per memmove call.
3094   ///
3095   /// When lowering \@llvm.memmove this field specifies the maximum number of
3096   /// store instructions that may be substituted for a call to memmove. Targets
3097   /// must set this value based on the cost threshold for that target. Targets
3098   /// should assume that the memmove will be done using as many of the largest
3099   /// store operations first, followed by smaller ones, if necessary, per
3100   /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
3101   /// with 8-bit alignment would result in nine 1-byte stores.  This only
3102   /// applies to copying a constant array of constant size.
3103   unsigned MaxStoresPerMemmove;
3104   /// Likewise for functions with the OptSize attribute.
3105   unsigned MaxStoresPerMemmoveOptSize;
3106 
3107   /// Tells the code generator that select is more expensive than a branch if
3108   /// the branch is usually predicted right.
3109   bool PredictableSelectIsExpensive;
3110 
3111   /// \see enableExtLdPromotion.
3112   bool EnableExtLdPromotion;
3113 
3114   /// Return true if the value types that can be represented by the specified
3115   /// register class are all legal.
3116   bool isLegalRC(const TargetRegisterInfo &TRI,
3117                  const TargetRegisterClass &RC) const;
3118 
3119   /// Replace/modify any TargetFrameIndex operands with a targte-dependent
3120   /// sequence of memory operands that is recognized by PrologEpilogInserter.
3121   MachineBasicBlock *emitPatchPoint(MachineInstr &MI,
3122                                     MachineBasicBlock *MBB) const;
3123 
3124   bool IsStrictFPEnabled;
3125 };
3126 
3127 /// This class defines information used to lower LLVM code to legal SelectionDAG
3128 /// operators that the target instruction selector can accept natively.
3129 ///
3130 /// This class also defines callbacks that targets must implement to lower
3131 /// target-specific constructs to SelectionDAG operators.
3132 class TargetLowering : public TargetLoweringBase {
3133 public:
3134   struct DAGCombinerInfo;
3135   struct MakeLibCallOptions;
3136 
3137   TargetLowering(const TargetLowering &) = delete;
3138   TargetLowering &operator=(const TargetLowering &) = delete;
3139 
3140   explicit TargetLowering(const TargetMachine &TM);
3141 
3142   bool isPositionIndependent() const;
3143 
3144   virtual bool isSDNodeSourceOfDivergence(const SDNode *N,
3145                                           FunctionLoweringInfo *FLI,
3146                                           LegacyDivergenceAnalysis *DA) const {
3147     return false;
3148   }
3149 
3150   virtual bool isSDNodeAlwaysUniform(const SDNode * N) const {
3151     return false;
3152   }
3153 
3154   /// Returns true by value, base pointer and offset pointer and addressing mode
3155   /// by reference if the node's address can be legally represented as
3156   /// pre-indexed load / store address.
3157   virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
3158                                          SDValue &/*Offset*/,
3159                                          ISD::MemIndexedMode &/*AM*/,
3160                                          SelectionDAG &/*DAG*/) const {
3161     return false;
3162   }
3163 
3164   /// Returns true by value, base pointer and offset pointer and addressing mode
3165   /// by reference if this node can be combined with a load / store to form a
3166   /// post-indexed load / store.
3167   virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
3168                                           SDValue &/*Base*/,
3169                                           SDValue &/*Offset*/,
3170                                           ISD::MemIndexedMode &/*AM*/,
3171                                           SelectionDAG &/*DAG*/) const {
3172     return false;
3173   }
3174 
3175   /// Returns true if the specified base+offset is a legal indexed addressing
3176   /// mode for this target. \p MI is the load or store instruction that is being
3177   /// considered for transformation.
3178   virtual bool isIndexingLegal(MachineInstr &MI, Register Base, Register Offset,
3179                                bool IsPre, MachineRegisterInfo &MRI) const {
3180     return false;
3181   }
3182 
3183   /// Return the entry encoding for a jump table in the current function.  The
3184   /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
3185   virtual unsigned getJumpTableEncoding() const;
3186 
3187   virtual const MCExpr *
3188   LowerCustomJumpTableEntry(const MachineJumpTableInfo * /*MJTI*/,
3189                             const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
3190                             MCContext &/*Ctx*/) const {
3191     llvm_unreachable("Need to implement this hook if target has custom JTIs");
3192   }
3193 
3194   /// Returns relocation base for the given PIC jumptable.
3195   virtual SDValue getPICJumpTableRelocBase(SDValue Table,
3196                                            SelectionDAG &DAG) const;
3197 
3198   /// This returns the relocation base for the given PIC jumptable, the same as
3199   /// getPICJumpTableRelocBase, but as an MCExpr.
3200   virtual const MCExpr *
3201   getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
3202                                unsigned JTI, MCContext &Ctx) const;
3203 
3204   /// Return true if folding a constant offset with the given GlobalAddress is
3205   /// legal.  It is frequently not legal in PIC relocation models.
3206   virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
3207 
3208   bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
3209                             SDValue &Chain) const;
3210 
3211   void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
3212                            SDValue &NewRHS, ISD::CondCode &CCCode,
3213                            const SDLoc &DL, const SDValue OldLHS,
3214                            const SDValue OldRHS) const;
3215 
3216   void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
3217                            SDValue &NewRHS, ISD::CondCode &CCCode,
3218                            const SDLoc &DL, const SDValue OldLHS,
3219                            const SDValue OldRHS, SDValue &Chain,
3220                            bool IsSignaling = false) const;
3221 
3222   /// Returns a pair of (return value, chain).
3223   /// It is an error to pass RTLIB::UNKNOWN_LIBCALL as \p LC.
3224   std::pair<SDValue, SDValue> makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC,
3225                                           EVT RetVT, ArrayRef<SDValue> Ops,
3226                                           MakeLibCallOptions CallOptions,
3227                                           const SDLoc &dl,
3228                                           SDValue Chain = SDValue()) const;
3229 
3230   /// Check whether parameters to a call that are passed in callee saved
3231   /// registers are the same as from the calling function.  This needs to be
3232   /// checked for tail call eligibility.
3233   bool parametersInCSRMatch(const MachineRegisterInfo &MRI,
3234       const uint32_t *CallerPreservedMask,
3235       const SmallVectorImpl<CCValAssign> &ArgLocs,
3236       const SmallVectorImpl<SDValue> &OutVals) const;
3237 
3238   //===--------------------------------------------------------------------===//
3239   // TargetLowering Optimization Methods
3240   //
3241 
3242   /// A convenience struct that encapsulates a DAG, and two SDValues for
3243   /// returning information from TargetLowering to its clients that want to
3244   /// combine.
3245   struct TargetLoweringOpt {
3246     SelectionDAG &DAG;
3247     bool LegalTys;
3248     bool LegalOps;
3249     SDValue Old;
3250     SDValue New;
3251 
3252     explicit TargetLoweringOpt(SelectionDAG &InDAG,
3253                                bool LT, bool LO) :
3254       DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
3255 
3256     bool LegalTypes() const { return LegalTys; }
3257     bool LegalOperations() const { return LegalOps; }
3258 
3259     bool CombineTo(SDValue O, SDValue N) {
3260       Old = O;
3261       New = N;
3262       return true;
3263     }
3264   };
3265 
3266   /// Determines the optimal series of memory ops to replace the memset / memcpy.
3267   /// Return true if the number of memory ops is below the threshold (Limit).
3268   /// It returns the types of the sequence of memory ops to perform
3269   /// memset / memcpy by reference.
3270   bool findOptimalMemOpLowering(std::vector<EVT> &MemOps, unsigned Limit,
3271                                 const MemOp &Op, unsigned DstAS, unsigned SrcAS,
3272                                 const AttributeList &FuncAttributes) const;
3273 
3274   /// Check to see if the specified operand of the specified instruction is a
3275   /// constant integer.  If so, check to see if there are any bits set in the
3276   /// constant that are not demanded.  If so, shrink the constant and return
3277   /// true.
3278   bool ShrinkDemandedConstant(SDValue Op, const APInt &DemandedBits,
3279                               const APInt &DemandedElts,
3280                               TargetLoweringOpt &TLO) const;
3281 
3282   /// Helper wrapper around ShrinkDemandedConstant, demanding all elements.
3283   bool ShrinkDemandedConstant(SDValue Op, const APInt &DemandedBits,
3284                               TargetLoweringOpt &TLO) const;
3285 
3286   // Target hook to do target-specific const optimization, which is called by
3287   // ShrinkDemandedConstant. This function should return true if the target
3288   // doesn't want ShrinkDemandedConstant to further optimize the constant.
3289   virtual bool targetShrinkDemandedConstant(SDValue Op,
3290                                             const APInt &DemandedBits,
3291                                             const APInt &DemandedElts,
3292                                             TargetLoweringOpt &TLO) const {
3293     return false;
3294   }
3295 
3296   /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.  This
3297   /// uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
3298   /// generalized for targets with other types of implicit widening casts.
3299   bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
3300                         TargetLoweringOpt &TLO) const;
3301 
3302   /// Look at Op.  At this point, we know that only the DemandedBits bits of the
3303   /// result of Op are ever used downstream.  If we can use this information to
3304   /// simplify Op, create a new simplified DAG node and return true, returning
3305   /// the original and new nodes in Old and New.  Otherwise, analyze the
3306   /// expression and return a mask of KnownOne and KnownZero bits for the
3307   /// expression (used to simplify the caller).  The KnownZero/One bits may only
3308   /// be accurate for those bits in the Demanded masks.
3309   /// \p AssumeSingleUse When this parameter is true, this function will
3310   ///    attempt to simplify \p Op even if there are multiple uses.
3311   ///    Callers are responsible for correctly updating the DAG based on the
3312   ///    results of this function, because simply replacing replacing TLO.Old
3313   ///    with TLO.New will be incorrect when this parameter is true and TLO.Old
3314   ///    has multiple uses.
3315   bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
3316                             const APInt &DemandedElts, KnownBits &Known,
3317                             TargetLoweringOpt &TLO, unsigned Depth = 0,
3318                             bool AssumeSingleUse = false) const;
3319 
3320   /// Helper wrapper around SimplifyDemandedBits, demanding all elements.
3321   /// Adds Op back to the worklist upon success.
3322   bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
3323                             KnownBits &Known, TargetLoweringOpt &TLO,
3324                             unsigned Depth = 0,
3325                             bool AssumeSingleUse = false) const;
3326 
3327   /// Helper wrapper around SimplifyDemandedBits.
3328   /// Adds Op back to the worklist upon success.
3329   bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
3330                             DAGCombinerInfo &DCI) const;
3331 
3332   /// More limited version of SimplifyDemandedBits that can be used to "look
3333   /// through" ops that don't contribute to the DemandedBits/DemandedElts -
3334   /// bitwise ops etc.
3335   SDValue SimplifyMultipleUseDemandedBits(SDValue Op, const APInt &DemandedBits,
3336                                           const APInt &DemandedElts,
3337                                           SelectionDAG &DAG,
3338                                           unsigned Depth) const;
3339 
3340   /// Helper wrapper around SimplifyMultipleUseDemandedBits, demanding all
3341   /// elements.
3342   SDValue SimplifyMultipleUseDemandedBits(SDValue Op, const APInt &DemandedBits,
3343                                           SelectionDAG &DAG,
3344                                           unsigned Depth = 0) const;
3345 
3346   /// Helper wrapper around SimplifyMultipleUseDemandedBits, demanding all
3347   /// bits from only some vector elements.
3348   SDValue SimplifyMultipleUseDemandedVectorElts(SDValue Op,
3349                                                 const APInt &DemandedElts,
3350                                                 SelectionDAG &DAG,
3351                                                 unsigned Depth = 0) const;
3352 
3353   /// Look at Vector Op. At this point, we know that only the DemandedElts
3354   /// elements of the result of Op are ever used downstream.  If we can use
3355   /// this information to simplify Op, create a new simplified DAG node and
3356   /// return true, storing the original and new nodes in TLO.
3357   /// Otherwise, analyze the expression and return a mask of KnownUndef and
3358   /// KnownZero elements for the expression (used to simplify the caller).
3359   /// The KnownUndef/Zero elements may only be accurate for those bits
3360   /// in the DemandedMask.
3361   /// \p AssumeSingleUse When this parameter is true, this function will
3362   ///    attempt to simplify \p Op even if there are multiple uses.
3363   ///    Callers are responsible for correctly updating the DAG based on the
3364   ///    results of this function, because simply replacing replacing TLO.Old
3365   ///    with TLO.New will be incorrect when this parameter is true and TLO.Old
3366   ///    has multiple uses.
3367   bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedEltMask,
3368                                   APInt &KnownUndef, APInt &KnownZero,
3369                                   TargetLoweringOpt &TLO, unsigned Depth = 0,
3370                                   bool AssumeSingleUse = false) const;
3371 
3372   /// Helper wrapper around SimplifyDemandedVectorElts.
3373   /// Adds Op back to the worklist upon success.
3374   bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedElts,
3375                                   APInt &KnownUndef, APInt &KnownZero,
3376                                   DAGCombinerInfo &DCI) const;
3377 
3378   /// Determine which of the bits specified in Mask are known to be either zero
3379   /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
3380   /// argument allows us to only collect the known bits that are shared by the
3381   /// requested vector elements.
3382   virtual void computeKnownBitsForTargetNode(const SDValue Op,
3383                                              KnownBits &Known,
3384                                              const APInt &DemandedElts,
3385                                              const SelectionDAG &DAG,
3386                                              unsigned Depth = 0) const;
3387 
3388   /// Determine which of the bits specified in Mask are known to be either zero
3389   /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
3390   /// argument allows us to only collect the known bits that are shared by the
3391   /// requested vector elements. This is for GISel.
3392   virtual void computeKnownBitsForTargetInstr(GISelKnownBits &Analysis,
3393                                               Register R, KnownBits &Known,
3394                                               const APInt &DemandedElts,
3395                                               const MachineRegisterInfo &MRI,
3396                                               unsigned Depth = 0) const;
3397 
3398   /// Determine the known alignment for the pointer value \p R. This is can
3399   /// typically be inferred from the number of low known 0 bits. However, for a
3400   /// pointer with a non-integral address space, the alignment value may be
3401   /// independent from the known low bits.
3402   virtual Align computeKnownAlignForTargetInstr(GISelKnownBits &Analysis,
3403                                                 Register R,
3404                                                 const MachineRegisterInfo &MRI,
3405                                                 unsigned Depth = 0) const;
3406 
3407   /// Determine which of the bits of FrameIndex \p FIOp are known to be 0.
3408   /// Default implementation computes low bits based on alignment
3409   /// information. This should preserve known bits passed into it.
3410   virtual void computeKnownBitsForFrameIndex(int FIOp,
3411                                              KnownBits &Known,
3412                                              const MachineFunction &MF) const;
3413 
3414   /// This method can be implemented by targets that want to expose additional
3415   /// information about sign bits to the DAG Combiner. The DemandedElts
3416   /// argument allows us to only collect the minimum sign bits that are shared
3417   /// by the requested vector elements.
3418   virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
3419                                                    const APInt &DemandedElts,
3420                                                    const SelectionDAG &DAG,
3421                                                    unsigned Depth = 0) const;
3422 
3423   /// This method can be implemented by targets that want to expose additional
3424   /// information about sign bits to GlobalISel combiners. The DemandedElts
3425   /// argument allows us to only collect the minimum sign bits that are shared
3426   /// by the requested vector elements.
3427   virtual unsigned computeNumSignBitsForTargetInstr(GISelKnownBits &Analysis,
3428                                                     Register R,
3429                                                     const APInt &DemandedElts,
3430                                                     const MachineRegisterInfo &MRI,
3431                                                     unsigned Depth = 0) const;
3432 
3433   /// Attempt to simplify any target nodes based on the demanded vector
3434   /// elements, returning true on success. Otherwise, analyze the expression and
3435   /// return a mask of KnownUndef and KnownZero elements for the expression
3436   /// (used to simplify the caller). The KnownUndef/Zero elements may only be
3437   /// accurate for those bits in the DemandedMask.
3438   virtual bool SimplifyDemandedVectorEltsForTargetNode(
3439       SDValue Op, const APInt &DemandedElts, APInt &KnownUndef,
3440       APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth = 0) const;
3441 
3442   /// Attempt to simplify any target nodes based on the demanded bits/elts,
3443   /// returning true on success. Otherwise, analyze the
3444   /// expression and return a mask of KnownOne and KnownZero bits for the
3445   /// expression (used to simplify the caller).  The KnownZero/One bits may only
3446   /// be accurate for those bits in the Demanded masks.
3447   virtual bool SimplifyDemandedBitsForTargetNode(SDValue Op,
3448                                                  const APInt &DemandedBits,
3449                                                  const APInt &DemandedElts,
3450                                                  KnownBits &Known,
3451                                                  TargetLoweringOpt &TLO,
3452                                                  unsigned Depth = 0) const;
3453 
3454   /// More limited version of SimplifyDemandedBits that can be used to "look
3455   /// through" ops that don't contribute to the DemandedBits/DemandedElts -
3456   /// bitwise ops etc.
3457   virtual SDValue SimplifyMultipleUseDemandedBitsForTargetNode(
3458       SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
3459       SelectionDAG &DAG, unsigned Depth) const;
3460 
3461   /// Tries to build a legal vector shuffle using the provided parameters
3462   /// or equivalent variations. The Mask argument maybe be modified as the
3463   /// function tries different variations.
3464   /// Returns an empty SDValue if the operation fails.
3465   SDValue buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0,
3466                                   SDValue N1, MutableArrayRef<int> Mask,
3467                                   SelectionDAG &DAG) const;
3468 
3469   /// This method returns the constant pool value that will be loaded by LD.
3470   /// NOTE: You must check for implicit extensions of the constant by LD.
3471   virtual const Constant *getTargetConstantFromLoad(LoadSDNode *LD) const;
3472 
3473   /// If \p SNaN is false, \returns true if \p Op is known to never be any
3474   /// NaN. If \p sNaN is true, returns if \p Op is known to never be a signaling
3475   /// NaN.
3476   virtual bool isKnownNeverNaNForTargetNode(SDValue Op,
3477                                             const SelectionDAG &DAG,
3478                                             bool SNaN = false,
3479                                             unsigned Depth = 0) const;
3480   struct DAGCombinerInfo {
3481     void *DC;  // The DAG Combiner object.
3482     CombineLevel Level;
3483     bool CalledByLegalizer;
3484 
3485   public:
3486     SelectionDAG &DAG;
3487 
3488     DAGCombinerInfo(SelectionDAG &dag, CombineLevel level,  bool cl, void *dc)
3489       : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
3490 
3491     bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
3492     bool isBeforeLegalizeOps() const { return Level < AfterLegalizeVectorOps; }
3493     bool isAfterLegalizeDAG() const { return Level >= AfterLegalizeDAG; }
3494     CombineLevel getDAGCombineLevel() { return Level; }
3495     bool isCalledByLegalizer() const { return CalledByLegalizer; }
3496 
3497     void AddToWorklist(SDNode *N);
3498     SDValue CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo = true);
3499     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
3500     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
3501 
3502     bool recursivelyDeleteUnusedNodes(SDNode *N);
3503 
3504     void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
3505   };
3506 
3507   /// Return if the N is a constant or constant vector equal to the true value
3508   /// from getBooleanContents().
3509   bool isConstTrueVal(const SDNode *N) const;
3510 
3511   /// Return if the N is a constant or constant vector equal to the false value
3512   /// from getBooleanContents().
3513   bool isConstFalseVal(const SDNode *N) const;
3514 
3515   /// Return if \p N is a True value when extended to \p VT.
3516   bool isExtendedTrueVal(const ConstantSDNode *N, EVT VT, bool SExt) const;
3517 
3518   /// Try to simplify a setcc built with the specified operands and cc. If it is
3519   /// unable to simplify it, return a null SDValue.
3520   SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
3521                         bool foldBooleans, DAGCombinerInfo &DCI,
3522                         const SDLoc &dl) const;
3523 
3524   // For targets which wrap address, unwrap for analysis.
3525   virtual SDValue unwrapAddress(SDValue N) const { return N; }
3526 
3527   /// Returns true (and the GlobalValue and the offset) if the node is a
3528   /// GlobalAddress + offset.
3529   virtual bool
3530   isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
3531 
3532   /// This method will be invoked for all target nodes and for any
3533   /// target-independent nodes that the target has registered with invoke it
3534   /// for.
3535   ///
3536   /// The semantics are as follows:
3537   /// Return Value:
3538   ///   SDValue.Val == 0   - No change was made
3539   ///   SDValue.Val == N   - N was replaced, is dead, and is already handled.
3540   ///   otherwise          - N should be replaced by the returned Operand.
3541   ///
3542   /// In addition, methods provided by DAGCombinerInfo may be used to perform
3543   /// more complex transformations.
3544   ///
3545   virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
3546 
3547   /// Return true if it is profitable to move this shift by a constant amount
3548   /// though its operand, adjusting any immediate operands as necessary to
3549   /// preserve semantics. This transformation may not be desirable if it
3550   /// disrupts a particularly auspicious target-specific tree (e.g. bitfield
3551   /// extraction in AArch64). By default, it returns true.
3552   ///
3553   /// @param N the shift node
3554   /// @param Level the current DAGCombine legalization level.
3555   virtual bool isDesirableToCommuteWithShift(const SDNode *N,
3556                                              CombineLevel Level) const {
3557     return true;
3558   }
3559 
3560   /// Return true if the target has native support for the specified value type
3561   /// and it is 'desirable' to use the type for the given node type. e.g. On x86
3562   /// i16 is legal, but undesirable since i16 instruction encodings are longer
3563   /// and some i16 instructions are slow.
3564   virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
3565     // By default, assume all legal types are desirable.
3566     return isTypeLegal(VT);
3567   }
3568 
3569   /// Return true if it is profitable for dag combiner to transform a floating
3570   /// point op of specified opcode to a equivalent op of an integer
3571   /// type. e.g. f32 load -> i32 load can be profitable on ARM.
3572   virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
3573                                                  EVT /*VT*/) const {
3574     return false;
3575   }
3576 
3577   /// This method query the target whether it is beneficial for dag combiner to
3578   /// promote the specified node. If true, it should return the desired
3579   /// promotion type by reference.
3580   virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
3581     return false;
3582   }
3583 
3584   /// Return true if the target supports swifterror attribute. It optimizes
3585   /// loads and stores to reading and writing a specific register.
3586   virtual bool supportSwiftError() const {
3587     return false;
3588   }
3589 
3590   /// Return true if the target supports that a subset of CSRs for the given
3591   /// machine function is handled explicitly via copies.
3592   virtual bool supportSplitCSR(MachineFunction *MF) const {
3593     return false;
3594   }
3595 
3596   /// Perform necessary initialization to handle a subset of CSRs explicitly
3597   /// via copies. This function is called at the beginning of instruction
3598   /// selection.
3599   virtual void initializeSplitCSR(MachineBasicBlock *Entry) const {
3600     llvm_unreachable("Not Implemented");
3601   }
3602 
3603   /// Insert explicit copies in entry and exit blocks. We copy a subset of
3604   /// CSRs to virtual registers in the entry block, and copy them back to
3605   /// physical registers in the exit blocks. This function is called at the end
3606   /// of instruction selection.
3607   virtual void insertCopiesSplitCSR(
3608       MachineBasicBlock *Entry,
3609       const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
3610     llvm_unreachable("Not Implemented");
3611   }
3612 
3613   /// Return the newly negated expression if the cost is not expensive and
3614   /// set the cost in \p Cost to indicate that if it is cheaper or neutral to
3615   /// do the negation.
3616   virtual SDValue getNegatedExpression(SDValue Op, SelectionDAG &DAG,
3617                                        bool LegalOps, bool OptForSize,
3618                                        NegatibleCost &Cost,
3619                                        unsigned Depth = 0) const;
3620 
3621   /// This is the helper function to return the newly negated expression only
3622   /// when the cost is cheaper.
3623   SDValue getCheaperNegatedExpression(SDValue Op, SelectionDAG &DAG,
3624                                       bool LegalOps, bool OptForSize,
3625                                       unsigned Depth = 0) const {
3626     NegatibleCost Cost = NegatibleCost::Expensive;
3627     SDValue Neg =
3628         getNegatedExpression(Op, DAG, LegalOps, OptForSize, Cost, Depth);
3629     if (Neg && Cost == NegatibleCost::Cheaper)
3630       return Neg;
3631     // Remove the new created node to avoid the side effect to the DAG.
3632     if (Neg && Neg.getNode()->use_empty())
3633       DAG.RemoveDeadNode(Neg.getNode());
3634     return SDValue();
3635   }
3636 
3637   /// This is the helper function to return the newly negated expression if
3638   /// the cost is not expensive.
3639   SDValue getNegatedExpression(SDValue Op, SelectionDAG &DAG, bool LegalOps,
3640                                bool OptForSize, unsigned Depth = 0) const {
3641     NegatibleCost Cost = NegatibleCost::Expensive;
3642     return getNegatedExpression(Op, DAG, LegalOps, OptForSize, Cost, Depth);
3643   }
3644 
3645   //===--------------------------------------------------------------------===//
3646   // Lowering methods - These methods must be implemented by targets so that
3647   // the SelectionDAGBuilder code knows how to lower these.
3648   //
3649 
3650   /// Target-specific splitting of values into parts that fit a register
3651   /// storing a legal type
3652   virtual bool splitValueIntoRegisterParts(SelectionDAG &DAG, const SDLoc &DL,
3653                                            SDValue Val, SDValue *Parts,
3654                                            unsigned NumParts, MVT PartVT,
3655                                            Optional<CallingConv::ID> CC) const {
3656     return false;
3657   }
3658 
3659   /// Target-specific combining of register parts into its original value
3660   virtual SDValue
3661   joinRegisterPartsIntoValue(SelectionDAG &DAG, const SDLoc &DL,
3662                              const SDValue *Parts, unsigned NumParts,
3663                              MVT PartVT, EVT ValueVT,
3664                              Optional<CallingConv::ID> CC) const {
3665     return SDValue();
3666   }
3667 
3668   /// This hook must be implemented to lower the incoming (formal) arguments,
3669   /// described by the Ins array, into the specified DAG. The implementation
3670   /// should fill in the InVals array with legal-type argument values, and
3671   /// return the resulting token chain value.
3672   virtual SDValue LowerFormalArguments(
3673       SDValue /*Chain*/, CallingConv::ID /*CallConv*/, bool /*isVarArg*/,
3674       const SmallVectorImpl<ISD::InputArg> & /*Ins*/, const SDLoc & /*dl*/,
3675       SelectionDAG & /*DAG*/, SmallVectorImpl<SDValue> & /*InVals*/) const {
3676     llvm_unreachable("Not Implemented");
3677   }
3678 
3679   /// This structure contains all information that is necessary for lowering
3680   /// calls. It is passed to TLI::LowerCallTo when the SelectionDAG builder
3681   /// needs to lower a call, and targets will see this struct in their LowerCall
3682   /// implementation.
3683   struct CallLoweringInfo {
3684     SDValue Chain;
3685     Type *RetTy = nullptr;
3686     bool RetSExt           : 1;
3687     bool RetZExt           : 1;
3688     bool IsVarArg          : 1;
3689     bool IsInReg           : 1;
3690     bool DoesNotReturn     : 1;
3691     bool IsReturnValueUsed : 1;
3692     bool IsConvergent      : 1;
3693     bool IsPatchPoint      : 1;
3694     bool IsPreallocated : 1;
3695     bool NoMerge           : 1;
3696 
3697     // IsTailCall should be modified by implementations of
3698     // TargetLowering::LowerCall that perform tail call conversions.
3699     bool IsTailCall = false;
3700 
3701     // Is Call lowering done post SelectionDAG type legalization.
3702     bool IsPostTypeLegalization = false;
3703 
3704     unsigned NumFixedArgs = -1;
3705     CallingConv::ID CallConv = CallingConv::C;
3706     SDValue Callee;
3707     ArgListTy Args;
3708     SelectionDAG &DAG;
3709     SDLoc DL;
3710     const CallBase *CB = nullptr;
3711     SmallVector<ISD::OutputArg, 32> Outs;
3712     SmallVector<SDValue, 32> OutVals;
3713     SmallVector<ISD::InputArg, 32> Ins;
3714     SmallVector<SDValue, 4> InVals;
3715 
3716     CallLoweringInfo(SelectionDAG &DAG)
3717         : RetSExt(false), RetZExt(false), IsVarArg(false), IsInReg(false),
3718           DoesNotReturn(false), IsReturnValueUsed(true), IsConvergent(false),
3719           IsPatchPoint(false), IsPreallocated(false), NoMerge(false),
3720           DAG(DAG) {}
3721 
3722     CallLoweringInfo &setDebugLoc(const SDLoc &dl) {
3723       DL = dl;
3724       return *this;
3725     }
3726 
3727     CallLoweringInfo &setChain(SDValue InChain) {
3728       Chain = InChain;
3729       return *this;
3730     }
3731 
3732     // setCallee with target/module-specific attributes
3733     CallLoweringInfo &setLibCallee(CallingConv::ID CC, Type *ResultType,
3734                                    SDValue Target, ArgListTy &&ArgsList) {
3735       RetTy = ResultType;
3736       Callee = Target;
3737       CallConv = CC;
3738       NumFixedArgs = ArgsList.size();
3739       Args = std::move(ArgsList);
3740 
3741       DAG.getTargetLoweringInfo().markLibCallAttributes(
3742           &(DAG.getMachineFunction()), CC, Args);
3743       return *this;
3744     }
3745 
3746     CallLoweringInfo &setCallee(CallingConv::ID CC, Type *ResultType,
3747                                 SDValue Target, ArgListTy &&ArgsList) {
3748       RetTy = ResultType;
3749       Callee = Target;
3750       CallConv = CC;
3751       NumFixedArgs = ArgsList.size();
3752       Args = std::move(ArgsList);
3753       return *this;
3754     }
3755 
3756     CallLoweringInfo &setCallee(Type *ResultType, FunctionType *FTy,
3757                                 SDValue Target, ArgListTy &&ArgsList,
3758                                 const CallBase &Call) {
3759       RetTy = ResultType;
3760 
3761       IsInReg = Call.hasRetAttr(Attribute::InReg);
3762       DoesNotReturn =
3763           Call.doesNotReturn() ||
3764           (!isa<InvokeInst>(Call) && isa<UnreachableInst>(Call.getNextNode()));
3765       IsVarArg = FTy->isVarArg();
3766       IsReturnValueUsed = !Call.use_empty();
3767       RetSExt = Call.hasRetAttr(Attribute::SExt);
3768       RetZExt = Call.hasRetAttr(Attribute::ZExt);
3769       NoMerge = Call.hasFnAttr(Attribute::NoMerge);
3770 
3771       Callee = Target;
3772 
3773       CallConv = Call.getCallingConv();
3774       NumFixedArgs = FTy->getNumParams();
3775       Args = std::move(ArgsList);
3776 
3777       CB = &Call;
3778 
3779       return *this;
3780     }
3781 
3782     CallLoweringInfo &setInRegister(bool Value = true) {
3783       IsInReg = Value;
3784       return *this;
3785     }
3786 
3787     CallLoweringInfo &setNoReturn(bool Value = true) {
3788       DoesNotReturn = Value;
3789       return *this;
3790     }
3791 
3792     CallLoweringInfo &setVarArg(bool Value = true) {
3793       IsVarArg = Value;
3794       return *this;
3795     }
3796 
3797     CallLoweringInfo &setTailCall(bool Value = true) {
3798       IsTailCall = Value;
3799       return *this;
3800     }
3801 
3802     CallLoweringInfo &setDiscardResult(bool Value = true) {
3803       IsReturnValueUsed = !Value;
3804       return *this;
3805     }
3806 
3807     CallLoweringInfo &setConvergent(bool Value = true) {
3808       IsConvergent = Value;
3809       return *this;
3810     }
3811 
3812     CallLoweringInfo &setSExtResult(bool Value = true) {
3813       RetSExt = Value;
3814       return *this;
3815     }
3816 
3817     CallLoweringInfo &setZExtResult(bool Value = true) {
3818       RetZExt = Value;
3819       return *this;
3820     }
3821 
3822     CallLoweringInfo &setIsPatchPoint(bool Value = true) {
3823       IsPatchPoint = Value;
3824       return *this;
3825     }
3826 
3827     CallLoweringInfo &setIsPreallocated(bool Value = true) {
3828       IsPreallocated = Value;
3829       return *this;
3830     }
3831 
3832     CallLoweringInfo &setIsPostTypeLegalization(bool Value=true) {
3833       IsPostTypeLegalization = Value;
3834       return *this;
3835     }
3836 
3837     ArgListTy &getArgs() {
3838       return Args;
3839     }
3840   };
3841 
3842   /// This structure is used to pass arguments to makeLibCall function.
3843   struct MakeLibCallOptions {
3844     // By passing type list before soften to makeLibCall, the target hook
3845     // shouldExtendTypeInLibCall can get the original type before soften.
3846     ArrayRef<EVT> OpsVTBeforeSoften;
3847     EVT RetVTBeforeSoften;
3848     bool IsSExt : 1;
3849     bool DoesNotReturn : 1;
3850     bool IsReturnValueUsed : 1;
3851     bool IsPostTypeLegalization : 1;
3852     bool IsSoften : 1;
3853 
3854     MakeLibCallOptions()
3855         : IsSExt(false), DoesNotReturn(false), IsReturnValueUsed(true),
3856           IsPostTypeLegalization(false), IsSoften(false) {}
3857 
3858     MakeLibCallOptions &setSExt(bool Value = true) {
3859       IsSExt = Value;
3860       return *this;
3861     }
3862 
3863     MakeLibCallOptions &setNoReturn(bool Value = true) {
3864       DoesNotReturn = Value;
3865       return *this;
3866     }
3867 
3868     MakeLibCallOptions &setDiscardResult(bool Value = true) {
3869       IsReturnValueUsed = !Value;
3870       return *this;
3871     }
3872 
3873     MakeLibCallOptions &setIsPostTypeLegalization(bool Value = true) {
3874       IsPostTypeLegalization = Value;
3875       return *this;
3876     }
3877 
3878     MakeLibCallOptions &setTypeListBeforeSoften(ArrayRef<EVT> OpsVT, EVT RetVT,
3879                                                 bool Value = true) {
3880       OpsVTBeforeSoften = OpsVT;
3881       RetVTBeforeSoften = RetVT;
3882       IsSoften = Value;
3883       return *this;
3884     }
3885   };
3886 
3887   /// This function lowers an abstract call to a function into an actual call.
3888   /// This returns a pair of operands.  The first element is the return value
3889   /// for the function (if RetTy is not VoidTy).  The second element is the
3890   /// outgoing token chain. It calls LowerCall to do the actual lowering.
3891   std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
3892 
3893   /// This hook must be implemented to lower calls into the specified
3894   /// DAG. The outgoing arguments to the call are described by the Outs array,
3895   /// and the values to be returned by the call are described by the Ins
3896   /// array. The implementation should fill in the InVals array with legal-type
3897   /// return values from the call, and return the resulting token chain value.
3898   virtual SDValue
3899     LowerCall(CallLoweringInfo &/*CLI*/,
3900               SmallVectorImpl<SDValue> &/*InVals*/) const {
3901     llvm_unreachable("Not Implemented");
3902   }
3903 
3904   /// Target-specific cleanup for formal ByVal parameters.
3905   virtual void HandleByVal(CCState *, unsigned &, Align) const {}
3906 
3907   /// This hook should be implemented to check whether the return values
3908   /// described by the Outs array can fit into the return registers.  If false
3909   /// is returned, an sret-demotion is performed.
3910   virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
3911                               MachineFunction &/*MF*/, bool /*isVarArg*/,
3912                const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
3913                LLVMContext &/*Context*/) const
3914   {
3915     // Return true by default to get preexisting behavior.
3916     return true;
3917   }
3918 
3919   /// This hook must be implemented to lower outgoing return values, described
3920   /// by the Outs array, into the specified DAG. The implementation should
3921   /// return the resulting token chain value.
3922   virtual SDValue LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
3923                               bool /*isVarArg*/,
3924                               const SmallVectorImpl<ISD::OutputArg> & /*Outs*/,
3925                               const SmallVectorImpl<SDValue> & /*OutVals*/,
3926                               const SDLoc & /*dl*/,
3927                               SelectionDAG & /*DAG*/) const {
3928     llvm_unreachable("Not Implemented");
3929   }
3930 
3931   /// Return true if result of the specified node is used by a return node
3932   /// only. It also compute and return the input chain for the tail call.
3933   ///
3934   /// This is used to determine whether it is possible to codegen a libcall as
3935   /// tail call at legalization time.
3936   virtual bool isUsedByReturnOnly(SDNode *, SDValue &/*Chain*/) const {
3937     return false;
3938   }
3939 
3940   /// Return true if the target may be able emit the call instruction as a tail
3941   /// call. This is used by optimization passes to determine if it's profitable
3942   /// to duplicate return instructions to enable tailcall optimization.
3943   virtual bool mayBeEmittedAsTailCall(const CallInst *) const {
3944     return false;
3945   }
3946 
3947   /// Return the builtin name for the __builtin___clear_cache intrinsic
3948   /// Default is to invoke the clear cache library call
3949   virtual const char * getClearCacheBuiltinName() const {
3950     return "__clear_cache";
3951   }
3952 
3953   /// Return the register ID of the name passed in. Used by named register
3954   /// global variables extension. There is no target-independent behaviour
3955   /// so the default action is to bail.
3956   virtual Register getRegisterByName(const char* RegName, LLT Ty,
3957                                      const MachineFunction &MF) const {
3958     report_fatal_error("Named registers not implemented for this target");
3959   }
3960 
3961   /// Return the type that should be used to zero or sign extend a
3962   /// zeroext/signext integer return value.  FIXME: Some C calling conventions
3963   /// require the return type to be promoted, but this is not true all the time,
3964   /// e.g. i1/i8/i16 on x86/x86_64. It is also not necessary for non-C calling
3965   /// conventions. The frontend should handle this and include all of the
3966   /// necessary information.
3967   virtual EVT getTypeForExtReturn(LLVMContext &Context, EVT VT,
3968                                        ISD::NodeType /*ExtendKind*/) const {
3969     EVT MinVT = getRegisterType(Context, MVT::i32);
3970     return VT.bitsLT(MinVT) ? MinVT : VT;
3971   }
3972 
3973   /// For some targets, an LLVM struct type must be broken down into multiple
3974   /// simple types, but the calling convention specifies that the entire struct
3975   /// must be passed in a block of consecutive registers.
3976   virtual bool
3977   functionArgumentNeedsConsecutiveRegisters(Type *Ty, CallingConv::ID CallConv,
3978                                             bool isVarArg) const {
3979     return false;
3980   }
3981 
3982   /// For most targets, an LLVM type must be broken down into multiple
3983   /// smaller types. Usually the halves are ordered according to the endianness
3984   /// but for some platform that would break. So this method will default to
3985   /// matching the endianness but can be overridden.
3986   virtual bool
3987   shouldSplitFunctionArgumentsAsLittleEndian(const DataLayout &DL) const {
3988     return DL.isLittleEndian();
3989   }
3990 
3991   /// Returns a 0 terminated array of registers that can be safely used as
3992   /// scratch registers.
3993   virtual const MCPhysReg *getScratchRegisters(CallingConv::ID CC) const {
3994     return nullptr;
3995   }
3996 
3997   /// This callback is used to prepare for a volatile or atomic load.
3998   /// It takes a chain node as input and returns the chain for the load itself.
3999   ///
4000   /// Having a callback like this is necessary for targets like SystemZ,
4001   /// which allows a CPU to reuse the result of a previous load indefinitely,
4002   /// even if a cache-coherent store is performed by another CPU.  The default
4003   /// implementation does nothing.
4004   virtual SDValue prepareVolatileOrAtomicLoad(SDValue Chain, const SDLoc &DL,
4005                                               SelectionDAG &DAG) const {
4006     return Chain;
4007   }
4008 
4009   /// Should SelectionDAG lower an atomic store of the given kind as a normal
4010   /// StoreSDNode (as opposed to an AtomicSDNode)?  NOTE: The intention is to
4011   /// eventually migrate all targets to the using StoreSDNodes, but porting is
4012   /// being done target at a time.
4013   virtual bool lowerAtomicStoreAsStoreSDNode(const StoreInst &SI) const {
4014     assert(SI.isAtomic() && "violated precondition");
4015     return false;
4016   }
4017 
4018   /// Should SelectionDAG lower an atomic load of the given kind as a normal
4019   /// LoadSDNode (as opposed to an AtomicSDNode)?  NOTE: The intention is to
4020   /// eventually migrate all targets to the using LoadSDNodes, but porting is
4021   /// being done target at a time.
4022   virtual bool lowerAtomicLoadAsLoadSDNode(const LoadInst &LI) const {
4023     assert(LI.isAtomic() && "violated precondition");
4024     return false;
4025   }
4026 
4027 
4028   /// This callback is invoked by the type legalizer to legalize nodes with an
4029   /// illegal operand type but legal result types.  It replaces the
4030   /// LowerOperation callback in the type Legalizer.  The reason we can not do
4031   /// away with LowerOperation entirely is that LegalizeDAG isn't yet ready to
4032   /// use this callback.
4033   ///
4034   /// TODO: Consider merging with ReplaceNodeResults.
4035   ///
4036   /// The target places new result values for the node in Results (their number
4037   /// and types must exactly match those of the original return values of
4038   /// the node), or leaves Results empty, which indicates that the node is not
4039   /// to be custom lowered after all.
4040   /// The default implementation calls LowerOperation.
4041   virtual void LowerOperationWrapper(SDNode *N,
4042                                      SmallVectorImpl<SDValue> &Results,
4043                                      SelectionDAG &DAG) const;
4044 
4045   /// This callback is invoked for operations that are unsupported by the
4046   /// target, which are registered to use 'custom' lowering, and whose defined
4047   /// values are all legal.  If the target has no operations that require custom
4048   /// lowering, it need not implement this.  The default implementation of this
4049   /// aborts.
4050   virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
4051 
4052   /// This callback is invoked when a node result type is illegal for the
4053   /// target, and the operation was registered to use 'custom' lowering for that
4054   /// result type.  The target places new result values for the node in Results
4055   /// (their number and types must exactly match those of the original return
4056   /// values of the node), or leaves Results empty, which indicates that the
4057   /// node is not to be custom lowered after all.
4058   ///
4059   /// If the target has no operations that require custom lowering, it need not
4060   /// implement this.  The default implementation aborts.
4061   virtual void ReplaceNodeResults(SDNode * /*N*/,
4062                                   SmallVectorImpl<SDValue> &/*Results*/,
4063                                   SelectionDAG &/*DAG*/) const {
4064     llvm_unreachable("ReplaceNodeResults not implemented for this target!");
4065   }
4066 
4067   /// This method returns the name of a target specific DAG node.
4068   virtual const char *getTargetNodeName(unsigned Opcode) const;
4069 
4070   /// This method returns a target specific FastISel object, or null if the
4071   /// target does not support "fast" ISel.
4072   virtual FastISel *createFastISel(FunctionLoweringInfo &,
4073                                    const TargetLibraryInfo *) const {
4074     return nullptr;
4075   }
4076 
4077   bool verifyReturnAddressArgumentIsConstant(SDValue Op,
4078                                              SelectionDAG &DAG) const;
4079 
4080   //===--------------------------------------------------------------------===//
4081   // Inline Asm Support hooks
4082   //
4083 
4084   /// This hook allows the target to expand an inline asm call to be explicit
4085   /// llvm code if it wants to.  This is useful for turning simple inline asms
4086   /// into LLVM intrinsics, which gives the compiler more information about the
4087   /// behavior of the code.
4088   virtual bool ExpandInlineAsm(CallInst *) const {
4089     return false;
4090   }
4091 
4092   enum ConstraintType {
4093     C_Register,            // Constraint represents specific register(s).
4094     C_RegisterClass,       // Constraint represents any of register(s) in class.
4095     C_Memory,              // Memory constraint.
4096     C_Immediate,           // Requires an immediate.
4097     C_Other,               // Something else.
4098     C_Unknown              // Unsupported constraint.
4099   };
4100 
4101   enum ConstraintWeight {
4102     // Generic weights.
4103     CW_Invalid  = -1,     // No match.
4104     CW_Okay     = 0,      // Acceptable.
4105     CW_Good     = 1,      // Good weight.
4106     CW_Better   = 2,      // Better weight.
4107     CW_Best     = 3,      // Best weight.
4108 
4109     // Well-known weights.
4110     CW_SpecificReg  = CW_Okay,    // Specific register operands.
4111     CW_Register     = CW_Good,    // Register operands.
4112     CW_Memory       = CW_Better,  // Memory operands.
4113     CW_Constant     = CW_Best,    // Constant operand.
4114     CW_Default      = CW_Okay     // Default or don't know type.
4115   };
4116 
4117   /// This contains information for each constraint that we are lowering.
4118   struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
4119     /// This contains the actual string for the code, like "m".  TargetLowering
4120     /// picks the 'best' code from ConstraintInfo::Codes that most closely
4121     /// matches the operand.
4122     std::string ConstraintCode;
4123 
4124     /// Information about the constraint code, e.g. Register, RegisterClass,
4125     /// Memory, Other, Unknown.
4126     TargetLowering::ConstraintType ConstraintType = TargetLowering::C_Unknown;
4127 
4128     /// If this is the result output operand or a clobber, this is null,
4129     /// otherwise it is the incoming operand to the CallInst.  This gets
4130     /// modified as the asm is processed.
4131     Value *CallOperandVal = nullptr;
4132 
4133     /// The ValueType for the operand value.
4134     MVT ConstraintVT = MVT::Other;
4135 
4136     /// Copy constructor for copying from a ConstraintInfo.
4137     AsmOperandInfo(InlineAsm::ConstraintInfo Info)
4138         : InlineAsm::ConstraintInfo(std::move(Info)) {}
4139 
4140     /// Return true of this is an input operand that is a matching constraint
4141     /// like "4".
4142     bool isMatchingInputConstraint() const;
4143 
4144     /// If this is an input matching constraint, this method returns the output
4145     /// operand it matches.
4146     unsigned getMatchedOperand() const;
4147   };
4148 
4149   using AsmOperandInfoVector = std::vector<AsmOperandInfo>;
4150 
4151   /// Split up the constraint string from the inline assembly value into the
4152   /// specific constraints and their prefixes, and also tie in the associated
4153   /// operand values.  If this returns an empty vector, and if the constraint
4154   /// string itself isn't empty, there was an error parsing.
4155   virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL,
4156                                                 const TargetRegisterInfo *TRI,
4157                                                 const CallBase &Call) const;
4158 
4159   /// Examine constraint type and operand type and determine a weight value.
4160   /// The operand object must already have been set up with the operand type.
4161   virtual ConstraintWeight getMultipleConstraintMatchWeight(
4162       AsmOperandInfo &info, int maIndex) const;
4163 
4164   /// Examine constraint string and operand type and determine a weight value.
4165   /// The operand object must already have been set up with the operand type.
4166   virtual ConstraintWeight getSingleConstraintMatchWeight(
4167       AsmOperandInfo &info, const char *constraint) const;
4168 
4169   /// Determines the constraint code and constraint type to use for the specific
4170   /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
4171   /// If the actual operand being passed in is available, it can be passed in as
4172   /// Op, otherwise an empty SDValue can be passed.
4173   virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
4174                                       SDValue Op,
4175                                       SelectionDAG *DAG = nullptr) const;
4176 
4177   /// Given a constraint, return the type of constraint it is for this target.
4178   virtual ConstraintType getConstraintType(StringRef Constraint) const;
4179 
4180   /// Given a physical register constraint (e.g.  {edx}), return the register
4181   /// number and the register class for the register.
4182   ///
4183   /// Given a register class constraint, like 'r', if this corresponds directly
4184   /// to an LLVM register class, return a register of 0 and the register class
4185   /// pointer.
4186   ///
4187   /// This should only be used for C_Register constraints.  On error, this
4188   /// returns a register number of 0 and a null register class pointer.
4189   virtual std::pair<unsigned, const TargetRegisterClass *>
4190   getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
4191                                StringRef Constraint, MVT VT) const;
4192 
4193   virtual unsigned getInlineAsmMemConstraint(StringRef ConstraintCode) const {
4194     if (ConstraintCode == "m")
4195       return InlineAsm::Constraint_m;
4196     return InlineAsm::Constraint_Unknown;
4197   }
4198 
4199   /// Try to replace an X constraint, which matches anything, with another that
4200   /// has more specific requirements based on the type of the corresponding
4201   /// operand.  This returns null if there is no replacement to make.
4202   virtual const char *LowerXConstraint(EVT ConstraintVT) const;
4203 
4204   /// Lower the specified operand into the Ops vector.  If it is invalid, don't
4205   /// add anything to Ops.
4206   virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
4207                                             std::vector<SDValue> &Ops,
4208                                             SelectionDAG &DAG) const;
4209 
4210   // Lower custom output constraints. If invalid, return SDValue().
4211   virtual SDValue LowerAsmOutputForConstraint(SDValue &Chain, SDValue &Flag,
4212                                               const SDLoc &DL,
4213                                               const AsmOperandInfo &OpInfo,
4214                                               SelectionDAG &DAG) const;
4215 
4216   //===--------------------------------------------------------------------===//
4217   // Div utility functions
4218   //
4219   SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
4220                     SmallVectorImpl<SDNode *> &Created) const;
4221   SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
4222                     SmallVectorImpl<SDNode *> &Created) const;
4223 
4224   /// Targets may override this function to provide custom SDIV lowering for
4225   /// power-of-2 denominators.  If the target returns an empty SDValue, LLVM
4226   /// assumes SDIV is expensive and replaces it with a series of other integer
4227   /// operations.
4228   virtual SDValue BuildSDIVPow2(SDNode *N, const APInt &Divisor,
4229                                 SelectionDAG &DAG,
4230                                 SmallVectorImpl<SDNode *> &Created) const;
4231 
4232   /// Indicate whether this target prefers to combine FDIVs with the same
4233   /// divisor. If the transform should never be done, return zero. If the
4234   /// transform should be done, return the minimum number of divisor uses
4235   /// that must exist.
4236   virtual unsigned combineRepeatedFPDivisors() const {
4237     return 0;
4238   }
4239 
4240   /// Hooks for building estimates in place of slower divisions and square
4241   /// roots.
4242 
4243   /// Return either a square root or its reciprocal estimate value for the input
4244   /// operand.
4245   /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
4246   /// 'Enabled' as set by a potential default override attribute.
4247   /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
4248   /// refinement iterations required to generate a sufficient (though not
4249   /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
4250   /// The boolean UseOneConstNR output is used to select a Newton-Raphson
4251   /// algorithm implementation that uses either one or two constants.
4252   /// The boolean Reciprocal is used to select whether the estimate is for the
4253   /// square root of the input operand or the reciprocal of its square root.
4254   /// A target may choose to implement its own refinement within this function.
4255   /// If that's true, then return '0' as the number of RefinementSteps to avoid
4256   /// any further refinement of the estimate.
4257   /// An empty SDValue return means no estimate sequence can be created.
4258   virtual SDValue getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
4259                                   int Enabled, int &RefinementSteps,
4260                                   bool &UseOneConstNR, bool Reciprocal) const {
4261     return SDValue();
4262   }
4263 
4264   /// Return a reciprocal estimate value for the input operand.
4265   /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
4266   /// 'Enabled' as set by a potential default override attribute.
4267   /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
4268   /// refinement iterations required to generate a sufficient (though not
4269   /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
4270   /// A target may choose to implement its own refinement within this function.
4271   /// If that's true, then return '0' as the number of RefinementSteps to avoid
4272   /// any further refinement of the estimate.
4273   /// An empty SDValue return means no estimate sequence can be created.
4274   virtual SDValue getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
4275                                    int Enabled, int &RefinementSteps) const {
4276     return SDValue();
4277   }
4278 
4279   /// Return a target-dependent comparison result if the input operand is
4280   /// suitable for use with a square root estimate calculation. For example, the
4281   /// comparison may check if the operand is NAN, INF, zero, normal, etc. The
4282   /// result should be used as the condition operand for a select or branch.
4283   virtual SDValue getSqrtInputTest(SDValue Operand, SelectionDAG &DAG,
4284                                    const DenormalMode &Mode) const;
4285 
4286   /// Return a target-dependent result if the input operand is not suitable for
4287   /// use with a square root estimate calculation.
4288   virtual SDValue getSqrtResultForDenormInput(SDValue Operand,
4289                                               SelectionDAG &DAG) const {
4290     return DAG.getConstantFP(0.0, SDLoc(Operand), Operand.getValueType());
4291   }
4292 
4293   //===--------------------------------------------------------------------===//
4294   // Legalization utility functions
4295   //
4296 
4297   /// Expand a MUL or [US]MUL_LOHI of n-bit values into two or four nodes,
4298   /// respectively, each computing an n/2-bit part of the result.
4299   /// \param Result A vector that will be filled with the parts of the result
4300   ///        in little-endian order.
4301   /// \param LL Low bits of the LHS of the MUL.  You can use this parameter
4302   ///        if you want to control how low bits are extracted from the LHS.
4303   /// \param LH High bits of the LHS of the MUL.  See LL for meaning.
4304   /// \param RL Low bits of the RHS of the MUL.  See LL for meaning
4305   /// \param RH High bits of the RHS of the MUL.  See LL for meaning.
4306   /// \returns true if the node has been expanded, false if it has not
4307   bool expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl, SDValue LHS,
4308                       SDValue RHS, SmallVectorImpl<SDValue> &Result, EVT HiLoVT,
4309                       SelectionDAG &DAG, MulExpansionKind Kind,
4310                       SDValue LL = SDValue(), SDValue LH = SDValue(),
4311                       SDValue RL = SDValue(), SDValue RH = SDValue()) const;
4312 
4313   /// Expand a MUL into two nodes.  One that computes the high bits of
4314   /// the result and one that computes the low bits.
4315   /// \param HiLoVT The value type to use for the Lo and Hi nodes.
4316   /// \param LL Low bits of the LHS of the MUL.  You can use this parameter
4317   ///        if you want to control how low bits are extracted from the LHS.
4318   /// \param LH High bits of the LHS of the MUL.  See LL for meaning.
4319   /// \param RL Low bits of the RHS of the MUL.  See LL for meaning
4320   /// \param RH High bits of the RHS of the MUL.  See LL for meaning.
4321   /// \returns true if the node has been expanded. false if it has not
4322   bool expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
4323                  SelectionDAG &DAG, MulExpansionKind Kind,
4324                  SDValue LL = SDValue(), SDValue LH = SDValue(),
4325                  SDValue RL = SDValue(), SDValue RH = SDValue()) const;
4326 
4327   /// Expand funnel shift.
4328   /// \param N Node to expand
4329   /// \param Result output after conversion
4330   /// \returns True, if the expansion was successful, false otherwise
4331   bool expandFunnelShift(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
4332 
4333   /// Expand rotations.
4334   /// \param N Node to expand
4335   /// \param AllowVectorOps expand vector rotate, this should only be performed
4336   ///        if the legalization is happening outside of LegalizeVectorOps
4337   /// \param Result output after conversion
4338   /// \returns True, if the expansion was successful, false otherwise
4339   bool expandROT(SDNode *N, bool AllowVectorOps, SDValue &Result,
4340                  SelectionDAG &DAG) const;
4341 
4342   /// Expand float(f32) to SINT(i64) conversion
4343   /// \param N Node to expand
4344   /// \param Result output after conversion
4345   /// \returns True, if the expansion was successful, false otherwise
4346   bool expandFP_TO_SINT(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
4347 
4348   /// Expand float to UINT conversion
4349   /// \param N Node to expand
4350   /// \param Result output after conversion
4351   /// \param Chain output chain after conversion
4352   /// \returns True, if the expansion was successful, false otherwise
4353   bool expandFP_TO_UINT(SDNode *N, SDValue &Result, SDValue &Chain,
4354                         SelectionDAG &DAG) const;
4355 
4356   /// Expand UINT(i64) to double(f64) conversion
4357   /// \param N Node to expand
4358   /// \param Result output after conversion
4359   /// \param Chain output chain after conversion
4360   /// \returns True, if the expansion was successful, false otherwise
4361   bool expandUINT_TO_FP(SDNode *N, SDValue &Result, SDValue &Chain,
4362                         SelectionDAG &DAG) const;
4363 
4364   /// Expand fminnum/fmaxnum into fminnum_ieee/fmaxnum_ieee with quieted inputs.
4365   SDValue expandFMINNUM_FMAXNUM(SDNode *N, SelectionDAG &DAG) const;
4366 
4367   /// Expand FP_TO_[US]INT_SAT into FP_TO_[US]INT and selects or min/max.
4368   /// \param N Node to expand
4369   /// \returns The expansion result
4370   SDValue expandFP_TO_INT_SAT(SDNode *N, SelectionDAG &DAG) const;
4371 
4372   /// Expand CTPOP nodes. Expands vector/scalar CTPOP nodes,
4373   /// vector nodes can only succeed if all operations are legal/custom.
4374   /// \param N Node to expand
4375   /// \param Result output after conversion
4376   /// \returns True, if the expansion was successful, false otherwise
4377   bool expandCTPOP(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
4378 
4379   /// Expand CTLZ/CTLZ_ZERO_UNDEF nodes. Expands vector/scalar CTLZ nodes,
4380   /// vector nodes can only succeed if all operations are legal/custom.
4381   /// \param N Node to expand
4382   /// \param Result output after conversion
4383   /// \returns True, if the expansion was successful, false otherwise
4384   bool expandCTLZ(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
4385 
4386   /// Expand CTTZ/CTTZ_ZERO_UNDEF nodes. Expands vector/scalar CTTZ nodes,
4387   /// vector nodes can only succeed if all operations are legal/custom.
4388   /// \param N Node to expand
4389   /// \param Result output after conversion
4390   /// \returns True, if the expansion was successful, false otherwise
4391   bool expandCTTZ(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
4392 
4393   /// Expand ABS nodes. Expands vector/scalar ABS nodes,
4394   /// vector nodes can only succeed if all operations are legal/custom.
4395   /// (ABS x) -> (XOR (ADD x, (SRA x, type_size)), (SRA x, type_size))
4396   /// \param N Node to expand
4397   /// \param Result output after conversion
4398   /// \param IsNegative indicate negated abs
4399   /// \returns True, if the expansion was successful, false otherwise
4400   bool expandABS(SDNode *N, SDValue &Result, SelectionDAG &DAG,
4401                  bool IsNegative = false) const;
4402 
4403   /// Turn load of vector type into a load of the individual elements.
4404   /// \param LD load to expand
4405   /// \returns BUILD_VECTOR and TokenFactor nodes.
4406   std::pair<SDValue, SDValue> scalarizeVectorLoad(LoadSDNode *LD,
4407                                                   SelectionDAG &DAG) const;
4408 
4409   // Turn a store of a vector type into stores of the individual elements.
4410   /// \param ST Store with a vector value type
4411   /// \returns TokenFactor of the individual store chains.
4412   SDValue scalarizeVectorStore(StoreSDNode *ST, SelectionDAG &DAG) const;
4413 
4414   /// Expands an unaligned load to 2 half-size loads for an integer, and
4415   /// possibly more for vectors.
4416   std::pair<SDValue, SDValue> expandUnalignedLoad(LoadSDNode *LD,
4417                                                   SelectionDAG &DAG) const;
4418 
4419   /// Expands an unaligned store to 2 half-size stores for integer values, and
4420   /// possibly more for vectors.
4421   SDValue expandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG) const;
4422 
4423   /// Increments memory address \p Addr according to the type of the value
4424   /// \p DataVT that should be stored. If the data is stored in compressed
4425   /// form, the memory address should be incremented according to the number of
4426   /// the stored elements. This number is equal to the number of '1's bits
4427   /// in the \p Mask.
4428   /// \p DataVT is a vector type. \p Mask is a vector value.
4429   /// \p DataVT and \p Mask have the same number of vector elements.
4430   SDValue IncrementMemoryAddress(SDValue Addr, SDValue Mask, const SDLoc &DL,
4431                                  EVT DataVT, SelectionDAG &DAG,
4432                                  bool IsCompressedMemory) const;
4433 
4434   /// Get a pointer to vector element \p Idx located in memory for a vector of
4435   /// type \p VecVT starting at a base address of \p VecPtr. If \p Idx is out of
4436   /// bounds the returned pointer is unspecified, but will be within the vector
4437   /// bounds.
4438   SDValue getVectorElementPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT,
4439                                   SDValue Index) const;
4440 
4441   /// Method for building the DAG expansion of ISD::[US][MIN|MAX]. This
4442   /// method accepts integers as its arguments.
4443   SDValue expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const;
4444 
4445   /// Method for building the DAG expansion of ISD::[US][ADD|SUB]SAT. This
4446   /// method accepts integers as its arguments.
4447   SDValue expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const;
4448 
4449   /// Method for building the DAG expansion of ISD::[US]SHLSAT. This
4450   /// method accepts integers as its arguments.
4451   SDValue expandShlSat(SDNode *Node, SelectionDAG &DAG) const;
4452 
4453   /// Method for building the DAG expansion of ISD::[U|S]MULFIX[SAT]. This
4454   /// method accepts integers as its arguments.
4455   SDValue expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const;
4456 
4457   /// Method for building the DAG expansion of ISD::[US]DIVFIX[SAT]. This
4458   /// method accepts integers as its arguments.
4459   /// Note: This method may fail if the division could not be performed
4460   /// within the type. Clients must retry with a wider type if this happens.
4461   SDValue expandFixedPointDiv(unsigned Opcode, const SDLoc &dl,
4462                               SDValue LHS, SDValue RHS,
4463                               unsigned Scale, SelectionDAG &DAG) const;
4464 
4465   /// Method for building the DAG expansion of ISD::U(ADD|SUB)O. Expansion
4466   /// always suceeds and populates the Result and Overflow arguments.
4467   void expandUADDSUBO(SDNode *Node, SDValue &Result, SDValue &Overflow,
4468                       SelectionDAG &DAG) const;
4469 
4470   /// Method for building the DAG expansion of ISD::S(ADD|SUB)O. Expansion
4471   /// always suceeds and populates the Result and Overflow arguments.
4472   void expandSADDSUBO(SDNode *Node, SDValue &Result, SDValue &Overflow,
4473                       SelectionDAG &DAG) const;
4474 
4475   /// Method for building the DAG expansion of ISD::[US]MULO. Returns whether
4476   /// expansion was successful and populates the Result and Overflow arguments.
4477   bool expandMULO(SDNode *Node, SDValue &Result, SDValue &Overflow,
4478                   SelectionDAG &DAG) const;
4479 
4480   /// Expand a VECREDUCE_* into an explicit calculation. If Count is specified,
4481   /// only the first Count elements of the vector are used.
4482   SDValue expandVecReduce(SDNode *Node, SelectionDAG &DAG) const;
4483 
4484   /// Expand a VECREDUCE_SEQ_* into an explicit ordered calculation.
4485   SDValue expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const;
4486 
4487   /// Expand an SREM or UREM using SDIV/UDIV or SDIVREM/UDIVREM, if legal.
4488   /// Returns true if the expansion was successful.
4489   bool expandREM(SDNode *Node, SDValue &Result, SelectionDAG &DAG) const;
4490 
4491   //===--------------------------------------------------------------------===//
4492   // Instruction Emitting Hooks
4493   //
4494 
4495   /// This method should be implemented by targets that mark instructions with
4496   /// the 'usesCustomInserter' flag.  These instructions are special in various
4497   /// ways, which require special support to insert.  The specified MachineInstr
4498   /// is created but not inserted into any basic blocks, and this method is
4499   /// called to expand it into a sequence of instructions, potentially also
4500   /// creating new basic blocks and control flow.
4501   /// As long as the returned basic block is different (i.e., we created a new
4502   /// one), the custom inserter is free to modify the rest of \p MBB.
4503   virtual MachineBasicBlock *
4504   EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const;
4505 
4506   /// This method should be implemented by targets that mark instructions with
4507   /// the 'hasPostISelHook' flag. These instructions must be adjusted after
4508   /// instruction selection by target hooks.  e.g. To fill in optional defs for
4509   /// ARM 's' setting instructions.
4510   virtual void AdjustInstrPostInstrSelection(MachineInstr &MI,
4511                                              SDNode *Node) const;
4512 
4513   /// If this function returns true, SelectionDAGBuilder emits a
4514   /// LOAD_STACK_GUARD node when it is lowering Intrinsic::stackprotector.
4515   virtual bool useLoadStackGuardNode() const {
4516     return false;
4517   }
4518 
4519   virtual SDValue emitStackGuardXorFP(SelectionDAG &DAG, SDValue Val,
4520                                       const SDLoc &DL) const {
4521     llvm_unreachable("not implemented for this target");
4522   }
4523 
4524   /// Lower TLS global address SDNode for target independent emulated TLS model.
4525   virtual SDValue LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
4526                                           SelectionDAG &DAG) const;
4527 
4528   /// Expands target specific indirect branch for the case of JumpTable
4529   /// expanasion.
4530   virtual SDValue expandIndirectJTBranch(const SDLoc& dl, SDValue Value, SDValue Addr,
4531                                          SelectionDAG &DAG) const {
4532     return DAG.getNode(ISD::BRIND, dl, MVT::Other, Value, Addr);
4533   }
4534 
4535   // seteq(x, 0) -> truncate(srl(ctlz(zext(x)), log2(#bits)))
4536   // If we're comparing for equality to zero and isCtlzFast is true, expose the
4537   // fact that this can be implemented as a ctlz/srl pair, so that the dag
4538   // combiner can fold the new nodes.
4539   SDValue lowerCmpEqZeroToCtlzSrl(SDValue Op, SelectionDAG &DAG) const;
4540 
4541   /// Give targets the chance to reduce the number of distinct addresing modes.
4542   ISD::MemIndexType getCanonicalIndexType(ISD::MemIndexType IndexType,
4543                                           EVT MemVT, SDValue Offsets) const;
4544 
4545 private:
4546   SDValue foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
4547                            const SDLoc &DL, DAGCombinerInfo &DCI) const;
4548   SDValue foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
4549                              const SDLoc &DL, DAGCombinerInfo &DCI) const;
4550 
4551   SDValue optimizeSetCCOfSignedTruncationCheck(EVT SCCVT, SDValue N0,
4552                                                SDValue N1, ISD::CondCode Cond,
4553                                                DAGCombinerInfo &DCI,
4554                                                const SDLoc &DL) const;
4555 
4556   // (X & (C l>>/<< Y)) ==/!= 0  -->  ((X <</l>> Y) & C) ==/!= 0
4557   SDValue optimizeSetCCByHoistingAndByConstFromLogicalShift(
4558       EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
4559       DAGCombinerInfo &DCI, const SDLoc &DL) const;
4560 
4561   SDValue prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
4562                             SDValue CompTargetNode, ISD::CondCode Cond,
4563                             DAGCombinerInfo &DCI, const SDLoc &DL,
4564                             SmallVectorImpl<SDNode *> &Created) const;
4565   SDValue buildUREMEqFold(EVT SETCCVT, SDValue REMNode, SDValue CompTargetNode,
4566                           ISD::CondCode Cond, DAGCombinerInfo &DCI,
4567                           const SDLoc &DL) const;
4568 
4569   SDValue prepareSREMEqFold(EVT SETCCVT, SDValue REMNode,
4570                             SDValue CompTargetNode, ISD::CondCode Cond,
4571                             DAGCombinerInfo &DCI, const SDLoc &DL,
4572                             SmallVectorImpl<SDNode *> &Created) const;
4573   SDValue buildSREMEqFold(EVT SETCCVT, SDValue REMNode, SDValue CompTargetNode,
4574                           ISD::CondCode Cond, DAGCombinerInfo &DCI,
4575                           const SDLoc &DL) const;
4576 };
4577 
4578 /// Given an LLVM IR type and return type attributes, compute the return value
4579 /// EVTs and flags, and optionally also the offsets, if the return value is
4580 /// being lowered to memory.
4581 void GetReturnInfo(CallingConv::ID CC, Type *ReturnType, AttributeList attr,
4582                    SmallVectorImpl<ISD::OutputArg> &Outs,
4583                    const TargetLowering &TLI, const DataLayout &DL);
4584 
4585 } // end namespace llvm
4586 
4587 #endif // LLVM_CODEGEN_TARGETLOWERING_H
4588