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