1 //===- llvm/CodeGen/SelectionDAGNodes.h - SelectionDAG Nodes ----*- 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 // This file declares the SDNode class and derived classes, which are used to
10 // represent the nodes and operations present in a SelectionDAG.  These nodes
11 // and operations are machine code level operations, with some similarities to
12 // the GCC RTL representation.
13 //
14 // Clients should include the SelectionDAG.h file instead of this file directly.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #ifndef LLVM_CODEGEN_SELECTIONDAGNODES_H
19 #define LLVM_CODEGEN_SELECTIONDAGNODES_H
20 
21 #include "llvm/ADT/APFloat.h"
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/BitVector.h"
24 #include "llvm/ADT/FoldingSet.h"
25 #include "llvm/ADT/GraphTraits.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/ilist_node.h"
29 #include "llvm/ADT/iterator.h"
30 #include "llvm/ADT/iterator_range.h"
31 #include "llvm/CodeGen/ISDOpcodes.h"
32 #include "llvm/CodeGen/MachineMemOperand.h"
33 #include "llvm/CodeGen/MachineValueType.h"
34 #include "llvm/CodeGen/Register.h"
35 #include "llvm/CodeGen/ValueTypes.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DebugLoc.h"
38 #include "llvm/IR/Instruction.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Metadata.h"
41 #include "llvm/IR/Operator.h"
42 #include "llvm/Support/AlignOf.h"
43 #include "llvm/Support/AtomicOrdering.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/TypeSize.h"
47 #include <algorithm>
48 #include <cassert>
49 #include <climits>
50 #include <cstddef>
51 #include <cstdint>
52 #include <cstring>
53 #include <iterator>
54 #include <string>
55 #include <tuple>
56 #include <utility>
57 
58 namespace llvm {
59 
60 class APInt;
61 class Constant;
62 class GlobalValue;
63 class MachineBasicBlock;
64 class MachineConstantPoolValue;
65 class MCSymbol;
66 class raw_ostream;
67 class SDNode;
68 class SelectionDAG;
69 class Type;
70 class Value;
71 
72 void checkForCycles(const SDNode *N, const SelectionDAG *DAG = nullptr,
73                     bool force = false);
74 
75 /// This represents a list of ValueType's that has been intern'd by
76 /// a SelectionDAG.  Instances of this simple value class are returned by
77 /// SelectionDAG::getVTList(...).
78 ///
79 struct SDVTList {
80   const EVT *VTs;
81   unsigned int NumVTs;
82 };
83 
84 namespace ISD {
85 
86   /// Node predicates
87 
88 /// If N is a BUILD_VECTOR or SPLAT_VECTOR node whose elements are all the
89 /// same constant or undefined, return true and return the constant value in
90 /// \p SplatValue.
91 bool isConstantSplatVector(const SDNode *N, APInt &SplatValue);
92 
93 /// Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where
94 /// all of the elements are ~0 or undef. If \p BuildVectorOnly is set to
95 /// true, it only checks BUILD_VECTOR.
96 bool isConstantSplatVectorAllOnes(const SDNode *N,
97                                   bool BuildVectorOnly = false);
98 
99 /// Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where
100 /// all of the elements are 0 or undef. If \p BuildVectorOnly is set to true, it
101 /// only checks BUILD_VECTOR.
102 bool isConstantSplatVectorAllZeros(const SDNode *N,
103                                    bool BuildVectorOnly = false);
104 
105 /// Return true if the specified node is a BUILD_VECTOR where all of the
106 /// elements are ~0 or undef.
107 bool isBuildVectorAllOnes(const SDNode *N);
108 
109 /// Return true if the specified node is a BUILD_VECTOR where all of the
110 /// elements are 0 or undef.
111 bool isBuildVectorAllZeros(const SDNode *N);
112 
113 /// Return true if the specified node is a BUILD_VECTOR node of all
114 /// ConstantSDNode or undef.
115 bool isBuildVectorOfConstantSDNodes(const SDNode *N);
116 
117 /// Return true if the specified node is a BUILD_VECTOR node of all
118 /// ConstantFPSDNode or undef.
119 bool isBuildVectorOfConstantFPSDNodes(const SDNode *N);
120 
121 /// Returns true if the specified node is a vector where all elements can
122 /// be truncated to the specified element size without a loss in meaning.
123 bool isVectorShrinkable(const SDNode *N, unsigned NewEltSize, bool Signed);
124 
125 /// Return true if the node has at least one operand and all operands of the
126 /// specified node are ISD::UNDEF.
127 bool allOperandsUndef(const SDNode *N);
128 
129 /// Return true if the specified node is FREEZE(UNDEF).
130 bool isFreezeUndef(const SDNode *N);
131 
132 } // end namespace ISD
133 
134 //===----------------------------------------------------------------------===//
135 /// Unlike LLVM values, Selection DAG nodes may return multiple
136 /// values as the result of a computation.  Many nodes return multiple values,
137 /// from loads (which define a token and a return value) to ADDC (which returns
138 /// a result and a carry value), to calls (which may return an arbitrary number
139 /// of values).
140 ///
141 /// As such, each use of a SelectionDAG computation must indicate the node that
142 /// computes it as well as which return value to use from that node.  This pair
143 /// of information is represented with the SDValue value type.
144 ///
145 class SDValue {
146   friend struct DenseMapInfo<SDValue>;
147 
148   SDNode *Node = nullptr; // The node defining the value we are using.
149   unsigned ResNo = 0;     // Which return value of the node we are using.
150 
151 public:
152   SDValue() = default;
153   SDValue(SDNode *node, unsigned resno);
154 
155   /// get the index which selects a specific result in the SDNode
156   unsigned getResNo() const { return ResNo; }
157 
158   /// get the SDNode which holds the desired result
159   SDNode *getNode() const { return Node; }
160 
161   /// set the SDNode
162   void setNode(SDNode *N) { Node = N; }
163 
164   inline SDNode *operator->() const { return Node; }
165 
166   bool operator==(const SDValue &O) const {
167     return Node == O.Node && ResNo == O.ResNo;
168   }
169   bool operator!=(const SDValue &O) const {
170     return !operator==(O);
171   }
172   bool operator<(const SDValue &O) const {
173     return std::tie(Node, ResNo) < std::tie(O.Node, O.ResNo);
174   }
175   explicit operator bool() const {
176     return Node != nullptr;
177   }
178 
179   SDValue getValue(unsigned R) const {
180     return SDValue(Node, R);
181   }
182 
183   /// Return true if this node is an operand of N.
184   bool isOperandOf(const SDNode *N) const;
185 
186   /// Return the ValueType of the referenced return value.
187   inline EVT getValueType() const;
188 
189   /// Return the simple ValueType of the referenced return value.
190   MVT getSimpleValueType() const {
191     return getValueType().getSimpleVT();
192   }
193 
194   /// Returns the size of the value in bits.
195   ///
196   /// If the value type is a scalable vector type, the scalable property will
197   /// be set and the runtime size will be a positive integer multiple of the
198   /// base size.
199   TypeSize getValueSizeInBits() const {
200     return getValueType().getSizeInBits();
201   }
202 
203   uint64_t getScalarValueSizeInBits() const {
204     return getValueType().getScalarType().getFixedSizeInBits();
205   }
206 
207   // Forwarding methods - These forward to the corresponding methods in SDNode.
208   inline unsigned getOpcode() const;
209   inline unsigned getNumOperands() const;
210   inline const SDValue &getOperand(unsigned i) const;
211   inline uint64_t getConstantOperandVal(unsigned i) const;
212   inline const APInt &getConstantOperandAPInt(unsigned i) const;
213   inline bool isTargetMemoryOpcode() const;
214   inline bool isTargetOpcode() const;
215   inline bool isMachineOpcode() const;
216   inline bool isUndef() const;
217   inline unsigned getMachineOpcode() const;
218   inline const DebugLoc &getDebugLoc() const;
219   inline void dump() const;
220   inline void dump(const SelectionDAG *G) const;
221   inline void dumpr() const;
222   inline void dumpr(const SelectionDAG *G) const;
223 
224   /// Return true if this operand (which must be a chain) reaches the
225   /// specified operand without crossing any side-effecting instructions.
226   /// In practice, this looks through token factors and non-volatile loads.
227   /// In order to remain efficient, this only
228   /// looks a couple of nodes in, it does not do an exhaustive search.
229   bool reachesChainWithoutSideEffects(SDValue Dest,
230                                       unsigned Depth = 2) const;
231 
232   /// Return true if there are no nodes using value ResNo of Node.
233   inline bool use_empty() const;
234 
235   /// Return true if there is exactly one node using value ResNo of Node.
236   inline bool hasOneUse() const;
237 };
238 
239 template<> struct DenseMapInfo<SDValue> {
240   static inline SDValue getEmptyKey() {
241     SDValue V;
242     V.ResNo = -1U;
243     return V;
244   }
245 
246   static inline SDValue getTombstoneKey() {
247     SDValue V;
248     V.ResNo = -2U;
249     return V;
250   }
251 
252   static unsigned getHashValue(const SDValue &Val) {
253     return ((unsigned)((uintptr_t)Val.getNode() >> 4) ^
254             (unsigned)((uintptr_t)Val.getNode() >> 9)) + Val.getResNo();
255   }
256 
257   static bool isEqual(const SDValue &LHS, const SDValue &RHS) {
258     return LHS == RHS;
259   }
260 };
261 
262 /// Allow casting operators to work directly on
263 /// SDValues as if they were SDNode*'s.
264 template<> struct simplify_type<SDValue> {
265   using SimpleType = SDNode *;
266 
267   static SimpleType getSimplifiedValue(SDValue &Val) {
268     return Val.getNode();
269   }
270 };
271 template<> struct simplify_type<const SDValue> {
272   using SimpleType = /*const*/ SDNode *;
273 
274   static SimpleType getSimplifiedValue(const SDValue &Val) {
275     return Val.getNode();
276   }
277 };
278 
279 /// Represents a use of a SDNode. This class holds an SDValue,
280 /// which records the SDNode being used and the result number, a
281 /// pointer to the SDNode using the value, and Next and Prev pointers,
282 /// which link together all the uses of an SDNode.
283 ///
284 class SDUse {
285   /// Val - The value being used.
286   SDValue Val;
287   /// User - The user of this value.
288   SDNode *User = nullptr;
289   /// Prev, Next - Pointers to the uses list of the SDNode referred by
290   /// this operand.
291   SDUse **Prev = nullptr;
292   SDUse *Next = nullptr;
293 
294 public:
295   SDUse() = default;
296   SDUse(const SDUse &U) = delete;
297   SDUse &operator=(const SDUse &) = delete;
298 
299   /// Normally SDUse will just implicitly convert to an SDValue that it holds.
300   operator const SDValue&() const { return Val; }
301 
302   /// If implicit conversion to SDValue doesn't work, the get() method returns
303   /// the SDValue.
304   const SDValue &get() const { return Val; }
305 
306   /// This returns the SDNode that contains this Use.
307   SDNode *getUser() { return User; }
308   const SDNode *getUser() const { return User; }
309 
310   /// Get the next SDUse in the use list.
311   SDUse *getNext() const { return Next; }
312 
313   /// Convenience function for get().getNode().
314   SDNode *getNode() const { return Val.getNode(); }
315   /// Convenience function for get().getResNo().
316   unsigned getResNo() const { return Val.getResNo(); }
317   /// Convenience function for get().getValueType().
318   EVT getValueType() const { return Val.getValueType(); }
319 
320   /// Convenience function for get().operator==
321   bool operator==(const SDValue &V) const {
322     return Val == V;
323   }
324 
325   /// Convenience function for get().operator!=
326   bool operator!=(const SDValue &V) const {
327     return Val != V;
328   }
329 
330   /// Convenience function for get().operator<
331   bool operator<(const SDValue &V) const {
332     return Val < V;
333   }
334 
335 private:
336   friend class SelectionDAG;
337   friend class SDNode;
338   // TODO: unfriend HandleSDNode once we fix its operand handling.
339   friend class HandleSDNode;
340 
341   void setUser(SDNode *p) { User = p; }
342 
343   /// Remove this use from its existing use list, assign it the
344   /// given value, and add it to the new value's node's use list.
345   inline void set(const SDValue &V);
346   /// Like set, but only supports initializing a newly-allocated
347   /// SDUse with a non-null value.
348   inline void setInitial(const SDValue &V);
349   /// Like set, but only sets the Node portion of the value,
350   /// leaving the ResNo portion unmodified.
351   inline void setNode(SDNode *N);
352 
353   void addToList(SDUse **List) {
354     Next = *List;
355     if (Next) Next->Prev = &Next;
356     Prev = List;
357     *List = this;
358   }
359 
360   void removeFromList() {
361     *Prev = Next;
362     if (Next) Next->Prev = Prev;
363   }
364 };
365 
366 /// simplify_type specializations - Allow casting operators to work directly on
367 /// SDValues as if they were SDNode*'s.
368 template<> struct simplify_type<SDUse> {
369   using SimpleType = SDNode *;
370 
371   static SimpleType getSimplifiedValue(SDUse &Val) {
372     return Val.getNode();
373   }
374 };
375 
376 /// These are IR-level optimization flags that may be propagated to SDNodes.
377 /// TODO: This data structure should be shared by the IR optimizer and the
378 /// the backend.
379 struct SDNodeFlags {
380 private:
381   bool NoUnsignedWrap : 1;
382   bool NoSignedWrap : 1;
383   bool Exact : 1;
384   bool NoNaNs : 1;
385   bool NoInfs : 1;
386   bool NoSignedZeros : 1;
387   bool AllowReciprocal : 1;
388   bool AllowContract : 1;
389   bool ApproximateFuncs : 1;
390   bool AllowReassociation : 1;
391 
392   // We assume instructions do not raise floating-point exceptions by default,
393   // and only those marked explicitly may do so.  We could choose to represent
394   // this via a positive "FPExcept" flags like on the MI level, but having a
395   // negative "NoFPExcept" flag here makes the flag intersection logic more
396   // straightforward.
397   bool NoFPExcept : 1;
398   // Instructions with attached 'unpredictable' metadata on IR level.
399   bool Unpredictable : 1;
400 
401 public:
402   /// Default constructor turns off all optimization flags.
403   SDNodeFlags()
404       : NoUnsignedWrap(false), NoSignedWrap(false), Exact(false), NoNaNs(false),
405         NoInfs(false), NoSignedZeros(false), AllowReciprocal(false),
406         AllowContract(false), ApproximateFuncs(false),
407         AllowReassociation(false), NoFPExcept(false), Unpredictable(false) {}
408 
409   /// Propagate the fast-math-flags from an IR FPMathOperator.
410   void copyFMF(const FPMathOperator &FPMO) {
411     setNoNaNs(FPMO.hasNoNaNs());
412     setNoInfs(FPMO.hasNoInfs());
413     setNoSignedZeros(FPMO.hasNoSignedZeros());
414     setAllowReciprocal(FPMO.hasAllowReciprocal());
415     setAllowContract(FPMO.hasAllowContract());
416     setApproximateFuncs(FPMO.hasApproxFunc());
417     setAllowReassociation(FPMO.hasAllowReassoc());
418   }
419 
420   // These are mutators for each flag.
421   void setNoUnsignedWrap(bool b) { NoUnsignedWrap = b; }
422   void setNoSignedWrap(bool b) { NoSignedWrap = b; }
423   void setExact(bool b) { Exact = b; }
424   void setNoNaNs(bool b) { NoNaNs = b; }
425   void setNoInfs(bool b) { NoInfs = b; }
426   void setNoSignedZeros(bool b) { NoSignedZeros = b; }
427   void setAllowReciprocal(bool b) { AllowReciprocal = b; }
428   void setAllowContract(bool b) { AllowContract = b; }
429   void setApproximateFuncs(bool b) { ApproximateFuncs = b; }
430   void setAllowReassociation(bool b) { AllowReassociation = b; }
431   void setNoFPExcept(bool b) { NoFPExcept = b; }
432   void setUnpredictable(bool b) { Unpredictable = b; }
433 
434   // These are accessors for each flag.
435   bool hasNoUnsignedWrap() const { return NoUnsignedWrap; }
436   bool hasNoSignedWrap() const { return NoSignedWrap; }
437   bool hasExact() const { return Exact; }
438   bool hasNoNaNs() const { return NoNaNs; }
439   bool hasNoInfs() const { return NoInfs; }
440   bool hasNoSignedZeros() const { return NoSignedZeros; }
441   bool hasAllowReciprocal() const { return AllowReciprocal; }
442   bool hasAllowContract() const { return AllowContract; }
443   bool hasApproximateFuncs() const { return ApproximateFuncs; }
444   bool hasAllowReassociation() const { return AllowReassociation; }
445   bool hasNoFPExcept() const { return NoFPExcept; }
446   bool hasUnpredictable() const { return Unpredictable; }
447 
448   /// Clear any flags in this flag set that aren't also set in Flags. All
449   /// flags will be cleared if Flags are undefined.
450   void intersectWith(const SDNodeFlags Flags) {
451     NoUnsignedWrap &= Flags.NoUnsignedWrap;
452     NoSignedWrap &= Flags.NoSignedWrap;
453     Exact &= Flags.Exact;
454     NoNaNs &= Flags.NoNaNs;
455     NoInfs &= Flags.NoInfs;
456     NoSignedZeros &= Flags.NoSignedZeros;
457     AllowReciprocal &= Flags.AllowReciprocal;
458     AllowContract &= Flags.AllowContract;
459     ApproximateFuncs &= Flags.ApproximateFuncs;
460     AllowReassociation &= Flags.AllowReassociation;
461     NoFPExcept &= Flags.NoFPExcept;
462     Unpredictable &= Flags.Unpredictable;
463   }
464 };
465 
466 /// Represents one node in the SelectionDAG.
467 ///
468 class SDNode : public FoldingSetNode, public ilist_node<SDNode> {
469 private:
470   /// The operation that this node performs.
471   int32_t NodeType;
472 
473 public:
474   /// Unique and persistent id per SDNode in the DAG. Used for debug printing.
475   /// We do not place that under `#if LLVM_ENABLE_ABI_BREAKING_CHECKS`
476   /// intentionally because it adds unneeded complexity without noticeable
477   /// benefits (see discussion with @thakis in D120714).
478   uint16_t PersistentId = 0xffff;
479 
480 protected:
481   // We define a set of mini-helper classes to help us interpret the bits in our
482   // SubclassData.  These are designed to fit within a uint16_t so they pack
483   // with PersistentId.
484 
485 #if defined(_AIX) && (!defined(__GNUC__) || defined(__clang__))
486 // Except for GCC; by default, AIX compilers store bit-fields in 4-byte words
487 // and give the `pack` pragma push semantics.
488 #define BEGIN_TWO_BYTE_PACK() _Pragma("pack(2)")
489 #define END_TWO_BYTE_PACK() _Pragma("pack(pop)")
490 #else
491 #define BEGIN_TWO_BYTE_PACK()
492 #define END_TWO_BYTE_PACK()
493 #endif
494 
495 BEGIN_TWO_BYTE_PACK()
496   class SDNodeBitfields {
497     friend class SDNode;
498     friend class MemIntrinsicSDNode;
499     friend class MemSDNode;
500     friend class SelectionDAG;
501 
502     uint16_t HasDebugValue : 1;
503     uint16_t IsMemIntrinsic : 1;
504     uint16_t IsDivergent : 1;
505   };
506   enum { NumSDNodeBits = 3 };
507 
508   class ConstantSDNodeBitfields {
509     friend class ConstantSDNode;
510 
511     uint16_t : NumSDNodeBits;
512 
513     uint16_t IsOpaque : 1;
514   };
515 
516   class MemSDNodeBitfields {
517     friend class MemSDNode;
518     friend class MemIntrinsicSDNode;
519     friend class AtomicSDNode;
520 
521     uint16_t : NumSDNodeBits;
522 
523     uint16_t IsVolatile : 1;
524     uint16_t IsNonTemporal : 1;
525     uint16_t IsDereferenceable : 1;
526     uint16_t IsInvariant : 1;
527   };
528   enum { NumMemSDNodeBits = NumSDNodeBits + 4 };
529 
530   class LSBaseSDNodeBitfields {
531     friend class LSBaseSDNode;
532     friend class VPBaseLoadStoreSDNode;
533     friend class MaskedLoadStoreSDNode;
534     friend class MaskedGatherScatterSDNode;
535     friend class VPGatherScatterSDNode;
536 
537     uint16_t : NumMemSDNodeBits;
538 
539     // This storage is shared between disparate class hierarchies to hold an
540     // enumeration specific to the class hierarchy in use.
541     //   LSBaseSDNode => enum ISD::MemIndexedMode
542     //   VPLoadStoreBaseSDNode => enum ISD::MemIndexedMode
543     //   MaskedLoadStoreBaseSDNode => enum ISD::MemIndexedMode
544     //   VPGatherScatterSDNode => enum ISD::MemIndexType
545     //   MaskedGatherScatterSDNode => enum ISD::MemIndexType
546     uint16_t AddressingMode : 3;
547   };
548   enum { NumLSBaseSDNodeBits = NumMemSDNodeBits + 3 };
549 
550   class LoadSDNodeBitfields {
551     friend class LoadSDNode;
552     friend class VPLoadSDNode;
553     friend class VPStridedLoadSDNode;
554     friend class MaskedLoadSDNode;
555     friend class MaskedGatherSDNode;
556     friend class VPGatherSDNode;
557 
558     uint16_t : NumLSBaseSDNodeBits;
559 
560     uint16_t ExtTy : 2; // enum ISD::LoadExtType
561     uint16_t IsExpanding : 1;
562   };
563 
564   class StoreSDNodeBitfields {
565     friend class StoreSDNode;
566     friend class VPStoreSDNode;
567     friend class VPStridedStoreSDNode;
568     friend class MaskedStoreSDNode;
569     friend class MaskedScatterSDNode;
570     friend class VPScatterSDNode;
571 
572     uint16_t : NumLSBaseSDNodeBits;
573 
574     uint16_t IsTruncating : 1;
575     uint16_t IsCompressing : 1;
576   };
577 
578   union {
579     char RawSDNodeBits[sizeof(uint16_t)];
580     SDNodeBitfields SDNodeBits;
581     ConstantSDNodeBitfields ConstantSDNodeBits;
582     MemSDNodeBitfields MemSDNodeBits;
583     LSBaseSDNodeBitfields LSBaseSDNodeBits;
584     LoadSDNodeBitfields LoadSDNodeBits;
585     StoreSDNodeBitfields StoreSDNodeBits;
586   };
587 END_TWO_BYTE_PACK()
588 #undef BEGIN_TWO_BYTE_PACK
589 #undef END_TWO_BYTE_PACK
590 
591   // RawSDNodeBits must cover the entirety of the union.  This means that all of
592   // the union's members must have size <= RawSDNodeBits.  We write the RHS as
593   // "2" instead of sizeof(RawSDNodeBits) because MSVC can't handle the latter.
594   static_assert(sizeof(SDNodeBitfields) <= 2, "field too wide");
595   static_assert(sizeof(ConstantSDNodeBitfields) <= 2, "field too wide");
596   static_assert(sizeof(MemSDNodeBitfields) <= 2, "field too wide");
597   static_assert(sizeof(LSBaseSDNodeBitfields) <= 2, "field too wide");
598   static_assert(sizeof(LoadSDNodeBitfields) <= 2, "field too wide");
599   static_assert(sizeof(StoreSDNodeBitfields) <= 2, "field too wide");
600 
601 private:
602   friend class SelectionDAG;
603   // TODO: unfriend HandleSDNode once we fix its operand handling.
604   friend class HandleSDNode;
605 
606   /// Unique id per SDNode in the DAG.
607   int NodeId = -1;
608 
609   /// The values that are used by this operation.
610   SDUse *OperandList = nullptr;
611 
612   /// The types of the values this node defines.  SDNode's may
613   /// define multiple values simultaneously.
614   const EVT *ValueList;
615 
616   /// List of uses for this SDNode.
617   SDUse *UseList = nullptr;
618 
619   /// The number of entries in the Operand/Value list.
620   unsigned short NumOperands = 0;
621   unsigned short NumValues;
622 
623   // The ordering of the SDNodes. It roughly corresponds to the ordering of the
624   // original LLVM instructions.
625   // This is used for turning off scheduling, because we'll forgo
626   // the normal scheduling algorithms and output the instructions according to
627   // this ordering.
628   unsigned IROrder;
629 
630   /// Source line information.
631   DebugLoc debugLoc;
632 
633   /// Return a pointer to the specified value type.
634   static const EVT *getValueTypeList(EVT VT);
635 
636   SDNodeFlags Flags;
637 
638   uint32_t CFIType = 0;
639 
640 public:
641   //===--------------------------------------------------------------------===//
642   //  Accessors
643   //
644 
645   /// Return the SelectionDAG opcode value for this node. For
646   /// pre-isel nodes (those for which isMachineOpcode returns false), these
647   /// are the opcode values in the ISD and <target>ISD namespaces. For
648   /// post-isel opcodes, see getMachineOpcode.
649   unsigned getOpcode()  const { return (unsigned)NodeType; }
650 
651   /// Test if this node has a target-specific opcode (in the
652   /// \<target\>ISD namespace).
653   bool isTargetOpcode() const { return NodeType >= ISD::BUILTIN_OP_END; }
654 
655   /// Test if this node has a target-specific opcode that may raise
656   /// FP exceptions (in the \<target\>ISD namespace and greater than
657   /// FIRST_TARGET_STRICTFP_OPCODE).  Note that all target memory
658   /// opcode are currently automatically considered to possibly raise
659   /// FP exceptions as well.
660   bool isTargetStrictFPOpcode() const {
661     return NodeType >= ISD::FIRST_TARGET_STRICTFP_OPCODE;
662   }
663 
664   /// Test if this node has a target-specific
665   /// memory-referencing opcode (in the \<target\>ISD namespace and
666   /// greater than FIRST_TARGET_MEMORY_OPCODE).
667   bool isTargetMemoryOpcode() const {
668     return NodeType >= ISD::FIRST_TARGET_MEMORY_OPCODE;
669   }
670 
671   /// Return true if the type of the node type undefined.
672   bool isUndef() const { return NodeType == ISD::UNDEF; }
673 
674   /// Test if this node is a memory intrinsic (with valid pointer information).
675   /// INTRINSIC_W_CHAIN and INTRINSIC_VOID nodes are sometimes created for
676   /// non-memory intrinsics (with chains) that are not really instances of
677   /// MemSDNode. For such nodes, we need some extra state to determine the
678   /// proper classof relationship.
679   bool isMemIntrinsic() const {
680     return (NodeType == ISD::INTRINSIC_W_CHAIN ||
681             NodeType == ISD::INTRINSIC_VOID) &&
682            SDNodeBits.IsMemIntrinsic;
683   }
684 
685   /// Test if this node is a strict floating point pseudo-op.
686   bool isStrictFPOpcode() {
687     switch (NodeType) {
688       default:
689         return false;
690       case ISD::STRICT_FP16_TO_FP:
691       case ISD::STRICT_FP_TO_FP16:
692 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
693       case ISD::STRICT_##DAGN:
694 #include "llvm/IR/ConstrainedOps.def"
695         return true;
696     }
697   }
698 
699   /// Test if this node is a vector predication operation.
700   bool isVPOpcode() const { return ISD::isVPOpcode(getOpcode()); }
701 
702   /// Test if this node has a post-isel opcode, directly
703   /// corresponding to a MachineInstr opcode.
704   bool isMachineOpcode() const { return NodeType < 0; }
705 
706   /// This may only be called if isMachineOpcode returns
707   /// true. It returns the MachineInstr opcode value that the node's opcode
708   /// corresponds to.
709   unsigned getMachineOpcode() const {
710     assert(isMachineOpcode() && "Not a MachineInstr opcode!");
711     return ~NodeType;
712   }
713 
714   bool getHasDebugValue() const { return SDNodeBits.HasDebugValue; }
715   void setHasDebugValue(bool b) { SDNodeBits.HasDebugValue = b; }
716 
717   bool isDivergent() const { return SDNodeBits.IsDivergent; }
718 
719   /// Return true if there are no uses of this node.
720   bool use_empty() const { return UseList == nullptr; }
721 
722   /// Return true if there is exactly one use of this node.
723   bool hasOneUse() const { return hasSingleElement(uses()); }
724 
725   /// Return the number of uses of this node. This method takes
726   /// time proportional to the number of uses.
727   size_t use_size() const { return std::distance(use_begin(), use_end()); }
728 
729   /// Return the unique node id.
730   int getNodeId() const { return NodeId; }
731 
732   /// Set unique node id.
733   void setNodeId(int Id) { NodeId = Id; }
734 
735   /// Return the node ordering.
736   unsigned getIROrder() const { return IROrder; }
737 
738   /// Set the node ordering.
739   void setIROrder(unsigned Order) { IROrder = Order; }
740 
741   /// Return the source location info.
742   const DebugLoc &getDebugLoc() const { return debugLoc; }
743 
744   /// Set source location info.  Try to avoid this, putting
745   /// it in the constructor is preferable.
746   void setDebugLoc(DebugLoc dl) { debugLoc = std::move(dl); }
747 
748   /// This class provides iterator support for SDUse
749   /// operands that use a specific SDNode.
750   class use_iterator {
751     friend class SDNode;
752 
753     SDUse *Op = nullptr;
754 
755     explicit use_iterator(SDUse *op) : Op(op) {}
756 
757   public:
758     using iterator_category = std::forward_iterator_tag;
759     using value_type = SDUse;
760     using difference_type = std::ptrdiff_t;
761     using pointer = value_type *;
762     using reference = value_type &;
763 
764     use_iterator() = default;
765     use_iterator(const use_iterator &I) = default;
766     use_iterator &operator=(const use_iterator &) = default;
767 
768     bool operator==(const use_iterator &x) const { return Op == x.Op; }
769     bool operator!=(const use_iterator &x) const {
770       return !operator==(x);
771     }
772 
773     /// Return true if this iterator is at the end of uses list.
774     bool atEnd() const { return Op == nullptr; }
775 
776     // Iterator traversal: forward iteration only.
777     use_iterator &operator++() {          // Preincrement
778       assert(Op && "Cannot increment end iterator!");
779       Op = Op->getNext();
780       return *this;
781     }
782 
783     use_iterator operator++(int) {        // Postincrement
784       use_iterator tmp = *this; ++*this; return tmp;
785     }
786 
787     /// Retrieve a pointer to the current user node.
788     SDNode *operator*() const {
789       assert(Op && "Cannot dereference end iterator!");
790       return Op->getUser();
791     }
792 
793     SDNode *operator->() const { return operator*(); }
794 
795     SDUse &getUse() const { return *Op; }
796 
797     /// Retrieve the operand # of this use in its user.
798     unsigned getOperandNo() const {
799       assert(Op && "Cannot dereference end iterator!");
800       return (unsigned)(Op - Op->getUser()->OperandList);
801     }
802   };
803 
804   /// Provide iteration support to walk over all uses of an SDNode.
805   use_iterator use_begin() const {
806     return use_iterator(UseList);
807   }
808 
809   static use_iterator use_end() { return use_iterator(nullptr); }
810 
811   inline iterator_range<use_iterator> uses() {
812     return make_range(use_begin(), use_end());
813   }
814   inline iterator_range<use_iterator> uses() const {
815     return make_range(use_begin(), use_end());
816   }
817 
818   /// Return true if there are exactly NUSES uses of the indicated value.
819   /// This method ignores uses of other values defined by this operation.
820   bool hasNUsesOfValue(unsigned NUses, unsigned Value) const;
821 
822   /// Return true if there are any use of the indicated value.
823   /// This method ignores uses of other values defined by this operation.
824   bool hasAnyUseOfValue(unsigned Value) const;
825 
826   /// Return true if this node is the only use of N.
827   bool isOnlyUserOf(const SDNode *N) const;
828 
829   /// Return true if this node is an operand of N.
830   bool isOperandOf(const SDNode *N) const;
831 
832   /// Return true if this node is a predecessor of N.
833   /// NOTE: Implemented on top of hasPredecessor and every bit as
834   /// expensive. Use carefully.
835   bool isPredecessorOf(const SDNode *N) const {
836     return N->hasPredecessor(this);
837   }
838 
839   /// Return true if N is a predecessor of this node.
840   /// N is either an operand of this node, or can be reached by recursively
841   /// traversing up the operands.
842   /// NOTE: This is an expensive method. Use it carefully.
843   bool hasPredecessor(const SDNode *N) const;
844 
845   /// Returns true if N is a predecessor of any node in Worklist. This
846   /// helper keeps Visited and Worklist sets externally to allow unions
847   /// searches to be performed in parallel, caching of results across
848   /// queries and incremental addition to Worklist. Stops early if N is
849   /// found but will resume. Remember to clear Visited and Worklists
850   /// if DAG changes. MaxSteps gives a maximum number of nodes to visit before
851   /// giving up. The TopologicalPrune flag signals that positive NodeIds are
852   /// topologically ordered (Operands have strictly smaller node id) and search
853   /// can be pruned leveraging this.
854   static bool hasPredecessorHelper(const SDNode *N,
855                                    SmallPtrSetImpl<const SDNode *> &Visited,
856                                    SmallVectorImpl<const SDNode *> &Worklist,
857                                    unsigned int MaxSteps = 0,
858                                    bool TopologicalPrune = false) {
859     SmallVector<const SDNode *, 8> DeferredNodes;
860     if (Visited.count(N))
861       return true;
862 
863     // Node Id's are assigned in three places: As a topological
864     // ordering (> 0), during legalization (results in values set to
865     // 0), new nodes (set to -1). If N has a topolgical id then we
866     // know that all nodes with ids smaller than it cannot be
867     // successors and we need not check them. Filter out all node
868     // that can't be matches. We add them to the worklist before exit
869     // in case of multiple calls. Note that during selection the topological id
870     // may be violated if a node's predecessor is selected before it. We mark
871     // this at selection negating the id of unselected successors and
872     // restricting topological pruning to positive ids.
873 
874     int NId = N->getNodeId();
875     // If we Invalidated the Id, reconstruct original NId.
876     if (NId < -1)
877       NId = -(NId + 1);
878 
879     bool Found = false;
880     while (!Worklist.empty()) {
881       const SDNode *M = Worklist.pop_back_val();
882       int MId = M->getNodeId();
883       if (TopologicalPrune && M->getOpcode() != ISD::TokenFactor && (NId > 0) &&
884           (MId > 0) && (MId < NId)) {
885         DeferredNodes.push_back(M);
886         continue;
887       }
888       for (const SDValue &OpV : M->op_values()) {
889         SDNode *Op = OpV.getNode();
890         if (Visited.insert(Op).second)
891           Worklist.push_back(Op);
892         if (Op == N)
893           Found = true;
894       }
895       if (Found)
896         break;
897       if (MaxSteps != 0 && Visited.size() >= MaxSteps)
898         break;
899     }
900     // Push deferred nodes back on worklist.
901     Worklist.append(DeferredNodes.begin(), DeferredNodes.end());
902     // If we bailed early, conservatively return found.
903     if (MaxSteps != 0 && Visited.size() >= MaxSteps)
904       return true;
905     return Found;
906   }
907 
908   /// Return true if all the users of N are contained in Nodes.
909   /// NOTE: Requires at least one match, but doesn't require them all.
910   static bool areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N);
911 
912   /// Return the number of values used by this operation.
913   unsigned getNumOperands() const { return NumOperands; }
914 
915   /// Return the maximum number of operands that a SDNode can hold.
916   static constexpr size_t getMaxNumOperands() {
917     return std::numeric_limits<decltype(SDNode::NumOperands)>::max();
918   }
919 
920   /// Helper method returns the integer value of a ConstantSDNode operand.
921   inline uint64_t getConstantOperandVal(unsigned Num) const;
922 
923   /// Helper method returns the APInt of a ConstantSDNode operand.
924   inline const APInt &getConstantOperandAPInt(unsigned Num) const;
925 
926   const SDValue &getOperand(unsigned Num) const {
927     assert(Num < NumOperands && "Invalid child # of SDNode!");
928     return OperandList[Num];
929   }
930 
931   using op_iterator = SDUse *;
932 
933   op_iterator op_begin() const { return OperandList; }
934   op_iterator op_end() const { return OperandList+NumOperands; }
935   ArrayRef<SDUse> ops() const { return ArrayRef(op_begin(), op_end()); }
936 
937   /// Iterator for directly iterating over the operand SDValue's.
938   struct value_op_iterator
939       : iterator_adaptor_base<value_op_iterator, op_iterator,
940                               std::random_access_iterator_tag, SDValue,
941                               ptrdiff_t, value_op_iterator *,
942                               value_op_iterator *> {
943     explicit value_op_iterator(SDUse *U = nullptr)
944       : iterator_adaptor_base(U) {}
945 
946     const SDValue &operator*() const { return I->get(); }
947   };
948 
949   iterator_range<value_op_iterator> op_values() const {
950     return make_range(value_op_iterator(op_begin()),
951                       value_op_iterator(op_end()));
952   }
953 
954   SDVTList getVTList() const {
955     SDVTList X = { ValueList, NumValues };
956     return X;
957   }
958 
959   /// If this node has a glue operand, return the node
960   /// to which the glue operand points. Otherwise return NULL.
961   SDNode *getGluedNode() const {
962     if (getNumOperands() != 0 &&
963         getOperand(getNumOperands()-1).getValueType() == MVT::Glue)
964       return getOperand(getNumOperands()-1).getNode();
965     return nullptr;
966   }
967 
968   /// If this node has a glue value with a user, return
969   /// the user (there is at most one). Otherwise return NULL.
970   SDNode *getGluedUser() const {
971     for (use_iterator UI = use_begin(), UE = use_end(); UI != UE; ++UI)
972       if (UI.getUse().get().getValueType() == MVT::Glue)
973         return *UI;
974     return nullptr;
975   }
976 
977   SDNodeFlags getFlags() const { return Flags; }
978   void setFlags(SDNodeFlags NewFlags) { Flags = NewFlags; }
979 
980   /// Clear any flags in this node that aren't also set in Flags.
981   /// If Flags is not in a defined state then this has no effect.
982   void intersectFlagsWith(const SDNodeFlags Flags);
983 
984   void setCFIType(uint32_t Type) { CFIType = Type; }
985   uint32_t getCFIType() const { return CFIType; }
986 
987   /// Return the number of values defined/returned by this operator.
988   unsigned getNumValues() const { return NumValues; }
989 
990   /// Return the type of a specified result.
991   EVT getValueType(unsigned ResNo) const {
992     assert(ResNo < NumValues && "Illegal result number!");
993     return ValueList[ResNo];
994   }
995 
996   /// Return the type of a specified result as a simple type.
997   MVT getSimpleValueType(unsigned ResNo) const {
998     return getValueType(ResNo).getSimpleVT();
999   }
1000 
1001   /// Returns MVT::getSizeInBits(getValueType(ResNo)).
1002   ///
1003   /// If the value type is a scalable vector type, the scalable property will
1004   /// be set and the runtime size will be a positive integer multiple of the
1005   /// base size.
1006   TypeSize getValueSizeInBits(unsigned ResNo) const {
1007     return getValueType(ResNo).getSizeInBits();
1008   }
1009 
1010   using value_iterator = const EVT *;
1011 
1012   value_iterator value_begin() const { return ValueList; }
1013   value_iterator value_end() const { return ValueList+NumValues; }
1014   iterator_range<value_iterator> values() const {
1015     return llvm::make_range(value_begin(), value_end());
1016   }
1017 
1018   /// Return the opcode of this operation for printing.
1019   std::string getOperationName(const SelectionDAG *G = nullptr) const;
1020   static const char* getIndexedModeName(ISD::MemIndexedMode AM);
1021   void print_types(raw_ostream &OS, const SelectionDAG *G) const;
1022   void print_details(raw_ostream &OS, const SelectionDAG *G) const;
1023   void print(raw_ostream &OS, const SelectionDAG *G = nullptr) const;
1024   void printr(raw_ostream &OS, const SelectionDAG *G = nullptr) const;
1025 
1026   /// Print a SelectionDAG node and all children down to
1027   /// the leaves.  The given SelectionDAG allows target-specific nodes
1028   /// to be printed in human-readable form.  Unlike printr, this will
1029   /// print the whole DAG, including children that appear multiple
1030   /// times.
1031   ///
1032   void printrFull(raw_ostream &O, const SelectionDAG *G = nullptr) const;
1033 
1034   /// Print a SelectionDAG node and children up to
1035   /// depth "depth."  The given SelectionDAG allows target-specific
1036   /// nodes to be printed in human-readable form.  Unlike printr, this
1037   /// will print children that appear multiple times wherever they are
1038   /// used.
1039   ///
1040   void printrWithDepth(raw_ostream &O, const SelectionDAG *G = nullptr,
1041                        unsigned depth = 100) const;
1042 
1043   /// Dump this node, for debugging.
1044   void dump() const;
1045 
1046   /// Dump (recursively) this node and its use-def subgraph.
1047   void dumpr() const;
1048 
1049   /// Dump this node, for debugging.
1050   /// The given SelectionDAG allows target-specific nodes to be printed
1051   /// in human-readable form.
1052   void dump(const SelectionDAG *G) const;
1053 
1054   /// Dump (recursively) this node and its use-def subgraph.
1055   /// The given SelectionDAG allows target-specific nodes to be printed
1056   /// in human-readable form.
1057   void dumpr(const SelectionDAG *G) const;
1058 
1059   /// printrFull to dbgs().  The given SelectionDAG allows
1060   /// target-specific nodes to be printed in human-readable form.
1061   /// Unlike dumpr, this will print the whole DAG, including children
1062   /// that appear multiple times.
1063   void dumprFull(const SelectionDAG *G = nullptr) const;
1064 
1065   /// printrWithDepth to dbgs().  The given
1066   /// SelectionDAG allows target-specific nodes to be printed in
1067   /// human-readable form.  Unlike dumpr, this will print children
1068   /// that appear multiple times wherever they are used.
1069   ///
1070   void dumprWithDepth(const SelectionDAG *G = nullptr,
1071                       unsigned depth = 100) const;
1072 
1073   /// Gather unique data for the node.
1074   void Profile(FoldingSetNodeID &ID) const;
1075 
1076   /// This method should only be used by the SDUse class.
1077   void addUse(SDUse &U) { U.addToList(&UseList); }
1078 
1079 protected:
1080   static SDVTList getSDVTList(EVT VT) {
1081     SDVTList Ret = { getValueTypeList(VT), 1 };
1082     return Ret;
1083   }
1084 
1085   /// Create an SDNode.
1086   ///
1087   /// SDNodes are created without any operands, and never own the operand
1088   /// storage. To add operands, see SelectionDAG::createOperands.
1089   SDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs)
1090       : NodeType(Opc), ValueList(VTs.VTs), NumValues(VTs.NumVTs),
1091         IROrder(Order), debugLoc(std::move(dl)) {
1092     memset(&RawSDNodeBits, 0, sizeof(RawSDNodeBits));
1093     assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
1094     assert(NumValues == VTs.NumVTs &&
1095            "NumValues wasn't wide enough for its operands!");
1096   }
1097 
1098   /// Release the operands and set this node to have zero operands.
1099   void DropOperands();
1100 };
1101 
1102 /// Wrapper class for IR location info (IR ordering and DebugLoc) to be passed
1103 /// into SDNode creation functions.
1104 /// When an SDNode is created from the DAGBuilder, the DebugLoc is extracted
1105 /// from the original Instruction, and IROrder is the ordinal position of
1106 /// the instruction.
1107 /// When an SDNode is created after the DAG is being built, both DebugLoc and
1108 /// the IROrder are propagated from the original SDNode.
1109 /// So SDLoc class provides two constructors besides the default one, one to
1110 /// be used by the DAGBuilder, the other to be used by others.
1111 class SDLoc {
1112 private:
1113   DebugLoc DL;
1114   int IROrder = 0;
1115 
1116 public:
1117   SDLoc() = default;
1118   SDLoc(const SDNode *N) : DL(N->getDebugLoc()), IROrder(N->getIROrder()) {}
1119   SDLoc(const SDValue V) : SDLoc(V.getNode()) {}
1120   SDLoc(const Instruction *I, int Order) : IROrder(Order) {
1121     assert(Order >= 0 && "bad IROrder");
1122     if (I)
1123       DL = I->getDebugLoc();
1124   }
1125 
1126   unsigned getIROrder() const { return IROrder; }
1127   const DebugLoc &getDebugLoc() const { return DL; }
1128 };
1129 
1130 // Define inline functions from the SDValue class.
1131 
1132 inline SDValue::SDValue(SDNode *node, unsigned resno)
1133     : Node(node), ResNo(resno) {
1134   // Explicitly check for !ResNo to avoid use-after-free, because there are
1135   // callers that use SDValue(N, 0) with a deleted N to indicate successful
1136   // combines.
1137   assert((!Node || !ResNo || ResNo < Node->getNumValues()) &&
1138          "Invalid result number for the given node!");
1139   assert(ResNo < -2U && "Cannot use result numbers reserved for DenseMaps.");
1140 }
1141 
1142 inline unsigned SDValue::getOpcode() const {
1143   return Node->getOpcode();
1144 }
1145 
1146 inline EVT SDValue::getValueType() const {
1147   return Node->getValueType(ResNo);
1148 }
1149 
1150 inline unsigned SDValue::getNumOperands() const {
1151   return Node->getNumOperands();
1152 }
1153 
1154 inline const SDValue &SDValue::getOperand(unsigned i) const {
1155   return Node->getOperand(i);
1156 }
1157 
1158 inline uint64_t SDValue::getConstantOperandVal(unsigned i) const {
1159   return Node->getConstantOperandVal(i);
1160 }
1161 
1162 inline const APInt &SDValue::getConstantOperandAPInt(unsigned i) const {
1163   return Node->getConstantOperandAPInt(i);
1164 }
1165 
1166 inline bool SDValue::isTargetOpcode() const {
1167   return Node->isTargetOpcode();
1168 }
1169 
1170 inline bool SDValue::isTargetMemoryOpcode() const {
1171   return Node->isTargetMemoryOpcode();
1172 }
1173 
1174 inline bool SDValue::isMachineOpcode() const {
1175   return Node->isMachineOpcode();
1176 }
1177 
1178 inline unsigned SDValue::getMachineOpcode() const {
1179   return Node->getMachineOpcode();
1180 }
1181 
1182 inline bool SDValue::isUndef() const {
1183   return Node->isUndef();
1184 }
1185 
1186 inline bool SDValue::use_empty() const {
1187   return !Node->hasAnyUseOfValue(ResNo);
1188 }
1189 
1190 inline bool SDValue::hasOneUse() const {
1191   return Node->hasNUsesOfValue(1, ResNo);
1192 }
1193 
1194 inline const DebugLoc &SDValue::getDebugLoc() const {
1195   return Node->getDebugLoc();
1196 }
1197 
1198 inline void SDValue::dump() const {
1199   return Node->dump();
1200 }
1201 
1202 inline void SDValue::dump(const SelectionDAG *G) const {
1203   return Node->dump(G);
1204 }
1205 
1206 inline void SDValue::dumpr() const {
1207   return Node->dumpr();
1208 }
1209 
1210 inline void SDValue::dumpr(const SelectionDAG *G) const {
1211   return Node->dumpr(G);
1212 }
1213 
1214 // Define inline functions from the SDUse class.
1215 
1216 inline void SDUse::set(const SDValue &V) {
1217   if (Val.getNode()) removeFromList();
1218   Val = V;
1219   if (V.getNode())
1220     V->addUse(*this);
1221 }
1222 
1223 inline void SDUse::setInitial(const SDValue &V) {
1224   Val = V;
1225   V->addUse(*this);
1226 }
1227 
1228 inline void SDUse::setNode(SDNode *N) {
1229   if (Val.getNode()) removeFromList();
1230   Val.setNode(N);
1231   if (N) N->addUse(*this);
1232 }
1233 
1234 /// This class is used to form a handle around another node that
1235 /// is persistent and is updated across invocations of replaceAllUsesWith on its
1236 /// operand.  This node should be directly created by end-users and not added to
1237 /// the AllNodes list.
1238 class HandleSDNode : public SDNode {
1239   SDUse Op;
1240 
1241 public:
1242   explicit HandleSDNode(SDValue X)
1243     : SDNode(ISD::HANDLENODE, 0, DebugLoc(), getSDVTList(MVT::Other)) {
1244     // HandleSDNodes are never inserted into the DAG, so they won't be
1245     // auto-numbered. Use ID 65535 as a sentinel.
1246     PersistentId = 0xffff;
1247 
1248     // Manually set up the operand list. This node type is special in that it's
1249     // always stack allocated and SelectionDAG does not manage its operands.
1250     // TODO: This should either (a) not be in the SDNode hierarchy, or (b) not
1251     // be so special.
1252     Op.setUser(this);
1253     Op.setInitial(X);
1254     NumOperands = 1;
1255     OperandList = &Op;
1256   }
1257   ~HandleSDNode();
1258 
1259   const SDValue &getValue() const { return Op; }
1260 };
1261 
1262 class AddrSpaceCastSDNode : public SDNode {
1263 private:
1264   unsigned SrcAddrSpace;
1265   unsigned DestAddrSpace;
1266 
1267 public:
1268   AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, EVT VT,
1269                       unsigned SrcAS, unsigned DestAS);
1270 
1271   unsigned getSrcAddressSpace() const { return SrcAddrSpace; }
1272   unsigned getDestAddressSpace() const { return DestAddrSpace; }
1273 
1274   static bool classof(const SDNode *N) {
1275     return N->getOpcode() == ISD::ADDRSPACECAST;
1276   }
1277 };
1278 
1279 /// This is an abstract virtual class for memory operations.
1280 class MemSDNode : public SDNode {
1281 private:
1282   // VT of in-memory value.
1283   EVT MemoryVT;
1284 
1285 protected:
1286   /// Memory reference information.
1287   MachineMemOperand *MMO;
1288 
1289 public:
1290   MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs,
1291             EVT memvt, MachineMemOperand *MMO);
1292 
1293   bool readMem() const { return MMO->isLoad(); }
1294   bool writeMem() const { return MMO->isStore(); }
1295 
1296   /// Returns alignment and volatility of the memory access
1297   Align getOriginalAlign() const { return MMO->getBaseAlign(); }
1298   Align getAlign() const { return MMO->getAlign(); }
1299 
1300   /// Return the SubclassData value, without HasDebugValue. This contains an
1301   /// encoding of the volatile flag, as well as bits used by subclasses. This
1302   /// function should only be used to compute a FoldingSetNodeID value.
1303   /// The HasDebugValue bit is masked out because CSE map needs to match
1304   /// nodes with debug info with nodes without debug info. Same is about
1305   /// isDivergent bit.
1306   unsigned getRawSubclassData() const {
1307     uint16_t Data;
1308     union {
1309       char RawSDNodeBits[sizeof(uint16_t)];
1310       SDNodeBitfields SDNodeBits;
1311     };
1312     memcpy(&RawSDNodeBits, &this->RawSDNodeBits, sizeof(this->RawSDNodeBits));
1313     SDNodeBits.HasDebugValue = 0;
1314     SDNodeBits.IsDivergent = false;
1315     memcpy(&Data, &RawSDNodeBits, sizeof(RawSDNodeBits));
1316     return Data;
1317   }
1318 
1319   bool isVolatile() const { return MemSDNodeBits.IsVolatile; }
1320   bool isNonTemporal() const { return MemSDNodeBits.IsNonTemporal; }
1321   bool isDereferenceable() const { return MemSDNodeBits.IsDereferenceable; }
1322   bool isInvariant() const { return MemSDNodeBits.IsInvariant; }
1323 
1324   // Returns the offset from the location of the access.
1325   int64_t getSrcValueOffset() const { return MMO->getOffset(); }
1326 
1327   /// Returns the AA info that describes the dereference.
1328   AAMDNodes getAAInfo() const { return MMO->getAAInfo(); }
1329 
1330   /// Returns the Ranges that describes the dereference.
1331   const MDNode *getRanges() const { return MMO->getRanges(); }
1332 
1333   /// Returns the synchronization scope ID for this memory operation.
1334   SyncScope::ID getSyncScopeID() const { return MMO->getSyncScopeID(); }
1335 
1336   /// Return the atomic ordering requirements for this memory operation. For
1337   /// cmpxchg atomic operations, return the atomic ordering requirements when
1338   /// store occurs.
1339   AtomicOrdering getSuccessOrdering() const {
1340     return MMO->getSuccessOrdering();
1341   }
1342 
1343   /// Return a single atomic ordering that is at least as strong as both the
1344   /// success and failure orderings for an atomic operation.  (For operations
1345   /// other than cmpxchg, this is equivalent to getSuccessOrdering().)
1346   AtomicOrdering getMergedOrdering() const { return MMO->getMergedOrdering(); }
1347 
1348   /// Return true if the memory operation ordering is Unordered or higher.
1349   bool isAtomic() const { return MMO->isAtomic(); }
1350 
1351   /// Returns true if the memory operation doesn't imply any ordering
1352   /// constraints on surrounding memory operations beyond the normal memory
1353   /// aliasing rules.
1354   bool isUnordered() const { return MMO->isUnordered(); }
1355 
1356   /// Returns true if the memory operation is neither atomic or volatile.
1357   bool isSimple() const { return !isAtomic() && !isVolatile(); }
1358 
1359   /// Return the type of the in-memory value.
1360   EVT getMemoryVT() const { return MemoryVT; }
1361 
1362   /// Return a MachineMemOperand object describing the memory
1363   /// reference performed by operation.
1364   MachineMemOperand *getMemOperand() const { return MMO; }
1365 
1366   const MachinePointerInfo &getPointerInfo() const {
1367     return MMO->getPointerInfo();
1368   }
1369 
1370   /// Return the address space for the associated pointer
1371   unsigned getAddressSpace() const {
1372     return getPointerInfo().getAddrSpace();
1373   }
1374 
1375   /// Update this MemSDNode's MachineMemOperand information
1376   /// to reflect the alignment of NewMMO, if it has a greater alignment.
1377   /// This must only be used when the new alignment applies to all users of
1378   /// this MachineMemOperand.
1379   void refineAlignment(const MachineMemOperand *NewMMO) {
1380     MMO->refineAlignment(NewMMO);
1381   }
1382 
1383   const SDValue &getChain() const { return getOperand(0); }
1384 
1385   const SDValue &getBasePtr() const {
1386     switch (getOpcode()) {
1387     case ISD::STORE:
1388     case ISD::VP_STORE:
1389     case ISD::MSTORE:
1390     case ISD::VP_SCATTER:
1391     case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
1392       return getOperand(2);
1393     case ISD::MGATHER:
1394     case ISD::MSCATTER:
1395       return getOperand(3);
1396     default:
1397       return getOperand(1);
1398     }
1399   }
1400 
1401   // Methods to support isa and dyn_cast
1402   static bool classof(const SDNode *N) {
1403     // For some targets, we lower some target intrinsics to a MemIntrinsicNode
1404     // with either an intrinsic or a target opcode.
1405     switch (N->getOpcode()) {
1406     case ISD::LOAD:
1407     case ISD::STORE:
1408     case ISD::PREFETCH:
1409     case ISD::ATOMIC_CMP_SWAP:
1410     case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1411     case ISD::ATOMIC_SWAP:
1412     case ISD::ATOMIC_LOAD_ADD:
1413     case ISD::ATOMIC_LOAD_SUB:
1414     case ISD::ATOMIC_LOAD_AND:
1415     case ISD::ATOMIC_LOAD_CLR:
1416     case ISD::ATOMIC_LOAD_OR:
1417     case ISD::ATOMIC_LOAD_XOR:
1418     case ISD::ATOMIC_LOAD_NAND:
1419     case ISD::ATOMIC_LOAD_MIN:
1420     case ISD::ATOMIC_LOAD_MAX:
1421     case ISD::ATOMIC_LOAD_UMIN:
1422     case ISD::ATOMIC_LOAD_UMAX:
1423     case ISD::ATOMIC_LOAD_FADD:
1424     case ISD::ATOMIC_LOAD_FSUB:
1425     case ISD::ATOMIC_LOAD_FMAX:
1426     case ISD::ATOMIC_LOAD_FMIN:
1427     case ISD::ATOMIC_LOAD_UINC_WRAP:
1428     case ISD::ATOMIC_LOAD_UDEC_WRAP:
1429     case ISD::ATOMIC_LOAD:
1430     case ISD::ATOMIC_STORE:
1431     case ISD::MLOAD:
1432     case ISD::MSTORE:
1433     case ISD::MGATHER:
1434     case ISD::MSCATTER:
1435     case ISD::VP_LOAD:
1436     case ISD::VP_STORE:
1437     case ISD::VP_GATHER:
1438     case ISD::VP_SCATTER:
1439     case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
1440     case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
1441     case ISD::GET_FPENV_MEM:
1442     case ISD::SET_FPENV_MEM:
1443       return true;
1444     default:
1445       return N->isMemIntrinsic() || N->isTargetMemoryOpcode();
1446     }
1447   }
1448 };
1449 
1450 /// This is an SDNode representing atomic operations.
1451 class AtomicSDNode : public MemSDNode {
1452 public:
1453   AtomicSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTL,
1454                EVT MemVT, MachineMemOperand *MMO)
1455     : MemSDNode(Opc, Order, dl, VTL, MemVT, MMO) {
1456     assert(((Opc != ISD::ATOMIC_LOAD && Opc != ISD::ATOMIC_STORE) ||
1457             MMO->isAtomic()) && "then why are we using an AtomicSDNode?");
1458   }
1459 
1460   const SDValue &getBasePtr() const { return getOperand(1); }
1461   const SDValue &getVal() const { return getOperand(2); }
1462 
1463   /// Returns true if this SDNode represents cmpxchg atomic operation, false
1464   /// otherwise.
1465   bool isCompareAndSwap() const {
1466     unsigned Op = getOpcode();
1467     return Op == ISD::ATOMIC_CMP_SWAP ||
1468            Op == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS;
1469   }
1470 
1471   /// For cmpxchg atomic operations, return the atomic ordering requirements
1472   /// when store does not occur.
1473   AtomicOrdering getFailureOrdering() const {
1474     assert(isCompareAndSwap() && "Must be cmpxchg operation");
1475     return MMO->getFailureOrdering();
1476   }
1477 
1478   // Methods to support isa and dyn_cast
1479   static bool classof(const SDNode *N) {
1480     return N->getOpcode() == ISD::ATOMIC_CMP_SWAP     ||
1481            N->getOpcode() == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS ||
1482            N->getOpcode() == ISD::ATOMIC_SWAP         ||
1483            N->getOpcode() == ISD::ATOMIC_LOAD_ADD     ||
1484            N->getOpcode() == ISD::ATOMIC_LOAD_SUB     ||
1485            N->getOpcode() == ISD::ATOMIC_LOAD_AND     ||
1486            N->getOpcode() == ISD::ATOMIC_LOAD_CLR     ||
1487            N->getOpcode() == ISD::ATOMIC_LOAD_OR      ||
1488            N->getOpcode() == ISD::ATOMIC_LOAD_XOR     ||
1489            N->getOpcode() == ISD::ATOMIC_LOAD_NAND    ||
1490            N->getOpcode() == ISD::ATOMIC_LOAD_MIN     ||
1491            N->getOpcode() == ISD::ATOMIC_LOAD_MAX     ||
1492            N->getOpcode() == ISD::ATOMIC_LOAD_UMIN    ||
1493            N->getOpcode() == ISD::ATOMIC_LOAD_UMAX    ||
1494            N->getOpcode() == ISD::ATOMIC_LOAD_FADD    ||
1495            N->getOpcode() == ISD::ATOMIC_LOAD_FSUB    ||
1496            N->getOpcode() == ISD::ATOMIC_LOAD_FMAX    ||
1497            N->getOpcode() == ISD::ATOMIC_LOAD_FMIN    ||
1498            N->getOpcode() == ISD::ATOMIC_LOAD_UINC_WRAP ||
1499            N->getOpcode() == ISD::ATOMIC_LOAD_UDEC_WRAP ||
1500            N->getOpcode() == ISD::ATOMIC_LOAD         ||
1501            N->getOpcode() == ISD::ATOMIC_STORE;
1502   }
1503 };
1504 
1505 /// This SDNode is used for target intrinsics that touch
1506 /// memory and need an associated MachineMemOperand. Its opcode may be
1507 /// INTRINSIC_VOID, INTRINSIC_W_CHAIN, PREFETCH, or a target-specific opcode
1508 /// with a value not less than FIRST_TARGET_MEMORY_OPCODE.
1509 class MemIntrinsicSDNode : public MemSDNode {
1510 public:
1511   MemIntrinsicSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
1512                      SDVTList VTs, EVT MemoryVT, MachineMemOperand *MMO)
1513       : MemSDNode(Opc, Order, dl, VTs, MemoryVT, MMO) {
1514     SDNodeBits.IsMemIntrinsic = true;
1515   }
1516 
1517   // Methods to support isa and dyn_cast
1518   static bool classof(const SDNode *N) {
1519     // We lower some target intrinsics to their target opcode
1520     // early a node with a target opcode can be of this class
1521     return N->isMemIntrinsic()             ||
1522            N->getOpcode() == ISD::PREFETCH ||
1523            N->isTargetMemoryOpcode();
1524   }
1525 };
1526 
1527 /// This SDNode is used to implement the code generator
1528 /// support for the llvm IR shufflevector instruction.  It combines elements
1529 /// from two input vectors into a new input vector, with the selection and
1530 /// ordering of elements determined by an array of integers, referred to as
1531 /// the shuffle mask.  For input vectors of width N, mask indices of 0..N-1
1532 /// refer to elements from the LHS input, and indices from N to 2N-1 the RHS.
1533 /// An index of -1 is treated as undef, such that the code generator may put
1534 /// any value in the corresponding element of the result.
1535 class ShuffleVectorSDNode : public SDNode {
1536   // The memory for Mask is owned by the SelectionDAG's OperandAllocator, and
1537   // is freed when the SelectionDAG object is destroyed.
1538   const int *Mask;
1539 
1540 protected:
1541   friend class SelectionDAG;
1542 
1543   ShuffleVectorSDNode(EVT VT, unsigned Order, const DebugLoc &dl, const int *M)
1544       : SDNode(ISD::VECTOR_SHUFFLE, Order, dl, getSDVTList(VT)), Mask(M) {}
1545 
1546 public:
1547   ArrayRef<int> getMask() const {
1548     EVT VT = getValueType(0);
1549     return ArrayRef(Mask, VT.getVectorNumElements());
1550   }
1551 
1552   int getMaskElt(unsigned Idx) const {
1553     assert(Idx < getValueType(0).getVectorNumElements() && "Idx out of range!");
1554     return Mask[Idx];
1555   }
1556 
1557   bool isSplat() const { return isSplatMask(Mask, getValueType(0)); }
1558 
1559   int getSplatIndex() const {
1560     assert(isSplat() && "Cannot get splat index for non-splat!");
1561     EVT VT = getValueType(0);
1562     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1563       if (Mask[i] >= 0)
1564         return Mask[i];
1565 
1566     // We can choose any index value here and be correct because all elements
1567     // are undefined. Return 0 for better potential for callers to simplify.
1568     return 0;
1569   }
1570 
1571   static bool isSplatMask(const int *Mask, EVT VT);
1572 
1573   /// Change values in a shuffle permute mask assuming
1574   /// the two vector operands have swapped position.
1575   static void commuteMask(MutableArrayRef<int> Mask) {
1576     unsigned NumElems = Mask.size();
1577     for (unsigned i = 0; i != NumElems; ++i) {
1578       int idx = Mask[i];
1579       if (idx < 0)
1580         continue;
1581       else if (idx < (int)NumElems)
1582         Mask[i] = idx + NumElems;
1583       else
1584         Mask[i] = idx - NumElems;
1585     }
1586   }
1587 
1588   static bool classof(const SDNode *N) {
1589     return N->getOpcode() == ISD::VECTOR_SHUFFLE;
1590   }
1591 };
1592 
1593 class ConstantSDNode : public SDNode {
1594   friend class SelectionDAG;
1595 
1596   const ConstantInt *Value;
1597 
1598   ConstantSDNode(bool isTarget, bool isOpaque, const ConstantInt *val, EVT VT)
1599       : SDNode(isTarget ? ISD::TargetConstant : ISD::Constant, 0, DebugLoc(),
1600                getSDVTList(VT)),
1601         Value(val) {
1602     ConstantSDNodeBits.IsOpaque = isOpaque;
1603   }
1604 
1605 public:
1606   const ConstantInt *getConstantIntValue() const { return Value; }
1607   const APInt &getAPIntValue() const { return Value->getValue(); }
1608   uint64_t getZExtValue() const { return Value->getZExtValue(); }
1609   int64_t getSExtValue() const { return Value->getSExtValue(); }
1610   uint64_t getLimitedValue(uint64_t Limit = UINT64_MAX) {
1611     return Value->getLimitedValue(Limit);
1612   }
1613   MaybeAlign getMaybeAlignValue() const { return Value->getMaybeAlignValue(); }
1614   Align getAlignValue() const { return Value->getAlignValue(); }
1615 
1616   bool isOne() const { return Value->isOne(); }
1617   bool isZero() const { return Value->isZero(); }
1618   bool isAllOnes() const { return Value->isMinusOne(); }
1619   bool isMaxSignedValue() const { return Value->isMaxValue(true); }
1620   bool isMinSignedValue() const { return Value->isMinValue(true); }
1621 
1622   bool isOpaque() const { return ConstantSDNodeBits.IsOpaque; }
1623 
1624   static bool classof(const SDNode *N) {
1625     return N->getOpcode() == ISD::Constant ||
1626            N->getOpcode() == ISD::TargetConstant;
1627   }
1628 };
1629 
1630 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
1631   return cast<ConstantSDNode>(getOperand(Num))->getZExtValue();
1632 }
1633 
1634 const APInt &SDNode::getConstantOperandAPInt(unsigned Num) const {
1635   return cast<ConstantSDNode>(getOperand(Num))->getAPIntValue();
1636 }
1637 
1638 class ConstantFPSDNode : public SDNode {
1639   friend class SelectionDAG;
1640 
1641   const ConstantFP *Value;
1642 
1643   ConstantFPSDNode(bool isTarget, const ConstantFP *val, EVT VT)
1644       : SDNode(isTarget ? ISD::TargetConstantFP : ISD::ConstantFP, 0,
1645                DebugLoc(), getSDVTList(VT)),
1646         Value(val) {}
1647 
1648 public:
1649   const APFloat& getValueAPF() const { return Value->getValueAPF(); }
1650   const ConstantFP *getConstantFPValue() const { return Value; }
1651 
1652   /// Return true if the value is positive or negative zero.
1653   bool isZero() const { return Value->isZero(); }
1654 
1655   /// Return true if the value is a NaN.
1656   bool isNaN() const { return Value->isNaN(); }
1657 
1658   /// Return true if the value is an infinity
1659   bool isInfinity() const { return Value->isInfinity(); }
1660 
1661   /// Return true if the value is negative.
1662   bool isNegative() const { return Value->isNegative(); }
1663 
1664   /// We don't rely on operator== working on double values, as
1665   /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
1666   /// As such, this method can be used to do an exact bit-for-bit comparison of
1667   /// two floating point values.
1668 
1669   /// We leave the version with the double argument here because it's just so
1670   /// convenient to write "2.0" and the like.  Without this function we'd
1671   /// have to duplicate its logic everywhere it's called.
1672   bool isExactlyValue(double V) const {
1673     return Value->getValueAPF().isExactlyValue(V);
1674   }
1675   bool isExactlyValue(const APFloat& V) const;
1676 
1677   static bool isValueValidForType(EVT VT, const APFloat& Val);
1678 
1679   static bool classof(const SDNode *N) {
1680     return N->getOpcode() == ISD::ConstantFP ||
1681            N->getOpcode() == ISD::TargetConstantFP;
1682   }
1683 };
1684 
1685 /// Returns true if \p V is a constant integer zero.
1686 bool isNullConstant(SDValue V);
1687 
1688 /// Returns true if \p V is an FP constant with a value of positive zero.
1689 bool isNullFPConstant(SDValue V);
1690 
1691 /// Returns true if \p V is an integer constant with all bits set.
1692 bool isAllOnesConstant(SDValue V);
1693 
1694 /// Returns true if \p V is a constant integer one.
1695 bool isOneConstant(SDValue V);
1696 
1697 /// Returns true if \p V is a constant min signed integer value.
1698 bool isMinSignedConstant(SDValue V);
1699 
1700 /// Returns true if \p V is a neutral element of Opc with Flags.
1701 /// When OperandNo is 0, it checks that V is a left identity. Otherwise, it
1702 /// checks that V is a right identity.
1703 bool isNeutralConstant(unsigned Opc, SDNodeFlags Flags, SDValue V,
1704                        unsigned OperandNo);
1705 
1706 /// Return the non-bitcasted source operand of \p V if it exists.
1707 /// If \p V is not a bitcasted value, it is returned as-is.
1708 SDValue peekThroughBitcasts(SDValue V);
1709 
1710 /// Return the non-bitcasted and one-use source operand of \p V if it exists.
1711 /// If \p V is not a bitcasted one-use value, it is returned as-is.
1712 SDValue peekThroughOneUseBitcasts(SDValue V);
1713 
1714 /// Return the non-extracted vector source operand of \p V if it exists.
1715 /// If \p V is not an extracted subvector, it is returned as-is.
1716 SDValue peekThroughExtractSubvectors(SDValue V);
1717 
1718 /// Return the non-truncated source operand of \p V if it exists.
1719 /// If \p V is not a truncation, it is returned as-is.
1720 SDValue peekThroughTruncates(SDValue V);
1721 
1722 /// Returns true if \p V is a bitwise not operation. Assumes that an all ones
1723 /// constant is canonicalized to be operand 1.
1724 bool isBitwiseNot(SDValue V, bool AllowUndefs = false);
1725 
1726 /// If \p V is a bitwise not, returns the inverted operand. Otherwise returns
1727 /// an empty SDValue. Only bits set in \p Mask are required to be inverted,
1728 /// other bits may be arbitrary.
1729 SDValue getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs);
1730 
1731 /// Returns the SDNode if it is a constant splat BuildVector or constant int.
1732 ConstantSDNode *isConstOrConstSplat(SDValue N, bool AllowUndefs = false,
1733                                     bool AllowTruncation = false);
1734 
1735 /// Returns the SDNode if it is a demanded constant splat BuildVector or
1736 /// constant int.
1737 ConstantSDNode *isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
1738                                     bool AllowUndefs = false,
1739                                     bool AllowTruncation = false);
1740 
1741 /// Returns the SDNode if it is a constant splat BuildVector or constant float.
1742 ConstantFPSDNode *isConstOrConstSplatFP(SDValue N, bool AllowUndefs = false);
1743 
1744 /// Returns the SDNode if it is a demanded constant splat BuildVector or
1745 /// constant float.
1746 ConstantFPSDNode *isConstOrConstSplatFP(SDValue N, const APInt &DemandedElts,
1747                                         bool AllowUndefs = false);
1748 
1749 /// Return true if the value is a constant 0 integer or a splatted vector of
1750 /// a constant 0 integer (with no undefs by default).
1751 /// Build vector implicit truncation is not an issue for null values.
1752 bool isNullOrNullSplat(SDValue V, bool AllowUndefs = false);
1753 
1754 /// Return true if the value is a constant 1 integer or a splatted vector of a
1755 /// constant 1 integer (with no undefs).
1756 /// Build vector implicit truncation is allowed, but the truncated bits need to
1757 /// be zero.
1758 bool isOneOrOneSplat(SDValue V, bool AllowUndefs = false);
1759 
1760 /// Return true if the value is a constant -1 integer or a splatted vector of a
1761 /// constant -1 integer (with no undefs).
1762 /// Does not permit build vector implicit truncation.
1763 bool isAllOnesOrAllOnesSplat(SDValue V, bool AllowUndefs = false);
1764 
1765 /// Return true if \p V is either a integer or FP constant.
1766 inline bool isIntOrFPConstant(SDValue V) {
1767   return isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V);
1768 }
1769 
1770 class GlobalAddressSDNode : public SDNode {
1771   friend class SelectionDAG;
1772 
1773   const GlobalValue *TheGlobal;
1774   int64_t Offset;
1775   unsigned TargetFlags;
1776 
1777   GlobalAddressSDNode(unsigned Opc, unsigned Order, const DebugLoc &DL,
1778                       const GlobalValue *GA, EVT VT, int64_t o,
1779                       unsigned TF);
1780 
1781 public:
1782   const GlobalValue *getGlobal() const { return TheGlobal; }
1783   int64_t getOffset() const { return Offset; }
1784   unsigned getTargetFlags() const { return TargetFlags; }
1785   // Return the address space this GlobalAddress belongs to.
1786   unsigned getAddressSpace() const;
1787 
1788   static bool classof(const SDNode *N) {
1789     return N->getOpcode() == ISD::GlobalAddress ||
1790            N->getOpcode() == ISD::TargetGlobalAddress ||
1791            N->getOpcode() == ISD::GlobalTLSAddress ||
1792            N->getOpcode() == ISD::TargetGlobalTLSAddress;
1793   }
1794 };
1795 
1796 class FrameIndexSDNode : public SDNode {
1797   friend class SelectionDAG;
1798 
1799   int FI;
1800 
1801   FrameIndexSDNode(int fi, EVT VT, bool isTarg)
1802     : SDNode(isTarg ? ISD::TargetFrameIndex : ISD::FrameIndex,
1803       0, DebugLoc(), getSDVTList(VT)), FI(fi) {
1804   }
1805 
1806 public:
1807   int getIndex() const { return FI; }
1808 
1809   static bool classof(const SDNode *N) {
1810     return N->getOpcode() == ISD::FrameIndex ||
1811            N->getOpcode() == ISD::TargetFrameIndex;
1812   }
1813 };
1814 
1815 /// This SDNode is used for LIFETIME_START/LIFETIME_END values, which indicate
1816 /// the offet and size that are started/ended in the underlying FrameIndex.
1817 class LifetimeSDNode : public SDNode {
1818   friend class SelectionDAG;
1819   int64_t Size;
1820   int64_t Offset; // -1 if offset is unknown.
1821 
1822   LifetimeSDNode(unsigned Opcode, unsigned Order, const DebugLoc &dl,
1823                  SDVTList VTs, int64_t Size, int64_t Offset)
1824       : SDNode(Opcode, Order, dl, VTs), Size(Size), Offset(Offset) {}
1825 public:
1826   int64_t getFrameIndex() const {
1827     return cast<FrameIndexSDNode>(getOperand(1))->getIndex();
1828   }
1829 
1830   bool hasOffset() const { return Offset >= 0; }
1831   int64_t getOffset() const {
1832     assert(hasOffset() && "offset is unknown");
1833     return Offset;
1834   }
1835   int64_t getSize() const {
1836     assert(hasOffset() && "offset is unknown");
1837     return Size;
1838   }
1839 
1840   // Methods to support isa and dyn_cast
1841   static bool classof(const SDNode *N) {
1842     return N->getOpcode() == ISD::LIFETIME_START ||
1843            N->getOpcode() == ISD::LIFETIME_END;
1844   }
1845 };
1846 
1847 /// This SDNode is used for PSEUDO_PROBE values, which are the function guid and
1848 /// the index of the basic block being probed. A pseudo probe serves as a place
1849 /// holder and will be removed at the end of compilation. It does not have any
1850 /// operand because we do not want the instruction selection to deal with any.
1851 class PseudoProbeSDNode : public SDNode {
1852   friend class SelectionDAG;
1853   uint64_t Guid;
1854   uint64_t Index;
1855   uint32_t Attributes;
1856 
1857   PseudoProbeSDNode(unsigned Opcode, unsigned Order, const DebugLoc &Dl,
1858                     SDVTList VTs, uint64_t Guid, uint64_t Index, uint32_t Attr)
1859       : SDNode(Opcode, Order, Dl, VTs), Guid(Guid), Index(Index),
1860         Attributes(Attr) {}
1861 
1862 public:
1863   uint64_t getGuid() const { return Guid; }
1864   uint64_t getIndex() const { return Index; }
1865   uint32_t getAttributes() const { return Attributes; }
1866 
1867   // Methods to support isa and dyn_cast
1868   static bool classof(const SDNode *N) {
1869     return N->getOpcode() == ISD::PSEUDO_PROBE;
1870   }
1871 };
1872 
1873 class JumpTableSDNode : public SDNode {
1874   friend class SelectionDAG;
1875 
1876   int JTI;
1877   unsigned TargetFlags;
1878 
1879   JumpTableSDNode(int jti, EVT VT, bool isTarg, unsigned TF)
1880     : SDNode(isTarg ? ISD::TargetJumpTable : ISD::JumpTable,
1881       0, DebugLoc(), getSDVTList(VT)), JTI(jti), TargetFlags(TF) {
1882   }
1883 
1884 public:
1885   int getIndex() const { return JTI; }
1886   unsigned getTargetFlags() const { return TargetFlags; }
1887 
1888   static bool classof(const SDNode *N) {
1889     return N->getOpcode() == ISD::JumpTable ||
1890            N->getOpcode() == ISD::TargetJumpTable;
1891   }
1892 };
1893 
1894 class ConstantPoolSDNode : public SDNode {
1895   friend class SelectionDAG;
1896 
1897   union {
1898     const Constant *ConstVal;
1899     MachineConstantPoolValue *MachineCPVal;
1900   } Val;
1901   int Offset;  // It's a MachineConstantPoolValue if top bit is set.
1902   Align Alignment; // Minimum alignment requirement of CP.
1903   unsigned TargetFlags;
1904 
1905   ConstantPoolSDNode(bool isTarget, const Constant *c, EVT VT, int o,
1906                      Align Alignment, unsigned TF)
1907       : SDNode(isTarget ? ISD::TargetConstantPool : ISD::ConstantPool, 0,
1908                DebugLoc(), getSDVTList(VT)),
1909         Offset(o), Alignment(Alignment), TargetFlags(TF) {
1910     assert(Offset >= 0 && "Offset is too large");
1911     Val.ConstVal = c;
1912   }
1913 
1914   ConstantPoolSDNode(bool isTarget, MachineConstantPoolValue *v, EVT VT, int o,
1915                      Align Alignment, unsigned TF)
1916       : SDNode(isTarget ? ISD::TargetConstantPool : ISD::ConstantPool, 0,
1917                DebugLoc(), getSDVTList(VT)),
1918         Offset(o), Alignment(Alignment), TargetFlags(TF) {
1919     assert(Offset >= 0 && "Offset is too large");
1920     Val.MachineCPVal = v;
1921     Offset |= 1 << (sizeof(unsigned)*CHAR_BIT-1);
1922   }
1923 
1924 public:
1925   bool isMachineConstantPoolEntry() const {
1926     return Offset < 0;
1927   }
1928 
1929   const Constant *getConstVal() const {
1930     assert(!isMachineConstantPoolEntry() && "Wrong constantpool type");
1931     return Val.ConstVal;
1932   }
1933 
1934   MachineConstantPoolValue *getMachineCPVal() const {
1935     assert(isMachineConstantPoolEntry() && "Wrong constantpool type");
1936     return Val.MachineCPVal;
1937   }
1938 
1939   int getOffset() const {
1940     return Offset & ~(1 << (sizeof(unsigned)*CHAR_BIT-1));
1941   }
1942 
1943   // Return the alignment of this constant pool object, which is either 0 (for
1944   // default alignment) or the desired value.
1945   Align getAlign() const { return Alignment; }
1946   unsigned getTargetFlags() const { return TargetFlags; }
1947 
1948   Type *getType() const;
1949 
1950   static bool classof(const SDNode *N) {
1951     return N->getOpcode() == ISD::ConstantPool ||
1952            N->getOpcode() == ISD::TargetConstantPool;
1953   }
1954 };
1955 
1956 /// Completely target-dependent object reference.
1957 class TargetIndexSDNode : public SDNode {
1958   friend class SelectionDAG;
1959 
1960   unsigned TargetFlags;
1961   int Index;
1962   int64_t Offset;
1963 
1964 public:
1965   TargetIndexSDNode(int Idx, EVT VT, int64_t Ofs, unsigned TF)
1966       : SDNode(ISD::TargetIndex, 0, DebugLoc(), getSDVTList(VT)),
1967         TargetFlags(TF), Index(Idx), Offset(Ofs) {}
1968 
1969   unsigned getTargetFlags() const { return TargetFlags; }
1970   int getIndex() const { return Index; }
1971   int64_t getOffset() const { return Offset; }
1972 
1973   static bool classof(const SDNode *N) {
1974     return N->getOpcode() == ISD::TargetIndex;
1975   }
1976 };
1977 
1978 class BasicBlockSDNode : public SDNode {
1979   friend class SelectionDAG;
1980 
1981   MachineBasicBlock *MBB;
1982 
1983   /// Debug info is meaningful and potentially useful here, but we create
1984   /// blocks out of order when they're jumped to, which makes it a bit
1985   /// harder.  Let's see if we need it first.
1986   explicit BasicBlockSDNode(MachineBasicBlock *mbb)
1987     : SDNode(ISD::BasicBlock, 0, DebugLoc(), getSDVTList(MVT::Other)), MBB(mbb)
1988   {}
1989 
1990 public:
1991   MachineBasicBlock *getBasicBlock() const { return MBB; }
1992 
1993   static bool classof(const SDNode *N) {
1994     return N->getOpcode() == ISD::BasicBlock;
1995   }
1996 };
1997 
1998 /// A "pseudo-class" with methods for operating on BUILD_VECTORs.
1999 class BuildVectorSDNode : public SDNode {
2000 public:
2001   // These are constructed as SDNodes and then cast to BuildVectorSDNodes.
2002   explicit BuildVectorSDNode() = delete;
2003 
2004   /// Check if this is a constant splat, and if so, find the
2005   /// smallest element size that splats the vector.  If MinSplatBits is
2006   /// nonzero, the element size must be at least that large.  Note that the
2007   /// splat element may be the entire vector (i.e., a one element vector).
2008   /// Returns the splat element value in SplatValue.  Any undefined bits in
2009   /// that value are zero, and the corresponding bits in the SplatUndef mask
2010   /// are set.  The SplatBitSize value is set to the splat element size in
2011   /// bits.  HasAnyUndefs is set to true if any bits in the vector are
2012   /// undefined.  isBigEndian describes the endianness of the target.
2013   bool isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
2014                        unsigned &SplatBitSize, bool &HasAnyUndefs,
2015                        unsigned MinSplatBits = 0,
2016                        bool isBigEndian = false) const;
2017 
2018   /// Returns the demanded splatted value or a null value if this is not a
2019   /// splat.
2020   ///
2021   /// The DemandedElts mask indicates the elements that must be in the splat.
2022   /// If passed a non-null UndefElements bitvector, it will resize it to match
2023   /// the vector width and set the bits where elements are undef.
2024   SDValue getSplatValue(const APInt &DemandedElts,
2025                         BitVector *UndefElements = nullptr) const;
2026 
2027   /// Returns the splatted value or a null value if this is not a splat.
2028   ///
2029   /// If passed a non-null UndefElements bitvector, it will resize it to match
2030   /// the vector width and set the bits where elements are undef.
2031   SDValue getSplatValue(BitVector *UndefElements = nullptr) const;
2032 
2033   /// Find the shortest repeating sequence of values in the build vector.
2034   ///
2035   /// e.g. { u, X, u, X, u, u, X, u } -> { X }
2036   ///      { X, Y, u, Y, u, u, X, u } -> { X, Y }
2037   ///
2038   /// Currently this must be a power-of-2 build vector.
2039   /// The DemandedElts mask indicates the elements that must be present,
2040   /// undemanded elements in Sequence may be null (SDValue()). If passed a
2041   /// non-null UndefElements bitvector, it will resize it to match the original
2042   /// vector width and set the bits where elements are undef. If result is
2043   /// false, Sequence will be empty.
2044   bool getRepeatedSequence(const APInt &DemandedElts,
2045                            SmallVectorImpl<SDValue> &Sequence,
2046                            BitVector *UndefElements = nullptr) const;
2047 
2048   /// Find the shortest repeating sequence of values in the build vector.
2049   ///
2050   /// e.g. { u, X, u, X, u, u, X, u } -> { X }
2051   ///      { X, Y, u, Y, u, u, X, u } -> { X, Y }
2052   ///
2053   /// Currently this must be a power-of-2 build vector.
2054   /// If passed a non-null UndefElements bitvector, it will resize it to match
2055   /// the original vector width and set the bits where elements are undef.
2056   /// If result is false, Sequence will be empty.
2057   bool getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
2058                            BitVector *UndefElements = nullptr) const;
2059 
2060   /// Returns the demanded splatted constant or null if this is not a constant
2061   /// splat.
2062   ///
2063   /// The DemandedElts mask indicates the elements that must be in the splat.
2064   /// If passed a non-null UndefElements bitvector, it will resize it to match
2065   /// the vector width and set the bits where elements are undef.
2066   ConstantSDNode *
2067   getConstantSplatNode(const APInt &DemandedElts,
2068                        BitVector *UndefElements = nullptr) const;
2069 
2070   /// Returns the splatted constant or null if this is not a constant
2071   /// splat.
2072   ///
2073   /// If passed a non-null UndefElements bitvector, it will resize it to match
2074   /// the vector width and set the bits where elements are undef.
2075   ConstantSDNode *
2076   getConstantSplatNode(BitVector *UndefElements = nullptr) const;
2077 
2078   /// Returns the demanded splatted constant FP or null if this is not a
2079   /// constant FP splat.
2080   ///
2081   /// The DemandedElts mask indicates the elements that must be in the splat.
2082   /// If passed a non-null UndefElements bitvector, it will resize it to match
2083   /// the vector width and set the bits where elements are undef.
2084   ConstantFPSDNode *
2085   getConstantFPSplatNode(const APInt &DemandedElts,
2086                          BitVector *UndefElements = nullptr) const;
2087 
2088   /// Returns the splatted constant FP or null if this is not a constant
2089   /// FP splat.
2090   ///
2091   /// If passed a non-null UndefElements bitvector, it will resize it to match
2092   /// the vector width and set the bits where elements are undef.
2093   ConstantFPSDNode *
2094   getConstantFPSplatNode(BitVector *UndefElements = nullptr) const;
2095 
2096   /// If this is a constant FP splat and the splatted constant FP is an
2097   /// exact power or 2, return the log base 2 integer value.  Otherwise,
2098   /// return -1.
2099   ///
2100   /// The BitWidth specifies the necessary bit precision.
2101   int32_t getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
2102                                           uint32_t BitWidth) const;
2103 
2104   /// Extract the raw bit data from a build vector of Undef, Constant or
2105   /// ConstantFP node elements. Each raw bit element will be \p
2106   /// DstEltSizeInBits wide, undef elements are treated as zero, and entirely
2107   /// undefined elements are flagged in \p UndefElements.
2108   bool getConstantRawBits(bool IsLittleEndian, unsigned DstEltSizeInBits,
2109                           SmallVectorImpl<APInt> &RawBitElements,
2110                           BitVector &UndefElements) const;
2111 
2112   bool isConstant() const;
2113 
2114   /// If this BuildVector is constant and represents the numerical series
2115   /// "<a, a+n, a+2n, a+3n, ...>" where a is integer and n is a non-zero integer,
2116   /// the value "<a,n>" is returned.
2117   std::optional<std::pair<APInt, APInt>> isConstantSequence() const;
2118 
2119   /// Recast bit data \p SrcBitElements to \p DstEltSizeInBits wide elements.
2120   /// Undef elements are treated as zero, and entirely undefined elements are
2121   /// flagged in \p DstUndefElements.
2122   static void recastRawBits(bool IsLittleEndian, unsigned DstEltSizeInBits,
2123                             SmallVectorImpl<APInt> &DstBitElements,
2124                             ArrayRef<APInt> SrcBitElements,
2125                             BitVector &DstUndefElements,
2126                             const BitVector &SrcUndefElements);
2127 
2128   static bool classof(const SDNode *N) {
2129     return N->getOpcode() == ISD::BUILD_VECTOR;
2130   }
2131 };
2132 
2133 /// An SDNode that holds an arbitrary LLVM IR Value. This is
2134 /// used when the SelectionDAG needs to make a simple reference to something
2135 /// in the LLVM IR representation.
2136 ///
2137 class SrcValueSDNode : public SDNode {
2138   friend class SelectionDAG;
2139 
2140   const Value *V;
2141 
2142   /// Create a SrcValue for a general value.
2143   explicit SrcValueSDNode(const Value *v)
2144     : SDNode(ISD::SRCVALUE, 0, DebugLoc(), getSDVTList(MVT::Other)), V(v) {}
2145 
2146 public:
2147   /// Return the contained Value.
2148   const Value *getValue() const { return V; }
2149 
2150   static bool classof(const SDNode *N) {
2151     return N->getOpcode() == ISD::SRCVALUE;
2152   }
2153 };
2154 
2155 class MDNodeSDNode : public SDNode {
2156   friend class SelectionDAG;
2157 
2158   const MDNode *MD;
2159 
2160   explicit MDNodeSDNode(const MDNode *md)
2161   : SDNode(ISD::MDNODE_SDNODE, 0, DebugLoc(), getSDVTList(MVT::Other)), MD(md)
2162   {}
2163 
2164 public:
2165   const MDNode *getMD() const { return MD; }
2166 
2167   static bool classof(const SDNode *N) {
2168     return N->getOpcode() == ISD::MDNODE_SDNODE;
2169   }
2170 };
2171 
2172 class RegisterSDNode : public SDNode {
2173   friend class SelectionDAG;
2174 
2175   Register Reg;
2176 
2177   RegisterSDNode(Register reg, EVT VT)
2178     : SDNode(ISD::Register, 0, DebugLoc(), getSDVTList(VT)), Reg(reg) {}
2179 
2180 public:
2181   Register getReg() const { return Reg; }
2182 
2183   static bool classof(const SDNode *N) {
2184     return N->getOpcode() == ISD::Register;
2185   }
2186 };
2187 
2188 class RegisterMaskSDNode : public SDNode {
2189   friend class SelectionDAG;
2190 
2191   // The memory for RegMask is not owned by the node.
2192   const uint32_t *RegMask;
2193 
2194   RegisterMaskSDNode(const uint32_t *mask)
2195     : SDNode(ISD::RegisterMask, 0, DebugLoc(), getSDVTList(MVT::Untyped)),
2196       RegMask(mask) {}
2197 
2198 public:
2199   const uint32_t *getRegMask() const { return RegMask; }
2200 
2201   static bool classof(const SDNode *N) {
2202     return N->getOpcode() == ISD::RegisterMask;
2203   }
2204 };
2205 
2206 class BlockAddressSDNode : public SDNode {
2207   friend class SelectionDAG;
2208 
2209   const BlockAddress *BA;
2210   int64_t Offset;
2211   unsigned TargetFlags;
2212 
2213   BlockAddressSDNode(unsigned NodeTy, EVT VT, const BlockAddress *ba,
2214                      int64_t o, unsigned Flags)
2215     : SDNode(NodeTy, 0, DebugLoc(), getSDVTList(VT)),
2216              BA(ba), Offset(o), TargetFlags(Flags) {}
2217 
2218 public:
2219   const BlockAddress *getBlockAddress() const { return BA; }
2220   int64_t getOffset() const { return Offset; }
2221   unsigned getTargetFlags() const { return TargetFlags; }
2222 
2223   static bool classof(const SDNode *N) {
2224     return N->getOpcode() == ISD::BlockAddress ||
2225            N->getOpcode() == ISD::TargetBlockAddress;
2226   }
2227 };
2228 
2229 class LabelSDNode : public SDNode {
2230   friend class SelectionDAG;
2231 
2232   MCSymbol *Label;
2233 
2234   LabelSDNode(unsigned Opcode, unsigned Order, const DebugLoc &dl, MCSymbol *L)
2235       : SDNode(Opcode, Order, dl, getSDVTList(MVT::Other)), Label(L) {
2236     assert(LabelSDNode::classof(this) && "not a label opcode");
2237   }
2238 
2239 public:
2240   MCSymbol *getLabel() const { return Label; }
2241 
2242   static bool classof(const SDNode *N) {
2243     return N->getOpcode() == ISD::EH_LABEL ||
2244            N->getOpcode() == ISD::ANNOTATION_LABEL;
2245   }
2246 };
2247 
2248 class ExternalSymbolSDNode : public SDNode {
2249   friend class SelectionDAG;
2250 
2251   const char *Symbol;
2252   unsigned TargetFlags;
2253 
2254   ExternalSymbolSDNode(bool isTarget, const char *Sym, unsigned TF, EVT VT)
2255       : SDNode(isTarget ? ISD::TargetExternalSymbol : ISD::ExternalSymbol, 0,
2256                DebugLoc(), getSDVTList(VT)),
2257         Symbol(Sym), TargetFlags(TF) {}
2258 
2259 public:
2260   const char *getSymbol() const { return Symbol; }
2261   unsigned getTargetFlags() const { return TargetFlags; }
2262 
2263   static bool classof(const SDNode *N) {
2264     return N->getOpcode() == ISD::ExternalSymbol ||
2265            N->getOpcode() == ISD::TargetExternalSymbol;
2266   }
2267 };
2268 
2269 class MCSymbolSDNode : public SDNode {
2270   friend class SelectionDAG;
2271 
2272   MCSymbol *Symbol;
2273 
2274   MCSymbolSDNode(MCSymbol *Symbol, EVT VT)
2275       : SDNode(ISD::MCSymbol, 0, DebugLoc(), getSDVTList(VT)), Symbol(Symbol) {}
2276 
2277 public:
2278   MCSymbol *getMCSymbol() const { return Symbol; }
2279 
2280   static bool classof(const SDNode *N) {
2281     return N->getOpcode() == ISD::MCSymbol;
2282   }
2283 };
2284 
2285 class CondCodeSDNode : public SDNode {
2286   friend class SelectionDAG;
2287 
2288   ISD::CondCode Condition;
2289 
2290   explicit CondCodeSDNode(ISD::CondCode Cond)
2291     : SDNode(ISD::CONDCODE, 0, DebugLoc(), getSDVTList(MVT::Other)),
2292       Condition(Cond) {}
2293 
2294 public:
2295   ISD::CondCode get() const { return Condition; }
2296 
2297   static bool classof(const SDNode *N) {
2298     return N->getOpcode() == ISD::CONDCODE;
2299   }
2300 };
2301 
2302 /// This class is used to represent EVT's, which are used
2303 /// to parameterize some operations.
2304 class VTSDNode : public SDNode {
2305   friend class SelectionDAG;
2306 
2307   EVT ValueType;
2308 
2309   explicit VTSDNode(EVT VT)
2310     : SDNode(ISD::VALUETYPE, 0, DebugLoc(), getSDVTList(MVT::Other)),
2311       ValueType(VT) {}
2312 
2313 public:
2314   EVT getVT() const { return ValueType; }
2315 
2316   static bool classof(const SDNode *N) {
2317     return N->getOpcode() == ISD::VALUETYPE;
2318   }
2319 };
2320 
2321 /// Base class for LoadSDNode and StoreSDNode
2322 class LSBaseSDNode : public MemSDNode {
2323 public:
2324   LSBaseSDNode(ISD::NodeType NodeTy, unsigned Order, const DebugLoc &dl,
2325                SDVTList VTs, ISD::MemIndexedMode AM, EVT MemVT,
2326                MachineMemOperand *MMO)
2327       : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2328     LSBaseSDNodeBits.AddressingMode = AM;
2329     assert(getAddressingMode() == AM && "Value truncated");
2330   }
2331 
2332   const SDValue &getOffset() const {
2333     return getOperand(getOpcode() == ISD::LOAD ? 2 : 3);
2334   }
2335 
2336   /// Return the addressing mode for this load or store:
2337   /// unindexed, pre-inc, pre-dec, post-inc, or post-dec.
2338   ISD::MemIndexedMode getAddressingMode() const {
2339     return static_cast<ISD::MemIndexedMode>(LSBaseSDNodeBits.AddressingMode);
2340   }
2341 
2342   /// Return true if this is a pre/post inc/dec load/store.
2343   bool isIndexed() const { return getAddressingMode() != ISD::UNINDEXED; }
2344 
2345   /// Return true if this is NOT a pre/post inc/dec load/store.
2346   bool isUnindexed() const { return getAddressingMode() == ISD::UNINDEXED; }
2347 
2348   static bool classof(const SDNode *N) {
2349     return N->getOpcode() == ISD::LOAD ||
2350            N->getOpcode() == ISD::STORE;
2351   }
2352 };
2353 
2354 /// This class is used to represent ISD::LOAD nodes.
2355 class LoadSDNode : public LSBaseSDNode {
2356   friend class SelectionDAG;
2357 
2358   LoadSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2359              ISD::MemIndexedMode AM, ISD::LoadExtType ETy, EVT MemVT,
2360              MachineMemOperand *MMO)
2361       : LSBaseSDNode(ISD::LOAD, Order, dl, VTs, AM, MemVT, MMO) {
2362     LoadSDNodeBits.ExtTy = ETy;
2363     assert(readMem() && "Load MachineMemOperand is not a load!");
2364     assert(!writeMem() && "Load MachineMemOperand is a store!");
2365   }
2366 
2367 public:
2368   /// Return whether this is a plain node,
2369   /// or one of the varieties of value-extending loads.
2370   ISD::LoadExtType getExtensionType() const {
2371     return static_cast<ISD::LoadExtType>(LoadSDNodeBits.ExtTy);
2372   }
2373 
2374   const SDValue &getBasePtr() const { return getOperand(1); }
2375   const SDValue &getOffset() const { return getOperand(2); }
2376 
2377   static bool classof(const SDNode *N) {
2378     return N->getOpcode() == ISD::LOAD;
2379   }
2380 };
2381 
2382 /// This class is used to represent ISD::STORE nodes.
2383 class StoreSDNode : public LSBaseSDNode {
2384   friend class SelectionDAG;
2385 
2386   StoreSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2387               ISD::MemIndexedMode AM, bool isTrunc, EVT MemVT,
2388               MachineMemOperand *MMO)
2389       : LSBaseSDNode(ISD::STORE, Order, dl, VTs, AM, MemVT, MMO) {
2390     StoreSDNodeBits.IsTruncating = isTrunc;
2391     assert(!readMem() && "Store MachineMemOperand is a load!");
2392     assert(writeMem() && "Store MachineMemOperand is not a store!");
2393   }
2394 
2395 public:
2396   /// Return true if the op does a truncation before store.
2397   /// For integers this is the same as doing a TRUNCATE and storing the result.
2398   /// For floats, it is the same as doing an FP_ROUND and storing the result.
2399   bool isTruncatingStore() const { return StoreSDNodeBits.IsTruncating; }
2400   void setTruncatingStore(bool Truncating) {
2401     StoreSDNodeBits.IsTruncating = Truncating;
2402   }
2403 
2404   const SDValue &getValue() const { return getOperand(1); }
2405   const SDValue &getBasePtr() const { return getOperand(2); }
2406   const SDValue &getOffset() const { return getOperand(3); }
2407 
2408   static bool classof(const SDNode *N) {
2409     return N->getOpcode() == ISD::STORE;
2410   }
2411 };
2412 
2413 /// This base class is used to represent VP_LOAD, VP_STORE,
2414 /// EXPERIMENTAL_VP_STRIDED_LOAD and EXPERIMENTAL_VP_STRIDED_STORE nodes
2415 class VPBaseLoadStoreSDNode : public MemSDNode {
2416 public:
2417   friend class SelectionDAG;
2418 
2419   VPBaseLoadStoreSDNode(ISD::NodeType NodeTy, unsigned Order,
2420                         const DebugLoc &DL, SDVTList VTs,
2421                         ISD::MemIndexedMode AM, EVT MemVT,
2422                         MachineMemOperand *MMO)
2423       : MemSDNode(NodeTy, Order, DL, VTs, MemVT, MMO) {
2424     LSBaseSDNodeBits.AddressingMode = AM;
2425     assert(getAddressingMode() == AM && "Value truncated");
2426   }
2427 
2428   // VPStridedStoreSDNode (Chain, Data, Ptr,    Offset, Stride, Mask, EVL)
2429   // VPStoreSDNode        (Chain, Data, Ptr,    Offset, Mask,   EVL)
2430   // VPStridedLoadSDNode  (Chain, Ptr,  Offset, Stride, Mask,   EVL)
2431   // VPLoadSDNode         (Chain, Ptr,  Offset, Mask,   EVL)
2432   // Mask is a vector of i1 elements;
2433   // the type of EVL is TLI.getVPExplicitVectorLengthTy().
2434   const SDValue &getOffset() const {
2435     return getOperand((getOpcode() == ISD::EXPERIMENTAL_VP_STRIDED_LOAD ||
2436                        getOpcode() == ISD::VP_LOAD)
2437                           ? 2
2438                           : 3);
2439   }
2440   const SDValue &getBasePtr() const {
2441     return getOperand((getOpcode() == ISD::EXPERIMENTAL_VP_STRIDED_LOAD ||
2442                        getOpcode() == ISD::VP_LOAD)
2443                           ? 1
2444                           : 2);
2445   }
2446   const SDValue &getMask() const {
2447     switch (getOpcode()) {
2448     default:
2449       llvm_unreachable("Invalid opcode");
2450     case ISD::VP_LOAD:
2451       return getOperand(3);
2452     case ISD::VP_STORE:
2453     case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
2454       return getOperand(4);
2455     case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
2456       return getOperand(5);
2457     }
2458   }
2459   const SDValue &getVectorLength() const {
2460     switch (getOpcode()) {
2461     default:
2462       llvm_unreachable("Invalid opcode");
2463     case ISD::VP_LOAD:
2464       return getOperand(4);
2465     case ISD::VP_STORE:
2466     case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
2467       return getOperand(5);
2468     case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
2469       return getOperand(6);
2470     }
2471   }
2472 
2473   /// Return the addressing mode for this load or store:
2474   /// unindexed, pre-inc, pre-dec, post-inc, or post-dec.
2475   ISD::MemIndexedMode getAddressingMode() const {
2476     return static_cast<ISD::MemIndexedMode>(LSBaseSDNodeBits.AddressingMode);
2477   }
2478 
2479   /// Return true if this is a pre/post inc/dec load/store.
2480   bool isIndexed() const { return getAddressingMode() != ISD::UNINDEXED; }
2481 
2482   /// Return true if this is NOT a pre/post inc/dec load/store.
2483   bool isUnindexed() const { return getAddressingMode() == ISD::UNINDEXED; }
2484 
2485   static bool classof(const SDNode *N) {
2486     return N->getOpcode() == ISD::EXPERIMENTAL_VP_STRIDED_LOAD ||
2487            N->getOpcode() == ISD::EXPERIMENTAL_VP_STRIDED_STORE ||
2488            N->getOpcode() == ISD::VP_LOAD || N->getOpcode() == ISD::VP_STORE;
2489   }
2490 };
2491 
2492 /// This class is used to represent a VP_LOAD node
2493 class VPLoadSDNode : public VPBaseLoadStoreSDNode {
2494 public:
2495   friend class SelectionDAG;
2496 
2497   VPLoadSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2498                ISD::MemIndexedMode AM, ISD::LoadExtType ETy, bool isExpanding,
2499                EVT MemVT, MachineMemOperand *MMO)
2500       : VPBaseLoadStoreSDNode(ISD::VP_LOAD, Order, dl, VTs, AM, MemVT, MMO) {
2501     LoadSDNodeBits.ExtTy = ETy;
2502     LoadSDNodeBits.IsExpanding = isExpanding;
2503   }
2504 
2505   ISD::LoadExtType getExtensionType() const {
2506     return static_cast<ISD::LoadExtType>(LoadSDNodeBits.ExtTy);
2507   }
2508 
2509   const SDValue &getBasePtr() const { return getOperand(1); }
2510   const SDValue &getOffset() const { return getOperand(2); }
2511   const SDValue &getMask() const { return getOperand(3); }
2512   const SDValue &getVectorLength() const { return getOperand(4); }
2513 
2514   static bool classof(const SDNode *N) {
2515     return N->getOpcode() == ISD::VP_LOAD;
2516   }
2517   bool isExpandingLoad() const { return LoadSDNodeBits.IsExpanding; }
2518 };
2519 
2520 /// This class is used to represent an EXPERIMENTAL_VP_STRIDED_LOAD node.
2521 class VPStridedLoadSDNode : public VPBaseLoadStoreSDNode {
2522 public:
2523   friend class SelectionDAG;
2524 
2525   VPStridedLoadSDNode(unsigned Order, const DebugLoc &DL, SDVTList VTs,
2526                       ISD::MemIndexedMode AM, ISD::LoadExtType ETy,
2527                       bool IsExpanding, EVT MemVT, MachineMemOperand *MMO)
2528       : VPBaseLoadStoreSDNode(ISD::EXPERIMENTAL_VP_STRIDED_LOAD, Order, DL, VTs,
2529                               AM, MemVT, MMO) {
2530     LoadSDNodeBits.ExtTy = ETy;
2531     LoadSDNodeBits.IsExpanding = IsExpanding;
2532   }
2533 
2534   ISD::LoadExtType getExtensionType() const {
2535     return static_cast<ISD::LoadExtType>(LoadSDNodeBits.ExtTy);
2536   }
2537 
2538   const SDValue &getBasePtr() const { return getOperand(1); }
2539   const SDValue &getOffset() const { return getOperand(2); }
2540   const SDValue &getStride() const { return getOperand(3); }
2541   const SDValue &getMask() const { return getOperand(4); }
2542   const SDValue &getVectorLength() const { return getOperand(5); }
2543 
2544   static bool classof(const SDNode *N) {
2545     return N->getOpcode() == ISD::EXPERIMENTAL_VP_STRIDED_LOAD;
2546   }
2547   bool isExpandingLoad() const { return LoadSDNodeBits.IsExpanding; }
2548 };
2549 
2550 /// This class is used to represent a VP_STORE node
2551 class VPStoreSDNode : public VPBaseLoadStoreSDNode {
2552 public:
2553   friend class SelectionDAG;
2554 
2555   VPStoreSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2556                 ISD::MemIndexedMode AM, bool isTrunc, bool isCompressing,
2557                 EVT MemVT, MachineMemOperand *MMO)
2558       : VPBaseLoadStoreSDNode(ISD::VP_STORE, Order, dl, VTs, AM, MemVT, MMO) {
2559     StoreSDNodeBits.IsTruncating = isTrunc;
2560     StoreSDNodeBits.IsCompressing = isCompressing;
2561   }
2562 
2563   /// Return true if this is a truncating store.
2564   /// For integers this is the same as doing a TRUNCATE and storing the result.
2565   /// For floats, it is the same as doing an FP_ROUND and storing the result.
2566   bool isTruncatingStore() const { return StoreSDNodeBits.IsTruncating; }
2567 
2568   /// Returns true if the op does a compression to the vector before storing.
2569   /// The node contiguously stores the active elements (integers or floats)
2570   /// in src (those with their respective bit set in writemask k) to unaligned
2571   /// memory at base_addr.
2572   bool isCompressingStore() const { return StoreSDNodeBits.IsCompressing; }
2573 
2574   const SDValue &getValue() const { return getOperand(1); }
2575   const SDValue &getBasePtr() const { return getOperand(2); }
2576   const SDValue &getOffset() const { return getOperand(3); }
2577   const SDValue &getMask() const { return getOperand(4); }
2578   const SDValue &getVectorLength() const { return getOperand(5); }
2579 
2580   static bool classof(const SDNode *N) {
2581     return N->getOpcode() == ISD::VP_STORE;
2582   }
2583 };
2584 
2585 /// This class is used to represent an EXPERIMENTAL_VP_STRIDED_STORE node.
2586 class VPStridedStoreSDNode : public VPBaseLoadStoreSDNode {
2587 public:
2588   friend class SelectionDAG;
2589 
2590   VPStridedStoreSDNode(unsigned Order, const DebugLoc &DL, SDVTList VTs,
2591                        ISD::MemIndexedMode AM, bool IsTrunc, bool IsCompressing,
2592                        EVT MemVT, MachineMemOperand *MMO)
2593       : VPBaseLoadStoreSDNode(ISD::EXPERIMENTAL_VP_STRIDED_STORE, Order, DL,
2594                               VTs, AM, MemVT, MMO) {
2595     StoreSDNodeBits.IsTruncating = IsTrunc;
2596     StoreSDNodeBits.IsCompressing = IsCompressing;
2597   }
2598 
2599   /// Return true if this is a truncating store.
2600   /// For integers this is the same as doing a TRUNCATE and storing the result.
2601   /// For floats, it is the same as doing an FP_ROUND and storing the result.
2602   bool isTruncatingStore() const { return StoreSDNodeBits.IsTruncating; }
2603 
2604   /// Returns true if the op does a compression to the vector before storing.
2605   /// The node contiguously stores the active elements (integers or floats)
2606   /// in src (those with their respective bit set in writemask k) to unaligned
2607   /// memory at base_addr.
2608   bool isCompressingStore() const { return StoreSDNodeBits.IsCompressing; }
2609 
2610   const SDValue &getValue() const { return getOperand(1); }
2611   const SDValue &getBasePtr() const { return getOperand(2); }
2612   const SDValue &getOffset() const { return getOperand(3); }
2613   const SDValue &getStride() const { return getOperand(4); }
2614   const SDValue &getMask() const { return getOperand(5); }
2615   const SDValue &getVectorLength() const { return getOperand(6); }
2616 
2617   static bool classof(const SDNode *N) {
2618     return N->getOpcode() == ISD::EXPERIMENTAL_VP_STRIDED_STORE;
2619   }
2620 };
2621 
2622 /// This base class is used to represent MLOAD and MSTORE nodes
2623 class MaskedLoadStoreSDNode : public MemSDNode {
2624 public:
2625   friend class SelectionDAG;
2626 
2627   MaskedLoadStoreSDNode(ISD::NodeType NodeTy, unsigned Order,
2628                         const DebugLoc &dl, SDVTList VTs,
2629                         ISD::MemIndexedMode AM, EVT MemVT,
2630                         MachineMemOperand *MMO)
2631       : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2632     LSBaseSDNodeBits.AddressingMode = AM;
2633     assert(getAddressingMode() == AM && "Value truncated");
2634   }
2635 
2636   // MaskedLoadSDNode (Chain, ptr, offset, mask, passthru)
2637   // MaskedStoreSDNode (Chain, data, ptr, offset, mask)
2638   // Mask is a vector of i1 elements
2639   const SDValue &getOffset() const {
2640     return getOperand(getOpcode() == ISD::MLOAD ? 2 : 3);
2641   }
2642   const SDValue &getMask() const {
2643     return getOperand(getOpcode() == ISD::MLOAD ? 3 : 4);
2644   }
2645 
2646   /// Return the addressing mode for this load or store:
2647   /// unindexed, pre-inc, pre-dec, post-inc, or post-dec.
2648   ISD::MemIndexedMode getAddressingMode() const {
2649     return static_cast<ISD::MemIndexedMode>(LSBaseSDNodeBits.AddressingMode);
2650   }
2651 
2652   /// Return true if this is a pre/post inc/dec load/store.
2653   bool isIndexed() const { return getAddressingMode() != ISD::UNINDEXED; }
2654 
2655   /// Return true if this is NOT a pre/post inc/dec load/store.
2656   bool isUnindexed() const { return getAddressingMode() == ISD::UNINDEXED; }
2657 
2658   static bool classof(const SDNode *N) {
2659     return N->getOpcode() == ISD::MLOAD ||
2660            N->getOpcode() == ISD::MSTORE;
2661   }
2662 };
2663 
2664 /// This class is used to represent an MLOAD node
2665 class MaskedLoadSDNode : public MaskedLoadStoreSDNode {
2666 public:
2667   friend class SelectionDAG;
2668 
2669   MaskedLoadSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2670                    ISD::MemIndexedMode AM, ISD::LoadExtType ETy,
2671                    bool IsExpanding, EVT MemVT, MachineMemOperand *MMO)
2672       : MaskedLoadStoreSDNode(ISD::MLOAD, Order, dl, VTs, AM, MemVT, MMO) {
2673     LoadSDNodeBits.ExtTy = ETy;
2674     LoadSDNodeBits.IsExpanding = IsExpanding;
2675   }
2676 
2677   ISD::LoadExtType getExtensionType() const {
2678     return static_cast<ISD::LoadExtType>(LoadSDNodeBits.ExtTy);
2679   }
2680 
2681   const SDValue &getBasePtr() const { return getOperand(1); }
2682   const SDValue &getOffset() const { return getOperand(2); }
2683   const SDValue &getMask() const { return getOperand(3); }
2684   const SDValue &getPassThru() const { return getOperand(4); }
2685 
2686   static bool classof(const SDNode *N) {
2687     return N->getOpcode() == ISD::MLOAD;
2688   }
2689 
2690   bool isExpandingLoad() const { return LoadSDNodeBits.IsExpanding; }
2691 };
2692 
2693 /// This class is used to represent an MSTORE node
2694 class MaskedStoreSDNode : public MaskedLoadStoreSDNode {
2695 public:
2696   friend class SelectionDAG;
2697 
2698   MaskedStoreSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2699                     ISD::MemIndexedMode AM, bool isTrunc, bool isCompressing,
2700                     EVT MemVT, MachineMemOperand *MMO)
2701       : MaskedLoadStoreSDNode(ISD::MSTORE, Order, dl, VTs, AM, MemVT, MMO) {
2702     StoreSDNodeBits.IsTruncating = isTrunc;
2703     StoreSDNodeBits.IsCompressing = isCompressing;
2704   }
2705 
2706   /// Return true if the op does a truncation before store.
2707   /// For integers this is the same as doing a TRUNCATE and storing the result.
2708   /// For floats, it is the same as doing an FP_ROUND and storing the result.
2709   bool isTruncatingStore() const { return StoreSDNodeBits.IsTruncating; }
2710 
2711   /// Returns true if the op does a compression to the vector before storing.
2712   /// The node contiguously stores the active elements (integers or floats)
2713   /// in src (those with their respective bit set in writemask k) to unaligned
2714   /// memory at base_addr.
2715   bool isCompressingStore() const { return StoreSDNodeBits.IsCompressing; }
2716 
2717   const SDValue &getValue() const { return getOperand(1); }
2718   const SDValue &getBasePtr() const { return getOperand(2); }
2719   const SDValue &getOffset() const { return getOperand(3); }
2720   const SDValue &getMask() const { return getOperand(4); }
2721 
2722   static bool classof(const SDNode *N) {
2723     return N->getOpcode() == ISD::MSTORE;
2724   }
2725 };
2726 
2727 /// This is a base class used to represent
2728 /// VP_GATHER and VP_SCATTER nodes
2729 ///
2730 class VPGatherScatterSDNode : public MemSDNode {
2731 public:
2732   friend class SelectionDAG;
2733 
2734   VPGatherScatterSDNode(ISD::NodeType NodeTy, unsigned Order,
2735                         const DebugLoc &dl, SDVTList VTs, EVT MemVT,
2736                         MachineMemOperand *MMO, ISD::MemIndexType IndexType)
2737       : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2738     LSBaseSDNodeBits.AddressingMode = IndexType;
2739     assert(getIndexType() == IndexType && "Value truncated");
2740   }
2741 
2742   /// How is Index applied to BasePtr when computing addresses.
2743   ISD::MemIndexType getIndexType() const {
2744     return static_cast<ISD::MemIndexType>(LSBaseSDNodeBits.AddressingMode);
2745   }
2746   bool isIndexScaled() const {
2747     return !cast<ConstantSDNode>(getScale())->isOne();
2748   }
2749   bool isIndexSigned() const { return isIndexTypeSigned(getIndexType()); }
2750 
2751   // In the both nodes address is Op1, mask is Op2:
2752   // VPGatherSDNode  (Chain, base, index, scale, mask, vlen)
2753   // VPScatterSDNode (Chain, value, base, index, scale, mask, vlen)
2754   // Mask is a vector of i1 elements
2755   const SDValue &getBasePtr() const {
2756     return getOperand((getOpcode() == ISD::VP_GATHER) ? 1 : 2);
2757   }
2758   const SDValue &getIndex() const {
2759     return getOperand((getOpcode() == ISD::VP_GATHER) ? 2 : 3);
2760   }
2761   const SDValue &getScale() const {
2762     return getOperand((getOpcode() == ISD::VP_GATHER) ? 3 : 4);
2763   }
2764   const SDValue &getMask() const {
2765     return getOperand((getOpcode() == ISD::VP_GATHER) ? 4 : 5);
2766   }
2767   const SDValue &getVectorLength() const {
2768     return getOperand((getOpcode() == ISD::VP_GATHER) ? 5 : 6);
2769   }
2770 
2771   static bool classof(const SDNode *N) {
2772     return N->getOpcode() == ISD::VP_GATHER ||
2773            N->getOpcode() == ISD::VP_SCATTER;
2774   }
2775 };
2776 
2777 /// This class is used to represent an VP_GATHER node
2778 ///
2779 class VPGatherSDNode : public VPGatherScatterSDNode {
2780 public:
2781   friend class SelectionDAG;
2782 
2783   VPGatherSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs, EVT MemVT,
2784                  MachineMemOperand *MMO, ISD::MemIndexType IndexType)
2785       : VPGatherScatterSDNode(ISD::VP_GATHER, Order, dl, VTs, MemVT, MMO,
2786                               IndexType) {}
2787 
2788   static bool classof(const SDNode *N) {
2789     return N->getOpcode() == ISD::VP_GATHER;
2790   }
2791 };
2792 
2793 /// This class is used to represent an VP_SCATTER node
2794 ///
2795 class VPScatterSDNode : public VPGatherScatterSDNode {
2796 public:
2797   friend class SelectionDAG;
2798 
2799   VPScatterSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs, EVT MemVT,
2800                   MachineMemOperand *MMO, ISD::MemIndexType IndexType)
2801       : VPGatherScatterSDNode(ISD::VP_SCATTER, Order, dl, VTs, MemVT, MMO,
2802                               IndexType) {}
2803 
2804   const SDValue &getValue() const { return getOperand(1); }
2805 
2806   static bool classof(const SDNode *N) {
2807     return N->getOpcode() == ISD::VP_SCATTER;
2808   }
2809 };
2810 
2811 /// This is a base class used to represent
2812 /// MGATHER and MSCATTER nodes
2813 ///
2814 class MaskedGatherScatterSDNode : public MemSDNode {
2815 public:
2816   friend class SelectionDAG;
2817 
2818   MaskedGatherScatterSDNode(ISD::NodeType NodeTy, unsigned Order,
2819                             const DebugLoc &dl, SDVTList VTs, EVT MemVT,
2820                             MachineMemOperand *MMO, ISD::MemIndexType IndexType)
2821       : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2822     LSBaseSDNodeBits.AddressingMode = IndexType;
2823     assert(getIndexType() == IndexType && "Value truncated");
2824   }
2825 
2826   /// How is Index applied to BasePtr when computing addresses.
2827   ISD::MemIndexType getIndexType() const {
2828     return static_cast<ISD::MemIndexType>(LSBaseSDNodeBits.AddressingMode);
2829   }
2830   bool isIndexScaled() const {
2831     return !cast<ConstantSDNode>(getScale())->isOne();
2832   }
2833   bool isIndexSigned() const { return isIndexTypeSigned(getIndexType()); }
2834 
2835   // In the both nodes address is Op1, mask is Op2:
2836   // MaskedGatherSDNode  (Chain, passthru, mask, base, index, scale)
2837   // MaskedScatterSDNode (Chain, value, mask, base, index, scale)
2838   // Mask is a vector of i1 elements
2839   const SDValue &getBasePtr() const { return getOperand(3); }
2840   const SDValue &getIndex()   const { return getOperand(4); }
2841   const SDValue &getMask()    const { return getOperand(2); }
2842   const SDValue &getScale()   const { return getOperand(5); }
2843 
2844   static bool classof(const SDNode *N) {
2845     return N->getOpcode() == ISD::MGATHER ||
2846            N->getOpcode() == ISD::MSCATTER;
2847   }
2848 };
2849 
2850 /// This class is used to represent an MGATHER node
2851 ///
2852 class MaskedGatherSDNode : public MaskedGatherScatterSDNode {
2853 public:
2854   friend class SelectionDAG;
2855 
2856   MaskedGatherSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2857                      EVT MemVT, MachineMemOperand *MMO,
2858                      ISD::MemIndexType IndexType, ISD::LoadExtType ETy)
2859       : MaskedGatherScatterSDNode(ISD::MGATHER, Order, dl, VTs, MemVT, MMO,
2860                                   IndexType) {
2861     LoadSDNodeBits.ExtTy = ETy;
2862   }
2863 
2864   const SDValue &getPassThru() const { return getOperand(1); }
2865 
2866   ISD::LoadExtType getExtensionType() const {
2867     return ISD::LoadExtType(LoadSDNodeBits.ExtTy);
2868   }
2869 
2870   static bool classof(const SDNode *N) {
2871     return N->getOpcode() == ISD::MGATHER;
2872   }
2873 };
2874 
2875 /// This class is used to represent an MSCATTER node
2876 ///
2877 class MaskedScatterSDNode : public MaskedGatherScatterSDNode {
2878 public:
2879   friend class SelectionDAG;
2880 
2881   MaskedScatterSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2882                       EVT MemVT, MachineMemOperand *MMO,
2883                       ISD::MemIndexType IndexType, bool IsTrunc)
2884       : MaskedGatherScatterSDNode(ISD::MSCATTER, Order, dl, VTs, MemVT, MMO,
2885                                   IndexType) {
2886     StoreSDNodeBits.IsTruncating = IsTrunc;
2887   }
2888 
2889   /// Return true if the op does a truncation before store.
2890   /// For integers this is the same as doing a TRUNCATE and storing the result.
2891   /// For floats, it is the same as doing an FP_ROUND and storing the result.
2892   bool isTruncatingStore() const { return StoreSDNodeBits.IsTruncating; }
2893 
2894   const SDValue &getValue() const { return getOperand(1); }
2895 
2896   static bool classof(const SDNode *N) {
2897     return N->getOpcode() == ISD::MSCATTER;
2898   }
2899 };
2900 
2901 class FPStateAccessSDNode : public MemSDNode {
2902 public:
2903   friend class SelectionDAG;
2904 
2905   FPStateAccessSDNode(unsigned NodeTy, unsigned Order, const DebugLoc &dl,
2906                       SDVTList VTs, EVT MemVT, MachineMemOperand *MMO)
2907       : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2908     assert((NodeTy == ISD::GET_FPENV_MEM || NodeTy == ISD::SET_FPENV_MEM) &&
2909            "Expected FP state access node");
2910   }
2911 
2912   static bool classof(const SDNode *N) {
2913     return N->getOpcode() == ISD::GET_FPENV_MEM ||
2914            N->getOpcode() == ISD::SET_FPENV_MEM;
2915   }
2916 };
2917 
2918 /// An SDNode that represents everything that will be needed
2919 /// to construct a MachineInstr. These nodes are created during the
2920 /// instruction selection proper phase.
2921 ///
2922 /// Note that the only supported way to set the `memoperands` is by calling the
2923 /// `SelectionDAG::setNodeMemRefs` function as the memory management happens
2924 /// inside the DAG rather than in the node.
2925 class MachineSDNode : public SDNode {
2926 private:
2927   friend class SelectionDAG;
2928 
2929   MachineSDNode(unsigned Opc, unsigned Order, const DebugLoc &DL, SDVTList VTs)
2930       : SDNode(Opc, Order, DL, VTs) {}
2931 
2932   // We use a pointer union between a single `MachineMemOperand` pointer and
2933   // a pointer to an array of `MachineMemOperand` pointers. This is null when
2934   // the number of these is zero, the single pointer variant used when the
2935   // number is one, and the array is used for larger numbers.
2936   //
2937   // The array is allocated via the `SelectionDAG`'s allocator and so will
2938   // always live until the DAG is cleaned up and doesn't require ownership here.
2939   //
2940   // We can't use something simpler like `TinyPtrVector` here because `SDNode`
2941   // subclasses aren't managed in a conforming C++ manner. See the comments on
2942   // `SelectionDAG::MorphNodeTo` which details what all goes on, but the
2943   // constraint here is that these don't manage memory with their constructor or
2944   // destructor and can be initialized to a good state even if they start off
2945   // uninitialized.
2946   PointerUnion<MachineMemOperand *, MachineMemOperand **> MemRefs = {};
2947 
2948   // Note that this could be folded into the above `MemRefs` member if doing so
2949   // is advantageous at some point. We don't need to store this in most cases.
2950   // However, at the moment this doesn't appear to make the allocation any
2951   // smaller and makes the code somewhat simpler to read.
2952   int NumMemRefs = 0;
2953 
2954 public:
2955   using mmo_iterator = ArrayRef<MachineMemOperand *>::const_iterator;
2956 
2957   ArrayRef<MachineMemOperand *> memoperands() const {
2958     // Special case the common cases.
2959     if (NumMemRefs == 0)
2960       return {};
2961     if (NumMemRefs == 1)
2962       return ArrayRef(MemRefs.getAddrOfPtr1(), 1);
2963 
2964     // Otherwise we have an actual array.
2965     return ArrayRef(cast<MachineMemOperand **>(MemRefs), NumMemRefs);
2966   }
2967   mmo_iterator memoperands_begin() const { return memoperands().begin(); }
2968   mmo_iterator memoperands_end() const { return memoperands().end(); }
2969   bool memoperands_empty() const { return memoperands().empty(); }
2970 
2971   /// Clear out the memory reference descriptor list.
2972   void clearMemRefs() {
2973     MemRefs = nullptr;
2974     NumMemRefs = 0;
2975   }
2976 
2977   static bool classof(const SDNode *N) {
2978     return N->isMachineOpcode();
2979   }
2980 };
2981 
2982 /// An SDNode that records if a register contains a value that is guaranteed to
2983 /// be aligned accordingly.
2984 class AssertAlignSDNode : public SDNode {
2985   Align Alignment;
2986 
2987 public:
2988   AssertAlignSDNode(unsigned Order, const DebugLoc &DL, EVT VT, Align A)
2989       : SDNode(ISD::AssertAlign, Order, DL, getSDVTList(VT)), Alignment(A) {}
2990 
2991   Align getAlign() const { return Alignment; }
2992 
2993   static bool classof(const SDNode *N) {
2994     return N->getOpcode() == ISD::AssertAlign;
2995   }
2996 };
2997 
2998 class SDNodeIterator {
2999   const SDNode *Node;
3000   unsigned Operand;
3001 
3002   SDNodeIterator(const SDNode *N, unsigned Op) : Node(N), Operand(Op) {}
3003 
3004 public:
3005   using iterator_category = std::forward_iterator_tag;
3006   using value_type = SDNode;
3007   using difference_type = std::ptrdiff_t;
3008   using pointer = value_type *;
3009   using reference = value_type &;
3010 
3011   bool operator==(const SDNodeIterator& x) const {
3012     return Operand == x.Operand;
3013   }
3014   bool operator!=(const SDNodeIterator& x) const { return !operator==(x); }
3015 
3016   pointer operator*() const {
3017     return Node->getOperand(Operand).getNode();
3018   }
3019   pointer operator->() const { return operator*(); }
3020 
3021   SDNodeIterator& operator++() {                // Preincrement
3022     ++Operand;
3023     return *this;
3024   }
3025   SDNodeIterator operator++(int) { // Postincrement
3026     SDNodeIterator tmp = *this; ++*this; return tmp;
3027   }
3028   size_t operator-(SDNodeIterator Other) const {
3029     assert(Node == Other.Node &&
3030            "Cannot compare iterators of two different nodes!");
3031     return Operand - Other.Operand;
3032   }
3033 
3034   static SDNodeIterator begin(const SDNode *N) { return SDNodeIterator(N, 0); }
3035   static SDNodeIterator end  (const SDNode *N) {
3036     return SDNodeIterator(N, N->getNumOperands());
3037   }
3038 
3039   unsigned getOperand() const { return Operand; }
3040   const SDNode *getNode() const { return Node; }
3041 };
3042 
3043 template <> struct GraphTraits<SDNode*> {
3044   using NodeRef = SDNode *;
3045   using ChildIteratorType = SDNodeIterator;
3046 
3047   static NodeRef getEntryNode(SDNode *N) { return N; }
3048 
3049   static ChildIteratorType child_begin(NodeRef N) {
3050     return SDNodeIterator::begin(N);
3051   }
3052 
3053   static ChildIteratorType child_end(NodeRef N) {
3054     return SDNodeIterator::end(N);
3055   }
3056 };
3057 
3058 /// A representation of the largest SDNode, for use in sizeof().
3059 ///
3060 /// This needs to be a union because the largest node differs on 32 bit systems
3061 /// with 4 and 8 byte pointer alignment, respectively.
3062 using LargestSDNode = AlignedCharArrayUnion<AtomicSDNode, TargetIndexSDNode,
3063                                             BlockAddressSDNode,
3064                                             GlobalAddressSDNode,
3065                                             PseudoProbeSDNode>;
3066 
3067 /// The SDNode class with the greatest alignment requirement.
3068 using MostAlignedSDNode = GlobalAddressSDNode;
3069 
3070 namespace ISD {
3071 
3072   /// Returns true if the specified node is a non-extending and unindexed load.
3073   inline bool isNormalLoad(const SDNode *N) {
3074     const LoadSDNode *Ld = dyn_cast<LoadSDNode>(N);
3075     return Ld && Ld->getExtensionType() == ISD::NON_EXTLOAD &&
3076       Ld->getAddressingMode() == ISD::UNINDEXED;
3077   }
3078 
3079   /// Returns true if the specified node is a non-extending load.
3080   inline bool isNON_EXTLoad(const SDNode *N) {
3081     return isa<LoadSDNode>(N) &&
3082       cast<LoadSDNode>(N)->getExtensionType() == ISD::NON_EXTLOAD;
3083   }
3084 
3085   /// Returns true if the specified node is a EXTLOAD.
3086   inline bool isEXTLoad(const SDNode *N) {
3087     return isa<LoadSDNode>(N) &&
3088       cast<LoadSDNode>(N)->getExtensionType() == ISD::EXTLOAD;
3089   }
3090 
3091   /// Returns true if the specified node is a SEXTLOAD.
3092   inline bool isSEXTLoad(const SDNode *N) {
3093     return isa<LoadSDNode>(N) &&
3094       cast<LoadSDNode>(N)->getExtensionType() == ISD::SEXTLOAD;
3095   }
3096 
3097   /// Returns true if the specified node is a ZEXTLOAD.
3098   inline bool isZEXTLoad(const SDNode *N) {
3099     return isa<LoadSDNode>(N) &&
3100       cast<LoadSDNode>(N)->getExtensionType() == ISD::ZEXTLOAD;
3101   }
3102 
3103   /// Returns true if the specified node is an unindexed load.
3104   inline bool isUNINDEXEDLoad(const SDNode *N) {
3105     return isa<LoadSDNode>(N) &&
3106       cast<LoadSDNode>(N)->getAddressingMode() == ISD::UNINDEXED;
3107   }
3108 
3109   /// Returns true if the specified node is a non-truncating
3110   /// and unindexed store.
3111   inline bool isNormalStore(const SDNode *N) {
3112     const StoreSDNode *St = dyn_cast<StoreSDNode>(N);
3113     return St && !St->isTruncatingStore() &&
3114       St->getAddressingMode() == ISD::UNINDEXED;
3115   }
3116 
3117   /// Returns true if the specified node is an unindexed store.
3118   inline bool isUNINDEXEDStore(const SDNode *N) {
3119     return isa<StoreSDNode>(N) &&
3120       cast<StoreSDNode>(N)->getAddressingMode() == ISD::UNINDEXED;
3121   }
3122 
3123   /// Attempt to match a unary predicate against a scalar/splat constant or
3124   /// every element of a constant BUILD_VECTOR.
3125   /// If AllowUndef is true, then UNDEF elements will pass nullptr to Match.
3126   bool matchUnaryPredicate(SDValue Op,
3127                            std::function<bool(ConstantSDNode *)> Match,
3128                            bool AllowUndefs = false);
3129 
3130   /// Attempt to match a binary predicate against a pair of scalar/splat
3131   /// constants or every element of a pair of constant BUILD_VECTORs.
3132   /// If AllowUndef is true, then UNDEF elements will pass nullptr to Match.
3133   /// If AllowTypeMismatch is true then RetType + ArgTypes don't need to match.
3134   bool matchBinaryPredicate(
3135       SDValue LHS, SDValue RHS,
3136       std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
3137       bool AllowUndefs = false, bool AllowTypeMismatch = false);
3138 
3139   /// Returns true if the specified value is the overflow result from one
3140   /// of the overflow intrinsic nodes.
3141   inline bool isOverflowIntrOpRes(SDValue Op) {
3142     unsigned Opc = Op.getOpcode();
3143     return (Op.getResNo() == 1 &&
3144             (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3145              Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
3146   }
3147 
3148 } // end namespace ISD
3149 
3150 } // end namespace llvm
3151 
3152 #endif // LLVM_CODEGEN_SELECTIONDAGNODES_H
3153