]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/CodeGen/SelectionDAGNodes.h
MFV r310796, r310797:
[FreeBSD/FreeBSD.git] / contrib / llvm / include / llvm / CodeGen / SelectionDAGNodes.h
1 //===-- llvm/CodeGen/SelectionDAGNodes.h - SelectionDAG Nodes ---*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file declares the SDNode class and derived classes, which are used to
11 // represent the nodes and operations present in a SelectionDAG.  These nodes
12 // and operations are machine code level operations, with some similarities to
13 // the GCC RTL representation.
14 //
15 // Clients should include the SelectionDAG.h file instead of this file directly.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #ifndef LLVM_CODEGEN_SELECTIONDAGNODES_H
20 #define LLVM_CODEGEN_SELECTIONDAGNODES_H
21
22 #include "llvm/ADT/BitVector.h"
23 #include "llvm/ADT/FoldingSet.h"
24 #include "llvm/ADT/GraphTraits.h"
25 #include "llvm/ADT/STLExtras.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_range.h"
30 #include "llvm/CodeGen/ISDOpcodes.h"
31 #include "llvm/CodeGen/MachineMemOperand.h"
32 #include "llvm/CodeGen/ValueTypes.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DebugLoc.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/Support/DataTypes.h"
37 #include "llvm/Support/MathExtras.h"
38 #include <cassert>
39
40 namespace llvm {
41
42 class SelectionDAG;
43 class GlobalValue;
44 class MachineBasicBlock;
45 class MachineConstantPoolValue;
46 class SDNode;
47 class HandleSDNode;
48 class Value;
49 class MCSymbol;
50 template <typename T> struct DenseMapInfo;
51 template <typename T> struct simplify_type;
52 template <typename T> struct ilist_traits;
53
54 void checkForCycles(const SDNode *N, const SelectionDAG *DAG = nullptr,
55                     bool force = false);
56
57 /// This represents a list of ValueType's that has been intern'd by
58 /// a SelectionDAG.  Instances of this simple value class are returned by
59 /// SelectionDAG::getVTList(...).
60 ///
61 struct SDVTList {
62   const EVT *VTs;
63   unsigned int NumVTs;
64 };
65
66 namespace ISD {
67   /// Node predicates
68
69   /// If N is a BUILD_VECTOR node whose elements are all the same constant or
70   /// undefined, return true and return the constant value in \p SplatValue.
71   bool isConstantSplatVector(const SDNode *N, APInt &SplatValue);
72
73   /// Return true if the specified node is a BUILD_VECTOR where all of the
74   /// elements are ~0 or undef.
75   bool isBuildVectorAllOnes(const SDNode *N);
76
77   /// Return true if the specified node is a BUILD_VECTOR where all of the
78   /// elements are 0 or undef.
79   bool isBuildVectorAllZeros(const SDNode *N);
80
81   /// Return true if the specified node is a BUILD_VECTOR node of all
82   /// ConstantSDNode or undef.
83   bool isBuildVectorOfConstantSDNodes(const SDNode *N);
84
85   /// Return true if the specified node is a BUILD_VECTOR node of all
86   /// ConstantFPSDNode or undef.
87   bool isBuildVectorOfConstantFPSDNodes(const SDNode *N);
88
89   /// Return true if the node has at least one operand and all operands of the
90   /// specified node are ISD::UNDEF.
91   bool allOperandsUndef(const SDNode *N);
92 }  // end llvm:ISD namespace
93
94 //===----------------------------------------------------------------------===//
95 /// Unlike LLVM values, Selection DAG nodes may return multiple
96 /// values as the result of a computation.  Many nodes return multiple values,
97 /// from loads (which define a token and a return value) to ADDC (which returns
98 /// a result and a carry value), to calls (which may return an arbitrary number
99 /// of values).
100 ///
101 /// As such, each use of a SelectionDAG computation must indicate the node that
102 /// computes it as well as which return value to use from that node.  This pair
103 /// of information is represented with the SDValue value type.
104 ///
105 class SDValue {
106   friend struct DenseMapInfo<SDValue>;
107
108   SDNode *Node;       // The node defining the value we are using.
109   unsigned ResNo;     // Which return value of the node we are using.
110 public:
111   SDValue() : Node(nullptr), ResNo(0) {}
112   SDValue(SDNode *node, unsigned resno);
113
114   /// get the index which selects a specific result in the SDNode
115   unsigned getResNo() const { return ResNo; }
116
117   /// get the SDNode which holds the desired result
118   SDNode *getNode() const { return Node; }
119
120   /// set the SDNode
121   void setNode(SDNode *N) { Node = N; }
122
123   inline SDNode *operator->() const { return Node; }
124
125   bool operator==(const SDValue &O) const {
126     return Node == O.Node && ResNo == O.ResNo;
127   }
128   bool operator!=(const SDValue &O) const {
129     return !operator==(O);
130   }
131   bool operator<(const SDValue &O) const {
132     return std::tie(Node, ResNo) < std::tie(O.Node, O.ResNo);
133   }
134   explicit operator bool() const {
135     return Node != nullptr;
136   }
137
138   SDValue getValue(unsigned R) const {
139     return SDValue(Node, R);
140   }
141
142   /// Return true if this node is an operand of N.
143   bool isOperandOf(const SDNode *N) const;
144
145   /// Return the ValueType of the referenced return value.
146   inline EVT getValueType() const;
147
148   /// Return the simple ValueType of the referenced return value.
149   MVT getSimpleValueType() const {
150     return getValueType().getSimpleVT();
151   }
152
153   /// Returns the size of the value in bits.
154   unsigned getValueSizeInBits() const {
155     return getValueType().getSizeInBits();
156   }
157
158   unsigned getScalarValueSizeInBits() const {
159     return getValueType().getScalarType().getSizeInBits();
160   }
161
162   // Forwarding methods - These forward to the corresponding methods in SDNode.
163   inline unsigned getOpcode() const;
164   inline unsigned getNumOperands() const;
165   inline const SDValue &getOperand(unsigned i) const;
166   inline uint64_t getConstantOperandVal(unsigned i) const;
167   inline bool isTargetMemoryOpcode() const;
168   inline bool isTargetOpcode() const;
169   inline bool isMachineOpcode() const;
170   inline bool isUndef() const;
171   inline unsigned getMachineOpcode() const;
172   inline const DebugLoc &getDebugLoc() const;
173   inline void dump() const;
174   inline void dumpr() const;
175
176   /// Return true if this operand (which must be a chain) reaches the
177   /// specified operand without crossing any side-effecting instructions.
178   /// In practice, this looks through token factors and non-volatile loads.
179   /// In order to remain efficient, this only
180   /// looks a couple of nodes in, it does not do an exhaustive search.
181   bool reachesChainWithoutSideEffects(SDValue Dest,
182                                       unsigned Depth = 2) const;
183
184   /// Return true if there are no nodes using value ResNo of Node.
185   inline bool use_empty() const;
186
187   /// Return true if there is exactly one node using value ResNo of Node.
188   inline bool hasOneUse() const;
189 };
190
191
192 template<> struct DenseMapInfo<SDValue> {
193   static inline SDValue getEmptyKey() {
194     SDValue V;
195     V.ResNo = -1U;
196     return V;
197   }
198   static inline SDValue getTombstoneKey() {
199     SDValue V;
200     V.ResNo = -2U;
201     return V;
202   }
203   static unsigned getHashValue(const SDValue &Val) {
204     return ((unsigned)((uintptr_t)Val.getNode() >> 4) ^
205             (unsigned)((uintptr_t)Val.getNode() >> 9)) + Val.getResNo();
206   }
207   static bool isEqual(const SDValue &LHS, const SDValue &RHS) {
208     return LHS == RHS;
209   }
210 };
211 template <> struct isPodLike<SDValue> { static const bool value = true; };
212
213
214 /// Allow casting operators to work directly on
215 /// SDValues as if they were SDNode*'s.
216 template<> struct simplify_type<SDValue> {
217   typedef SDNode* SimpleType;
218   static SimpleType getSimplifiedValue(SDValue &Val) {
219     return Val.getNode();
220   }
221 };
222 template<> struct simplify_type<const SDValue> {
223   typedef /*const*/ SDNode* SimpleType;
224   static SimpleType getSimplifiedValue(const SDValue &Val) {
225     return Val.getNode();
226   }
227 };
228
229 /// Represents a use of a SDNode. This class holds an SDValue,
230 /// which records the SDNode being used and the result number, a
231 /// pointer to the SDNode using the value, and Next and Prev pointers,
232 /// which link together all the uses of an SDNode.
233 ///
234 class SDUse {
235   /// Val - The value being used.
236   SDValue Val;
237   /// User - The user of this value.
238   SDNode *User;
239   /// Prev, Next - Pointers to the uses list of the SDNode referred by
240   /// this operand.
241   SDUse **Prev, *Next;
242
243   SDUse(const SDUse &U) = delete;
244   void operator=(const SDUse &U) = delete;
245
246 public:
247   SDUse() : Val(), User(nullptr), Prev(nullptr), Next(nullptr) {}
248
249   /// Normally SDUse will just implicitly convert to an SDValue that it holds.
250   operator const SDValue&() const { return Val; }
251
252   /// If implicit conversion to SDValue doesn't work, the get() method returns
253   /// the SDValue.
254   const SDValue &get() const { return Val; }
255
256   /// This returns the SDNode that contains this Use.
257   SDNode *getUser() { return User; }
258
259   /// Get the next SDUse in the use list.
260   SDUse *getNext() const { return Next; }
261
262   /// Convenience function for get().getNode().
263   SDNode *getNode() const { return Val.getNode(); }
264   /// Convenience function for get().getResNo().
265   unsigned getResNo() const { return Val.getResNo(); }
266   /// Convenience function for get().getValueType().
267   EVT getValueType() const { return Val.getValueType(); }
268
269   /// Convenience function for get().operator==
270   bool operator==(const SDValue &V) const {
271     return Val == V;
272   }
273
274   /// Convenience function for get().operator!=
275   bool operator!=(const SDValue &V) const {
276     return Val != V;
277   }
278
279   /// Convenience function for get().operator<
280   bool operator<(const SDValue &V) const {
281     return Val < V;
282   }
283
284 private:
285   friend class SelectionDAG;
286   friend class SDNode;
287   // TODO: unfriend HandleSDNode once we fix its operand handling.
288   friend class HandleSDNode;
289
290   void setUser(SDNode *p) { User = p; }
291
292   /// Remove this use from its existing use list, assign it the
293   /// given value, and add it to the new value's node's use list.
294   inline void set(const SDValue &V);
295   /// Like set, but only supports initializing a newly-allocated
296   /// SDUse with a non-null value.
297   inline void setInitial(const SDValue &V);
298   /// Like set, but only sets the Node portion of the value,
299   /// leaving the ResNo portion unmodified.
300   inline void setNode(SDNode *N);
301
302   void addToList(SDUse **List) {
303     Next = *List;
304     if (Next) Next->Prev = &Next;
305     Prev = List;
306     *List = this;
307   }
308
309   void removeFromList() {
310     *Prev = Next;
311     if (Next) Next->Prev = Prev;
312   }
313 };
314
315 /// simplify_type specializations - Allow casting operators to work directly on
316 /// SDValues as if they were SDNode*'s.
317 template<> struct simplify_type<SDUse> {
318   typedef SDNode* SimpleType;
319   static SimpleType getSimplifiedValue(SDUse &Val) {
320     return Val.getNode();
321   }
322 };
323
324 /// These are IR-level optimization flags that may be propagated to SDNodes.
325 /// TODO: This data structure should be shared by the IR optimizer and the
326 /// the backend.
327 struct SDNodeFlags {
328 private:
329   bool NoUnsignedWrap : 1;
330   bool NoSignedWrap : 1;
331   bool Exact : 1;
332   bool UnsafeAlgebra : 1;
333   bool NoNaNs : 1;
334   bool NoInfs : 1;
335   bool NoSignedZeros : 1;
336   bool AllowReciprocal : 1;
337   bool VectorReduction : 1;
338
339 public:
340   /// Default constructor turns off all optimization flags.
341   SDNodeFlags() {
342     NoUnsignedWrap = false;
343     NoSignedWrap = false;
344     Exact = false;
345     UnsafeAlgebra = false;
346     NoNaNs = false;
347     NoInfs = false;
348     NoSignedZeros = false;
349     AllowReciprocal = false;
350     VectorReduction = false;
351   }
352
353   // These are mutators for each flag.
354   void setNoUnsignedWrap(bool b) { NoUnsignedWrap = b; }
355   void setNoSignedWrap(bool b) { NoSignedWrap = b; }
356   void setExact(bool b) { Exact = b; }
357   void setUnsafeAlgebra(bool b) { UnsafeAlgebra = b; }
358   void setNoNaNs(bool b) { NoNaNs = b; }
359   void setNoInfs(bool b) { NoInfs = b; }
360   void setNoSignedZeros(bool b) { NoSignedZeros = b; }
361   void setAllowReciprocal(bool b) { AllowReciprocal = b; }
362   void setVectorReduction(bool b) { VectorReduction = b; }
363
364   // These are accessors for each flag.
365   bool hasNoUnsignedWrap() const { return NoUnsignedWrap; }
366   bool hasNoSignedWrap() const { return NoSignedWrap; }
367   bool hasExact() const { return Exact; }
368   bool hasUnsafeAlgebra() const { return UnsafeAlgebra; }
369   bool hasNoNaNs() const { return NoNaNs; }
370   bool hasNoInfs() const { return NoInfs; }
371   bool hasNoSignedZeros() const { return NoSignedZeros; }
372   bool hasAllowReciprocal() const { return AllowReciprocal; }
373   bool hasVectorReduction() const { return VectorReduction; }
374
375   /// Return a raw encoding of the flags.
376   /// This function should only be used to add data to the NodeID value.
377   unsigned getRawFlags() const {
378     return (NoUnsignedWrap << 0) | (NoSignedWrap << 1) | (Exact << 2) |
379     (UnsafeAlgebra << 3) | (NoNaNs << 4) | (NoInfs << 5) |
380     (NoSignedZeros << 6) | (AllowReciprocal << 7);
381   }
382
383   /// Clear any flags in this flag set that aren't also set in Flags.
384   void intersectWith(const SDNodeFlags *Flags) {
385     NoUnsignedWrap &= Flags->NoUnsignedWrap;
386     NoSignedWrap &= Flags->NoSignedWrap;
387     Exact &= Flags->Exact;
388     UnsafeAlgebra &= Flags->UnsafeAlgebra;
389     NoNaNs &= Flags->NoNaNs;
390     NoInfs &= Flags->NoInfs;
391     NoSignedZeros &= Flags->NoSignedZeros;
392     AllowReciprocal &= Flags->AllowReciprocal;
393   }
394 };
395
396 /// Represents one node in the SelectionDAG.
397 ///
398 class SDNode : public FoldingSetNode, public ilist_node<SDNode> {
399 private:
400   /// The operation that this node performs.
401   int16_t NodeType;
402
403   /// This tracks whether this node has one or more dbg_value
404   /// nodes corresponding to it.
405   uint16_t HasDebugValue : 1;
406
407 protected:
408   /// This member is defined by this class, but is not used for
409   /// anything.  Subclasses can use it to hold whatever state they find useful.
410   /// This field is initialized to zero by the ctor.
411   uint16_t SubclassData : 15;
412
413 private:
414   /// Unique id per SDNode in the DAG.
415   int NodeId;
416
417   /// The values that are used by this operation.
418   SDUse *OperandList;
419
420   /// The types of the values this node defines.  SDNode's may
421   /// define multiple values simultaneously.
422   const EVT *ValueList;
423
424   /// List of uses for this SDNode.
425   SDUse *UseList;
426
427   /// The number of entries in the Operand/Value list.
428   unsigned short NumOperands, NumValues;
429
430   // The ordering of the SDNodes. It roughly corresponds to the ordering of the
431   // original LLVM instructions.
432   // This is used for turning off scheduling, because we'll forgo
433   // the normal scheduling algorithms and output the instructions according to
434   // this ordering.
435   unsigned IROrder;
436
437   /// Source line information.
438   DebugLoc debugLoc;
439
440   /// Return a pointer to the specified value type.
441   static const EVT *getValueTypeList(EVT VT);
442
443   friend class SelectionDAG;
444   friend struct ilist_traits<SDNode>;
445   // TODO: unfriend HandleSDNode once we fix its operand handling.
446   friend class HandleSDNode;
447
448 public:
449   /// Unique and persistent id per SDNode in the DAG.
450   /// Used for debug printing.
451   uint16_t PersistentId;
452
453   //===--------------------------------------------------------------------===//
454   //  Accessors
455   //
456
457   /// Return the SelectionDAG opcode value for this node. For
458   /// pre-isel nodes (those for which isMachineOpcode returns false), these
459   /// are the opcode values in the ISD and <target>ISD namespaces. For
460   /// post-isel opcodes, see getMachineOpcode.
461   unsigned getOpcode()  const { return (unsigned short)NodeType; }
462
463   /// Test if this node has a target-specific opcode (in the
464   /// \<target\>ISD namespace).
465   bool isTargetOpcode() const { return NodeType >= ISD::BUILTIN_OP_END; }
466
467   /// Test if this node has a target-specific
468   /// memory-referencing opcode (in the \<target\>ISD namespace and
469   /// greater than FIRST_TARGET_MEMORY_OPCODE).
470   bool isTargetMemoryOpcode() const {
471     return NodeType >= ISD::FIRST_TARGET_MEMORY_OPCODE;
472   }
473
474   /// Return true if the type of the node type undefined.
475   bool isUndef() const { return NodeType == ISD::UNDEF; }
476
477   /// Test if this node is a memory intrinsic (with valid pointer information).
478   /// INTRINSIC_W_CHAIN and INTRINSIC_VOID nodes are sometimes created for
479   /// non-memory intrinsics (with chains) that are not really instances of
480   /// MemSDNode. For such nodes, we need some extra state to determine the
481   /// proper classof relationship.
482   bool isMemIntrinsic() const {
483     return (NodeType == ISD::INTRINSIC_W_CHAIN ||
484             NodeType == ISD::INTRINSIC_VOID) && ((SubclassData >> 13) & 1);
485   }
486
487   /// Test if this node has a post-isel opcode, directly
488   /// corresponding to a MachineInstr opcode.
489   bool isMachineOpcode() const { return NodeType < 0; }
490
491   /// This may only be called if isMachineOpcode returns
492   /// true. It returns the MachineInstr opcode value that the node's opcode
493   /// corresponds to.
494   unsigned getMachineOpcode() const {
495     assert(isMachineOpcode() && "Not a MachineInstr opcode!");
496     return ~NodeType;
497   }
498
499   /// Get this bit.
500   bool getHasDebugValue() const { return HasDebugValue; }
501
502   /// Set this bit.
503   void setHasDebugValue(bool b) { HasDebugValue = b; }
504
505   /// Return true if there are no uses of this node.
506   bool use_empty() const { return UseList == nullptr; }
507
508   /// Return true if there is exactly one use of this node.
509   bool hasOneUse() const {
510     return !use_empty() && std::next(use_begin()) == use_end();
511   }
512
513   /// Return the number of uses of this node. This method takes
514   /// time proportional to the number of uses.
515   size_t use_size() const { return std::distance(use_begin(), use_end()); }
516
517   /// Return the unique node id.
518   int getNodeId() const { return NodeId; }
519
520   /// Set unique node id.
521   void setNodeId(int Id) { NodeId = Id; }
522
523   /// Return the node ordering.
524   unsigned getIROrder() const { return IROrder; }
525
526   /// Set the node ordering.
527   void setIROrder(unsigned Order) { IROrder = Order; }
528
529   /// Return the source location info.
530   const DebugLoc &getDebugLoc() const { return debugLoc; }
531
532   /// Set source location info.  Try to avoid this, putting
533   /// it in the constructor is preferable.
534   void setDebugLoc(DebugLoc dl) { debugLoc = std::move(dl); }
535
536   /// This class provides iterator support for SDUse
537   /// operands that use a specific SDNode.
538   class use_iterator
539     : public std::iterator<std::forward_iterator_tag, SDUse, ptrdiff_t> {
540     SDUse *Op;
541     explicit use_iterator(SDUse *op) : Op(op) {
542     }
543     friend class SDNode;
544   public:
545     typedef std::iterator<std::forward_iterator_tag,
546                           SDUse, ptrdiff_t>::reference reference;
547     typedef std::iterator<std::forward_iterator_tag,
548                           SDUse, ptrdiff_t>::pointer pointer;
549
550     use_iterator(const use_iterator &I) : Op(I.Op) {}
551     use_iterator() : Op(nullptr) {}
552
553     bool operator==(const use_iterator &x) const {
554       return Op == x.Op;
555     }
556     bool operator!=(const use_iterator &x) const {
557       return !operator==(x);
558     }
559
560     /// Return true if this iterator is at the end of uses list.
561     bool atEnd() const { return Op == nullptr; }
562
563     // Iterator traversal: forward iteration only.
564     use_iterator &operator++() {          // Preincrement
565       assert(Op && "Cannot increment end iterator!");
566       Op = Op->getNext();
567       return *this;
568     }
569
570     use_iterator operator++(int) {        // Postincrement
571       use_iterator tmp = *this; ++*this; return tmp;
572     }
573
574     /// Retrieve a pointer to the current user node.
575     SDNode *operator*() const {
576       assert(Op && "Cannot dereference end iterator!");
577       return Op->getUser();
578     }
579
580     SDNode *operator->() const { return operator*(); }
581
582     SDUse &getUse() const { return *Op; }
583
584     /// Retrieve the operand # of this use in its user.
585     unsigned getOperandNo() const {
586       assert(Op && "Cannot dereference end iterator!");
587       return (unsigned)(Op - Op->getUser()->OperandList);
588     }
589   };
590
591   /// Provide iteration support to walk over all uses of an SDNode.
592   use_iterator use_begin() const {
593     return use_iterator(UseList);
594   }
595
596   static use_iterator use_end() { return use_iterator(nullptr); }
597
598   inline iterator_range<use_iterator> uses() {
599     return make_range(use_begin(), use_end());
600   }
601   inline iterator_range<use_iterator> uses() const {
602     return make_range(use_begin(), use_end());
603   }
604
605   /// Return true if there are exactly NUSES uses of the indicated value.
606   /// This method ignores uses of other values defined by this operation.
607   bool hasNUsesOfValue(unsigned NUses, unsigned Value) const;
608
609   /// Return true if there are any use of the indicated value.
610   /// This method ignores uses of other values defined by this operation.
611   bool hasAnyUseOfValue(unsigned Value) const;
612
613   /// Return true if this node is the only use of N.
614   bool isOnlyUserOf(const SDNode *N) const;
615
616   /// Return true if this node is an operand of N.
617   bool isOperandOf(const SDNode *N) const;
618
619   /// Return true if this node is a predecessor of N.
620   /// NOTE: Implemented on top of hasPredecessor and every bit as
621   /// expensive. Use carefully.
622   bool isPredecessorOf(const SDNode *N) const {
623     return N->hasPredecessor(this);
624   }
625
626   /// Return true if N is a predecessor of this node.
627   /// N is either an operand of this node, or can be reached by recursively
628   /// traversing up the operands.
629   /// NOTE: This is an expensive method. Use it carefully.
630   bool hasPredecessor(const SDNode *N) const;
631
632   /// Returns true if N is a predecessor of any node in Worklist. This
633   /// helper keeps Visited and Worklist sets externally to allow unions
634   /// searches to be performed in parallel, caching of results across
635   /// queries and incremental addition to Worklist. Stops early if N is
636   /// found but will resume. Remember to clear Visited and Worklists
637   /// if DAG changes.
638   static bool hasPredecessorHelper(const SDNode *N,
639                                    SmallPtrSetImpl<const SDNode *> &Visited,
640                                    SmallVectorImpl<const SDNode *> &Worklist) {
641     if (Visited.count(N))
642       return true;
643     while (!Worklist.empty()) {
644       const SDNode *M = Worklist.pop_back_val();
645       bool Found = false;
646       for (const SDValue &OpV : M->op_values()) {
647         SDNode *Op = OpV.getNode();
648         if (Visited.insert(Op).second)
649           Worklist.push_back(Op);
650         if (Op == N)
651           Found = true;
652       }
653       if (Found)
654         return true;
655     }
656     return false;
657   }
658
659   /// Return the number of values used by this operation.
660   unsigned getNumOperands() const { return NumOperands; }
661
662   /// Helper method returns the integer value of a ConstantSDNode operand.
663   uint64_t getConstantOperandVal(unsigned Num) const;
664
665   const SDValue &getOperand(unsigned Num) const {
666     assert(Num < NumOperands && "Invalid child # of SDNode!");
667     return OperandList[Num];
668   }
669
670   typedef SDUse* op_iterator;
671   op_iterator op_begin() const { return OperandList; }
672   op_iterator op_end() const { return OperandList+NumOperands; }
673   ArrayRef<SDUse> ops() const { return makeArrayRef(op_begin(), op_end()); }
674
675   /// Iterator for directly iterating over the operand SDValue's.
676   struct value_op_iterator
677       : iterator_adaptor_base<value_op_iterator, op_iterator,
678                               std::random_access_iterator_tag, SDValue,
679                               ptrdiff_t, value_op_iterator *,
680                               value_op_iterator *> {
681     explicit value_op_iterator(SDUse *U = nullptr)
682       : iterator_adaptor_base(U) {}
683
684     const SDValue &operator*() const { return I->get(); }
685   };
686
687   iterator_range<value_op_iterator> op_values() const {
688     return make_range(value_op_iterator(op_begin()),
689                       value_op_iterator(op_end()));
690   }
691
692   SDVTList getVTList() const {
693     SDVTList X = { ValueList, NumValues };
694     return X;
695   }
696
697   /// If this node has a glue operand, return the node
698   /// to which the glue operand points. Otherwise return NULL.
699   SDNode *getGluedNode() const {
700     if (getNumOperands() != 0 &&
701         getOperand(getNumOperands()-1).getValueType() == MVT::Glue)
702       return getOperand(getNumOperands()-1).getNode();
703     return nullptr;
704   }
705
706   /// If this node has a glue value with a user, return
707   /// the user (there is at most one). Otherwise return NULL.
708   SDNode *getGluedUser() const {
709     for (use_iterator UI = use_begin(), UE = use_end(); UI != UE; ++UI)
710       if (UI.getUse().get().getValueType() == MVT::Glue)
711         return *UI;
712     return nullptr;
713   }
714
715   /// This could be defined as a virtual function and implemented more simply
716   /// and directly, but it is not to avoid creating a vtable for this class.
717   const SDNodeFlags *getFlags() const;
718
719   /// Clear any flags in this node that aren't also set in Flags.
720   void intersectFlagsWith(const SDNodeFlags *Flags);
721
722   /// Return the number of values defined/returned by this operator.
723   unsigned getNumValues() const { return NumValues; }
724
725   /// Return the type of a specified result.
726   EVT getValueType(unsigned ResNo) const {
727     assert(ResNo < NumValues && "Illegal result number!");
728     return ValueList[ResNo];
729   }
730
731   /// Return the type of a specified result as a simple type.
732   MVT getSimpleValueType(unsigned ResNo) const {
733     return getValueType(ResNo).getSimpleVT();
734   }
735
736   /// Returns MVT::getSizeInBits(getValueType(ResNo)).
737   unsigned getValueSizeInBits(unsigned ResNo) const {
738     return getValueType(ResNo).getSizeInBits();
739   }
740
741   typedef const EVT* value_iterator;
742   value_iterator value_begin() const { return ValueList; }
743   value_iterator value_end() const { return ValueList+NumValues; }
744
745   /// Return the opcode of this operation for printing.
746   std::string getOperationName(const SelectionDAG *G = nullptr) const;
747   static const char* getIndexedModeName(ISD::MemIndexedMode AM);
748   void print_types(raw_ostream &OS, const SelectionDAG *G) const;
749   void print_details(raw_ostream &OS, const SelectionDAG *G) const;
750   void print(raw_ostream &OS, const SelectionDAG *G = nullptr) const;
751   void printr(raw_ostream &OS, const SelectionDAG *G = nullptr) const;
752
753   /// Print a SelectionDAG node and all children down to
754   /// the leaves.  The given SelectionDAG allows target-specific nodes
755   /// to be printed in human-readable form.  Unlike printr, this will
756   /// print the whole DAG, including children that appear multiple
757   /// times.
758   ///
759   void printrFull(raw_ostream &O, const SelectionDAG *G = nullptr) const;
760
761   /// Print a SelectionDAG node and children up to
762   /// depth "depth."  The given SelectionDAG allows target-specific
763   /// nodes to be printed in human-readable form.  Unlike printr, this
764   /// will print children that appear multiple times wherever they are
765   /// used.
766   ///
767   void printrWithDepth(raw_ostream &O, const SelectionDAG *G = nullptr,
768                        unsigned depth = 100) const;
769
770
771   /// Dump this node, for debugging.
772   void dump() const;
773
774   /// Dump (recursively) this node and its use-def subgraph.
775   void dumpr() const;
776
777   /// Dump this node, for debugging.
778   /// The given SelectionDAG allows target-specific nodes to be printed
779   /// in human-readable form.
780   void dump(const SelectionDAG *G) const;
781
782   /// Dump (recursively) this node and its use-def subgraph.
783   /// The given SelectionDAG allows target-specific nodes to be printed
784   /// in human-readable form.
785   void dumpr(const SelectionDAG *G) const;
786
787   /// printrFull to dbgs().  The given SelectionDAG allows
788   /// target-specific nodes to be printed in human-readable form.
789   /// Unlike dumpr, this will print the whole DAG, including children
790   /// that appear multiple times.
791   void dumprFull(const SelectionDAG *G = nullptr) const;
792
793   /// printrWithDepth to dbgs().  The given
794   /// SelectionDAG allows target-specific nodes to be printed in
795   /// human-readable form.  Unlike dumpr, this will print children
796   /// that appear multiple times wherever they are used.
797   ///
798   void dumprWithDepth(const SelectionDAG *G = nullptr,
799                       unsigned depth = 100) const;
800
801   /// Gather unique data for the node.
802   void Profile(FoldingSetNodeID &ID) const;
803
804   /// This method should only be used by the SDUse class.
805   void addUse(SDUse &U) { U.addToList(&UseList); }
806
807 protected:
808   static SDVTList getSDVTList(EVT VT) {
809     SDVTList Ret = { getValueTypeList(VT), 1 };
810     return Ret;
811   }
812
813   /// Create an SDNode.
814   ///
815   /// SDNodes are created without any operands, and never own the operand
816   /// storage. To add operands, see SelectionDAG::createOperands.
817   SDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs)
818       : NodeType(Opc), HasDebugValue(false), SubclassData(0), NodeId(-1),
819         OperandList(nullptr), ValueList(VTs.VTs), UseList(nullptr),
820         NumOperands(0), NumValues(VTs.NumVTs), IROrder(Order),
821         debugLoc(std::move(dl)) {
822     assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
823     assert(NumValues == VTs.NumVTs &&
824            "NumValues wasn't wide enough for its operands!");
825   }
826
827   /// Release the operands and set this node to have zero operands.
828   void DropOperands();
829 };
830
831 /// Wrapper class for IR location info (IR ordering and DebugLoc) to be passed
832 /// into SDNode creation functions.
833 /// When an SDNode is created from the DAGBuilder, the DebugLoc is extracted
834 /// from the original Instruction, and IROrder is the ordinal position of
835 /// the instruction.
836 /// When an SDNode is created after the DAG is being built, both DebugLoc and
837 /// the IROrder are propagated from the original SDNode.
838 /// So SDLoc class provides two constructors besides the default one, one to
839 /// be used by the DAGBuilder, the other to be used by others.
840 class SDLoc {
841 private:
842   DebugLoc DL;
843   int IROrder = 0;
844
845 public:
846   SDLoc() = default;
847   SDLoc(const SDNode *N) : DL(N->getDebugLoc()), IROrder(N->getIROrder()) {}
848   SDLoc(const SDValue V) : SDLoc(V.getNode()) {}
849   SDLoc(const Instruction *I, int Order) : IROrder(Order) {
850     assert(Order >= 0 && "bad IROrder");
851     if (I)
852       DL = I->getDebugLoc();
853   }
854   unsigned getIROrder() const { return IROrder; }
855   const DebugLoc &getDebugLoc() const { return DL; }
856 };
857
858
859 // Define inline functions from the SDValue class.
860
861 inline SDValue::SDValue(SDNode *node, unsigned resno)
862     : Node(node), ResNo(resno) {
863   assert((!Node || ResNo < Node->getNumValues()) &&
864          "Invalid result number for the given node!");
865   assert(ResNo < -2U && "Cannot use result numbers reserved for DenseMaps.");
866 }
867
868 inline unsigned SDValue::getOpcode() const {
869   return Node->getOpcode();
870 }
871 inline EVT SDValue::getValueType() const {
872   return Node->getValueType(ResNo);
873 }
874 inline unsigned SDValue::getNumOperands() const {
875   return Node->getNumOperands();
876 }
877 inline const SDValue &SDValue::getOperand(unsigned i) const {
878   return Node->getOperand(i);
879 }
880 inline uint64_t SDValue::getConstantOperandVal(unsigned i) const {
881   return Node->getConstantOperandVal(i);
882 }
883 inline bool SDValue::isTargetOpcode() const {
884   return Node->isTargetOpcode();
885 }
886 inline bool SDValue::isTargetMemoryOpcode() const {
887   return Node->isTargetMemoryOpcode();
888 }
889 inline bool SDValue::isMachineOpcode() const {
890   return Node->isMachineOpcode();
891 }
892 inline unsigned SDValue::getMachineOpcode() const {
893   return Node->getMachineOpcode();
894 }
895 inline bool SDValue::isUndef() const {
896   return Node->isUndef();
897 }
898 inline bool SDValue::use_empty() const {
899   return !Node->hasAnyUseOfValue(ResNo);
900 }
901 inline bool SDValue::hasOneUse() const {
902   return Node->hasNUsesOfValue(1, ResNo);
903 }
904 inline const DebugLoc &SDValue::getDebugLoc() const {
905   return Node->getDebugLoc();
906 }
907 inline void SDValue::dump() const {
908   return Node->dump();
909 }
910 inline void SDValue::dumpr() const {
911   return Node->dumpr();
912 }
913 // Define inline functions from the SDUse class.
914
915 inline void SDUse::set(const SDValue &V) {
916   if (Val.getNode()) removeFromList();
917   Val = V;
918   if (V.getNode()) V.getNode()->addUse(*this);
919 }
920
921 inline void SDUse::setInitial(const SDValue &V) {
922   Val = V;
923   V.getNode()->addUse(*this);
924 }
925
926 inline void SDUse::setNode(SDNode *N) {
927   if (Val.getNode()) removeFromList();
928   Val.setNode(N);
929   if (N) N->addUse(*this);
930 }
931
932 /// Returns true if the opcode is a binary operation with flags.
933 static bool isBinOpWithFlags(unsigned Opcode) {
934   switch (Opcode) {
935   case ISD::SDIV:
936   case ISD::UDIV:
937   case ISD::SRA:
938   case ISD::SRL:
939   case ISD::MUL:
940   case ISD::ADD:
941   case ISD::SUB:
942   case ISD::SHL:
943   case ISD::FADD:
944   case ISD::FDIV:
945   case ISD::FMUL:
946   case ISD::FREM:
947   case ISD::FSUB:
948     return true;
949   default:
950     return false;
951   }
952 }
953
954 /// This class is an extension of BinarySDNode
955 /// used from those opcodes that have associated extra flags.
956 class BinaryWithFlagsSDNode : public SDNode {
957 public:
958   SDNodeFlags Flags;
959   BinaryWithFlagsSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
960                         SDVTList VTs, const SDNodeFlags &NodeFlags)
961       : SDNode(Opc, Order, dl, VTs), Flags(NodeFlags) {}
962   static bool classof(const SDNode *N) {
963     return isBinOpWithFlags(N->getOpcode());
964   }
965 };
966
967 /// This class is used to form a handle around another node that
968 /// is persistent and is updated across invocations of replaceAllUsesWith on its
969 /// operand.  This node should be directly created by end-users and not added to
970 /// the AllNodes list.
971 class HandleSDNode : public SDNode {
972   SDUse Op;
973 public:
974   explicit HandleSDNode(SDValue X)
975     : SDNode(ISD::HANDLENODE, 0, DebugLoc(), getSDVTList(MVT::Other)) {
976     // HandleSDNodes are never inserted into the DAG, so they won't be
977     // auto-numbered. Use ID 65535 as a sentinel.
978     PersistentId = 0xffff;
979
980     // Manually set up the operand list. This node type is special in that it's
981     // always stack allocated and SelectionDAG does not manage its operands.
982     // TODO: This should either (a) not be in the SDNode hierarchy, or (b) not
983     // be so special.
984     Op.setUser(this);
985     Op.setInitial(X);
986     NumOperands = 1;
987     OperandList = &Op;
988   }
989   ~HandleSDNode();
990   const SDValue &getValue() const { return Op; }
991 };
992
993 class AddrSpaceCastSDNode : public SDNode {
994 private:
995   unsigned SrcAddrSpace;
996   unsigned DestAddrSpace;
997
998 public:
999   AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, EVT VT,
1000                       unsigned SrcAS, unsigned DestAS);
1001
1002   unsigned getSrcAddressSpace() const { return SrcAddrSpace; }
1003   unsigned getDestAddressSpace() const { return DestAddrSpace; }
1004
1005   static bool classof(const SDNode *N) {
1006     return N->getOpcode() == ISD::ADDRSPACECAST;
1007   }
1008 };
1009
1010 /// This is an abstract virtual class for memory operations.
1011 class MemSDNode : public SDNode {
1012 private:
1013   // VT of in-memory value.
1014   EVT MemoryVT;
1015
1016 protected:
1017   /// Memory reference information.
1018   MachineMemOperand *MMO;
1019
1020 public:
1021   MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs,
1022             EVT MemoryVT, MachineMemOperand *MMO);
1023
1024   bool readMem() const { return MMO->isLoad(); }
1025   bool writeMem() const { return MMO->isStore(); }
1026
1027   /// Returns alignment and volatility of the memory access
1028   unsigned getOriginalAlignment() const {
1029     return MMO->getBaseAlignment();
1030   }
1031   unsigned getAlignment() const {
1032     return MMO->getAlignment();
1033   }
1034
1035   /// Return the SubclassData value, which contains an
1036   /// encoding of the volatile flag, as well as bits used by subclasses. This
1037   /// function should only be used to compute a FoldingSetNodeID value.
1038   unsigned getRawSubclassData() const {
1039     return SubclassData;
1040   }
1041
1042   // We access subclass data here so that we can check consistency
1043   // with MachineMemOperand information.
1044   bool isVolatile() const { return (SubclassData >> 5) & 1; }
1045   bool isNonTemporal() const { return (SubclassData >> 6) & 1; }
1046   bool isInvariant() const { return (SubclassData >> 7) & 1; }
1047
1048   AtomicOrdering getOrdering() const {
1049     return AtomicOrdering((SubclassData >> 8) & 15);
1050   }
1051   SynchronizationScope getSynchScope() const {
1052     return SynchronizationScope((SubclassData >> 12) & 1);
1053   }
1054
1055   // Returns the offset from the location of the access.
1056   int64_t getSrcValueOffset() const { return MMO->getOffset(); }
1057
1058   /// Returns the AA info that describes the dereference.
1059   AAMDNodes getAAInfo() const { return MMO->getAAInfo(); }
1060
1061   /// Returns the Ranges that describes the dereference.
1062   const MDNode *getRanges() const { return MMO->getRanges(); }
1063
1064   /// Return the type of the in-memory value.
1065   EVT getMemoryVT() const { return MemoryVT; }
1066
1067   /// Return a MachineMemOperand object describing the memory
1068   /// reference performed by operation.
1069   MachineMemOperand *getMemOperand() const { return MMO; }
1070
1071   const MachinePointerInfo &getPointerInfo() const {
1072     return MMO->getPointerInfo();
1073   }
1074
1075   /// Return the address space for the associated pointer
1076   unsigned getAddressSpace() const {
1077     return getPointerInfo().getAddrSpace();
1078   }
1079
1080   /// Update this MemSDNode's MachineMemOperand information
1081   /// to reflect the alignment of NewMMO, if it has a greater alignment.
1082   /// This must only be used when the new alignment applies to all users of
1083   /// this MachineMemOperand.
1084   void refineAlignment(const MachineMemOperand *NewMMO) {
1085     MMO->refineAlignment(NewMMO);
1086   }
1087
1088   const SDValue &getChain() const { return getOperand(0); }
1089   const SDValue &getBasePtr() const {
1090     return getOperand(getOpcode() == ISD::STORE ? 2 : 1);
1091   }
1092
1093   // Methods to support isa and dyn_cast
1094   static bool classof(const SDNode *N) {
1095     // For some targets, we lower some target intrinsics to a MemIntrinsicNode
1096     // with either an intrinsic or a target opcode.
1097     return N->getOpcode() == ISD::LOAD                ||
1098            N->getOpcode() == ISD::STORE               ||
1099            N->getOpcode() == ISD::PREFETCH            ||
1100            N->getOpcode() == ISD::ATOMIC_CMP_SWAP     ||
1101            N->getOpcode() == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS ||
1102            N->getOpcode() == ISD::ATOMIC_SWAP         ||
1103            N->getOpcode() == ISD::ATOMIC_LOAD_ADD     ||
1104            N->getOpcode() == ISD::ATOMIC_LOAD_SUB     ||
1105            N->getOpcode() == ISD::ATOMIC_LOAD_AND     ||
1106            N->getOpcode() == ISD::ATOMIC_LOAD_OR      ||
1107            N->getOpcode() == ISD::ATOMIC_LOAD_XOR     ||
1108            N->getOpcode() == ISD::ATOMIC_LOAD_NAND    ||
1109            N->getOpcode() == ISD::ATOMIC_LOAD_MIN     ||
1110            N->getOpcode() == ISD::ATOMIC_LOAD_MAX     ||
1111            N->getOpcode() == ISD::ATOMIC_LOAD_UMIN    ||
1112            N->getOpcode() == ISD::ATOMIC_LOAD_UMAX    ||
1113            N->getOpcode() == ISD::ATOMIC_LOAD         ||
1114            N->getOpcode() == ISD::ATOMIC_STORE        ||
1115            N->getOpcode() == ISD::MLOAD               ||
1116            N->getOpcode() == ISD::MSTORE              ||
1117            N->getOpcode() == ISD::MGATHER             ||
1118            N->getOpcode() == ISD::MSCATTER            ||
1119            N->isMemIntrinsic()                        ||
1120            N->isTargetMemoryOpcode();
1121   }
1122 };
1123
1124 /// This is an SDNode representing atomic operations.
1125 class AtomicSDNode : public MemSDNode {
1126   /// For cmpxchg instructions, the ordering requirements when a store does not
1127   /// occur.
1128   AtomicOrdering FailureOrdering;
1129
1130   void InitAtomic(AtomicOrdering SuccessOrdering,
1131                   AtomicOrdering FailureOrdering,
1132                   SynchronizationScope SynchScope) {
1133     // This must match encodeMemSDNodeFlags() in SelectionDAG.cpp.
1134     assert((AtomicOrdering)((unsigned)SuccessOrdering & 15) ==
1135                SuccessOrdering &&
1136            "Ordering may not require more than 4 bits!");
1137     assert((AtomicOrdering)((unsigned)FailureOrdering & 15) ==
1138                FailureOrdering &&
1139            "Ordering may not require more than 4 bits!");
1140     assert((SynchScope & 1) == SynchScope &&
1141            "SynchScope may not require more than 1 bit!");
1142     SubclassData |= (unsigned)SuccessOrdering << 8;
1143     SubclassData |= SynchScope << 12;
1144     this->FailureOrdering = FailureOrdering;
1145     assert(getSuccessOrdering() == SuccessOrdering &&
1146            "Ordering encoding error!");
1147     assert(getFailureOrdering() == FailureOrdering &&
1148            "Ordering encoding error!");
1149     assert(getSynchScope() == SynchScope && "Synch-scope encoding error!");
1150   }
1151
1152 public:
1153   AtomicSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTL,
1154                EVT MemVT, MachineMemOperand *MMO,
1155                AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
1156                SynchronizationScope SynchScope)
1157       : MemSDNode(Opc, Order, dl, VTL, MemVT, MMO) {
1158     InitAtomic(SuccessOrdering, FailureOrdering, SynchScope);
1159   }
1160
1161   const SDValue &getBasePtr() const { return getOperand(1); }
1162   const SDValue &getVal() const { return getOperand(2); }
1163
1164   AtomicOrdering getSuccessOrdering() const {
1165     return getOrdering();
1166   }
1167
1168   // Not quite enough room in SubclassData for everything, so failure gets its
1169   // own field.
1170   AtomicOrdering getFailureOrdering() const {
1171     return FailureOrdering;
1172   }
1173
1174   bool isCompareAndSwap() const {
1175     unsigned Op = getOpcode();
1176     return Op == ISD::ATOMIC_CMP_SWAP || Op == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS;
1177   }
1178
1179   // Methods to support isa and dyn_cast
1180   static bool classof(const SDNode *N) {
1181     return N->getOpcode() == ISD::ATOMIC_CMP_SWAP     ||
1182            N->getOpcode() == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS ||
1183            N->getOpcode() == ISD::ATOMIC_SWAP         ||
1184            N->getOpcode() == ISD::ATOMIC_LOAD_ADD     ||
1185            N->getOpcode() == ISD::ATOMIC_LOAD_SUB     ||
1186            N->getOpcode() == ISD::ATOMIC_LOAD_AND     ||
1187            N->getOpcode() == ISD::ATOMIC_LOAD_OR      ||
1188            N->getOpcode() == ISD::ATOMIC_LOAD_XOR     ||
1189            N->getOpcode() == ISD::ATOMIC_LOAD_NAND    ||
1190            N->getOpcode() == ISD::ATOMIC_LOAD_MIN     ||
1191            N->getOpcode() == ISD::ATOMIC_LOAD_MAX     ||
1192            N->getOpcode() == ISD::ATOMIC_LOAD_UMIN    ||
1193            N->getOpcode() == ISD::ATOMIC_LOAD_UMAX    ||
1194            N->getOpcode() == ISD::ATOMIC_LOAD         ||
1195            N->getOpcode() == ISD::ATOMIC_STORE;
1196   }
1197 };
1198
1199 /// This SDNode is used for target intrinsics that touch
1200 /// memory and need an associated MachineMemOperand. Its opcode may be
1201 /// INTRINSIC_VOID, INTRINSIC_W_CHAIN, PREFETCH, or a target-specific opcode
1202 /// with a value not less than FIRST_TARGET_MEMORY_OPCODE.
1203 class MemIntrinsicSDNode : public MemSDNode {
1204 public:
1205   MemIntrinsicSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
1206                      SDVTList VTs, EVT MemoryVT, MachineMemOperand *MMO)
1207       : MemSDNode(Opc, Order, dl, VTs, MemoryVT, MMO) {
1208     SubclassData |= 1u << 13;
1209   }
1210
1211   // Methods to support isa and dyn_cast
1212   static bool classof(const SDNode *N) {
1213     // We lower some target intrinsics to their target opcode
1214     // early a node with a target opcode can be of this class
1215     return N->isMemIntrinsic()             ||
1216            N->getOpcode() == ISD::PREFETCH ||
1217            N->isTargetMemoryOpcode();
1218   }
1219 };
1220
1221 /// This SDNode is used to implement the code generator
1222 /// support for the llvm IR shufflevector instruction.  It combines elements
1223 /// from two input vectors into a new input vector, with the selection and
1224 /// ordering of elements determined by an array of integers, referred to as
1225 /// the shuffle mask.  For input vectors of width N, mask indices of 0..N-1
1226 /// refer to elements from the LHS input, and indices from N to 2N-1 the RHS.
1227 /// An index of -1 is treated as undef, such that the code generator may put
1228 /// any value in the corresponding element of the result.
1229 class ShuffleVectorSDNode : public SDNode {
1230   // The memory for Mask is owned by the SelectionDAG's OperandAllocator, and
1231   // is freed when the SelectionDAG object is destroyed.
1232   const int *Mask;
1233 protected:
1234   friend class SelectionDAG;
1235   ShuffleVectorSDNode(EVT VT, unsigned Order, const DebugLoc &dl, const int *M)
1236       : SDNode(ISD::VECTOR_SHUFFLE, Order, dl, getSDVTList(VT)), Mask(M) {}
1237
1238 public:
1239   ArrayRef<int> getMask() const {
1240     EVT VT = getValueType(0);
1241     return makeArrayRef(Mask, VT.getVectorNumElements());
1242   }
1243   int getMaskElt(unsigned Idx) const {
1244     assert(Idx < getValueType(0).getVectorNumElements() && "Idx out of range!");
1245     return Mask[Idx];
1246   }
1247
1248   bool isSplat() const { return isSplatMask(Mask, getValueType(0)); }
1249   int  getSplatIndex() const {
1250     assert(isSplat() && "Cannot get splat index for non-splat!");
1251     EVT VT = getValueType(0);
1252     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
1253       if (Mask[i] >= 0)
1254         return Mask[i];
1255     }
1256     llvm_unreachable("Splat with all undef indices?");
1257   }
1258   static bool isSplatMask(const int *Mask, EVT VT);
1259
1260   /// Change values in a shuffle permute mask assuming
1261   /// the two vector operands have swapped position.
1262   static void commuteMask(MutableArrayRef<int> Mask) {
1263     unsigned NumElems = Mask.size();
1264     for (unsigned i = 0; i != NumElems; ++i) {
1265       int idx = Mask[i];
1266       if (idx < 0)
1267         continue;
1268       else if (idx < (int)NumElems)
1269         Mask[i] = idx + NumElems;
1270       else
1271         Mask[i] = idx - NumElems;
1272     }
1273   }
1274
1275   static bool classof(const SDNode *N) {
1276     return N->getOpcode() == ISD::VECTOR_SHUFFLE;
1277   }
1278 };
1279
1280 class ConstantSDNode : public SDNode {
1281   const ConstantInt *Value;
1282   friend class SelectionDAG;
1283   ConstantSDNode(bool isTarget, bool isOpaque, const ConstantInt *val,
1284                  const DebugLoc &DL, EVT VT)
1285       : SDNode(isTarget ? ISD::TargetConstant : ISD::Constant, 0, DL,
1286                getSDVTList(VT)),
1287         Value(val) {
1288     SubclassData |= (uint16_t)isOpaque;
1289   }
1290 public:
1291
1292   const ConstantInt *getConstantIntValue() const { return Value; }
1293   const APInt &getAPIntValue() const { return Value->getValue(); }
1294   uint64_t getZExtValue() const { return Value->getZExtValue(); }
1295   int64_t getSExtValue() const { return Value->getSExtValue(); }
1296
1297   bool isOne() const { return Value->isOne(); }
1298   bool isNullValue() const { return Value->isNullValue(); }
1299   bool isAllOnesValue() const { return Value->isAllOnesValue(); }
1300
1301   bool isOpaque() const { return SubclassData & 1; }
1302
1303   static bool classof(const SDNode *N) {
1304     return N->getOpcode() == ISD::Constant ||
1305            N->getOpcode() == ISD::TargetConstant;
1306   }
1307 };
1308
1309 class ConstantFPSDNode : public SDNode {
1310   const ConstantFP *Value;
1311   friend class SelectionDAG;
1312   ConstantFPSDNode(bool isTarget, const ConstantFP *val, const DebugLoc &DL,
1313                    EVT VT)
1314       : SDNode(isTarget ? ISD::TargetConstantFP : ISD::ConstantFP, 0, DL,
1315                getSDVTList(VT)),
1316         Value(val) {}
1317
1318 public:
1319
1320   const APFloat& getValueAPF() const { return Value->getValueAPF(); }
1321   const ConstantFP *getConstantFPValue() const { return Value; }
1322
1323   /// Return true if the value is positive or negative zero.
1324   bool isZero() const { return Value->isZero(); }
1325
1326   /// Return true if the value is a NaN.
1327   bool isNaN() const { return Value->isNaN(); }
1328
1329   /// Return true if the value is an infinity
1330   bool isInfinity() const { return Value->isInfinity(); }
1331
1332   /// Return true if the value is negative.
1333   bool isNegative() const { return Value->isNegative(); }
1334
1335   /// We don't rely on operator== working on double values, as
1336   /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
1337   /// As such, this method can be used to do an exact bit-for-bit comparison of
1338   /// two floating point values.
1339
1340   /// We leave the version with the double argument here because it's just so
1341   /// convenient to write "2.0" and the like.  Without this function we'd
1342   /// have to duplicate its logic everywhere it's called.
1343   bool isExactlyValue(double V) const {
1344     bool ignored;
1345     APFloat Tmp(V);
1346     Tmp.convert(Value->getValueAPF().getSemantics(),
1347                 APFloat::rmNearestTiesToEven, &ignored);
1348     return isExactlyValue(Tmp);
1349   }
1350   bool isExactlyValue(const APFloat& V) const;
1351
1352   static bool isValueValidForType(EVT VT, const APFloat& Val);
1353
1354   static bool classof(const SDNode *N) {
1355     return N->getOpcode() == ISD::ConstantFP ||
1356            N->getOpcode() == ISD::TargetConstantFP;
1357   }
1358 };
1359
1360 /// Returns true if \p V is a constant integer zero.
1361 bool isNullConstant(SDValue V);
1362 /// Returns true if \p V is an FP constant with a value of positive zero.
1363 bool isNullFPConstant(SDValue V);
1364 /// Returns true if \p V is an integer constant with all bits set.
1365 bool isAllOnesConstant(SDValue V);
1366 /// Returns true if \p V is a constant integer one.
1367 bool isOneConstant(SDValue V);
1368 /// Returns true if \p V is a bitwise not operation. Assumes that an all ones
1369 /// constant is canonicalized to be operand 1.
1370 bool isBitwiseNot(SDValue V);
1371
1372 class GlobalAddressSDNode : public SDNode {
1373   const GlobalValue *TheGlobal;
1374   int64_t Offset;
1375   unsigned char TargetFlags;
1376   friend class SelectionDAG;
1377   GlobalAddressSDNode(unsigned Opc, unsigned Order, const DebugLoc &DL,
1378                       const GlobalValue *GA, EVT VT, int64_t o,
1379                       unsigned char TargetFlags);
1380
1381 public:
1382
1383   const GlobalValue *getGlobal() const { return TheGlobal; }
1384   int64_t getOffset() const { return Offset; }
1385   unsigned char getTargetFlags() const { return TargetFlags; }
1386   // Return the address space this GlobalAddress belongs to.
1387   unsigned getAddressSpace() const;
1388
1389   static bool classof(const SDNode *N) {
1390     return N->getOpcode() == ISD::GlobalAddress ||
1391            N->getOpcode() == ISD::TargetGlobalAddress ||
1392            N->getOpcode() == ISD::GlobalTLSAddress ||
1393            N->getOpcode() == ISD::TargetGlobalTLSAddress;
1394   }
1395 };
1396
1397 class FrameIndexSDNode : public SDNode {
1398   int FI;
1399   friend class SelectionDAG;
1400   FrameIndexSDNode(int fi, EVT VT, bool isTarg)
1401     : SDNode(isTarg ? ISD::TargetFrameIndex : ISD::FrameIndex,
1402       0, DebugLoc(), getSDVTList(VT)), FI(fi) {
1403   }
1404 public:
1405
1406   int getIndex() const { return FI; }
1407
1408   static bool classof(const SDNode *N) {
1409     return N->getOpcode() == ISD::FrameIndex ||
1410            N->getOpcode() == ISD::TargetFrameIndex;
1411   }
1412 };
1413
1414 class JumpTableSDNode : public SDNode {
1415   int JTI;
1416   unsigned char TargetFlags;
1417   friend class SelectionDAG;
1418   JumpTableSDNode(int jti, EVT VT, bool isTarg, unsigned char TF)
1419     : SDNode(isTarg ? ISD::TargetJumpTable : ISD::JumpTable,
1420       0, DebugLoc(), getSDVTList(VT)), JTI(jti), TargetFlags(TF) {
1421   }
1422 public:
1423
1424   int getIndex() const { return JTI; }
1425   unsigned char getTargetFlags() const { return TargetFlags; }
1426
1427   static bool classof(const SDNode *N) {
1428     return N->getOpcode() == ISD::JumpTable ||
1429            N->getOpcode() == ISD::TargetJumpTable;
1430   }
1431 };
1432
1433 class ConstantPoolSDNode : public SDNode {
1434   union {
1435     const Constant *ConstVal;
1436     MachineConstantPoolValue *MachineCPVal;
1437   } Val;
1438   int Offset;  // It's a MachineConstantPoolValue if top bit is set.
1439   unsigned Alignment;  // Minimum alignment requirement of CP (not log2 value).
1440   unsigned char TargetFlags;
1441   friend class SelectionDAG;
1442   ConstantPoolSDNode(bool isTarget, const Constant *c, EVT VT, int o,
1443                      unsigned Align, unsigned char TF)
1444     : SDNode(isTarget ? ISD::TargetConstantPool : ISD::ConstantPool, 0,
1445              DebugLoc(), getSDVTList(VT)), Offset(o), Alignment(Align),
1446              TargetFlags(TF) {
1447     assert(Offset >= 0 && "Offset is too large");
1448     Val.ConstVal = c;
1449   }
1450   ConstantPoolSDNode(bool isTarget, MachineConstantPoolValue *v,
1451                      EVT VT, int o, unsigned Align, unsigned char TF)
1452     : SDNode(isTarget ? ISD::TargetConstantPool : ISD::ConstantPool, 0,
1453              DebugLoc(), getSDVTList(VT)), Offset(o), Alignment(Align),
1454              TargetFlags(TF) {
1455     assert(Offset >= 0 && "Offset is too large");
1456     Val.MachineCPVal = v;
1457     Offset |= 1 << (sizeof(unsigned)*CHAR_BIT-1);
1458   }
1459 public:
1460
1461   bool isMachineConstantPoolEntry() const {
1462     return Offset < 0;
1463   }
1464
1465   const Constant *getConstVal() const {
1466     assert(!isMachineConstantPoolEntry() && "Wrong constantpool type");
1467     return Val.ConstVal;
1468   }
1469
1470   MachineConstantPoolValue *getMachineCPVal() const {
1471     assert(isMachineConstantPoolEntry() && "Wrong constantpool type");
1472     return Val.MachineCPVal;
1473   }
1474
1475   int getOffset() const {
1476     return Offset & ~(1 << (sizeof(unsigned)*CHAR_BIT-1));
1477   }
1478
1479   // Return the alignment of this constant pool object, which is either 0 (for
1480   // default alignment) or the desired value.
1481   unsigned getAlignment() const { return Alignment; }
1482   unsigned char getTargetFlags() const { return TargetFlags; }
1483
1484   Type *getType() const;
1485
1486   static bool classof(const SDNode *N) {
1487     return N->getOpcode() == ISD::ConstantPool ||
1488            N->getOpcode() == ISD::TargetConstantPool;
1489   }
1490 };
1491
1492 /// Completely target-dependent object reference.
1493 class TargetIndexSDNode : public SDNode {
1494   unsigned char TargetFlags;
1495   int Index;
1496   int64_t Offset;
1497   friend class SelectionDAG;
1498 public:
1499
1500   TargetIndexSDNode(int Idx, EVT VT, int64_t Ofs, unsigned char TF)
1501     : SDNode(ISD::TargetIndex, 0, DebugLoc(), getSDVTList(VT)),
1502       TargetFlags(TF), Index(Idx), Offset(Ofs) {}
1503 public:
1504
1505   unsigned char getTargetFlags() const { return TargetFlags; }
1506   int getIndex() const { return Index; }
1507   int64_t getOffset() const { return Offset; }
1508
1509   static bool classof(const SDNode *N) {
1510     return N->getOpcode() == ISD::TargetIndex;
1511   }
1512 };
1513
1514 class BasicBlockSDNode : public SDNode {
1515   MachineBasicBlock *MBB;
1516   friend class SelectionDAG;
1517   /// Debug info is meaningful and potentially useful here, but we create
1518   /// blocks out of order when they're jumped to, which makes it a bit
1519   /// harder.  Let's see if we need it first.
1520   explicit BasicBlockSDNode(MachineBasicBlock *mbb)
1521     : SDNode(ISD::BasicBlock, 0, DebugLoc(), getSDVTList(MVT::Other)), MBB(mbb)
1522   {}
1523 public:
1524
1525   MachineBasicBlock *getBasicBlock() const { return MBB; }
1526
1527   static bool classof(const SDNode *N) {
1528     return N->getOpcode() == ISD::BasicBlock;
1529   }
1530 };
1531
1532 /// A "pseudo-class" with methods for operating on BUILD_VECTORs.
1533 class BuildVectorSDNode : public SDNode {
1534   // These are constructed as SDNodes and then cast to BuildVectorSDNodes.
1535   explicit BuildVectorSDNode() = delete;
1536 public:
1537   /// Check if this is a constant splat, and if so, find the
1538   /// smallest element size that splats the vector.  If MinSplatBits is
1539   /// nonzero, the element size must be at least that large.  Note that the
1540   /// splat element may be the entire vector (i.e., a one element vector).
1541   /// Returns the splat element value in SplatValue.  Any undefined bits in
1542   /// that value are zero, and the corresponding bits in the SplatUndef mask
1543   /// are set.  The SplatBitSize value is set to the splat element size in
1544   /// bits.  HasAnyUndefs is set to true if any bits in the vector are
1545   /// undefined.  isBigEndian describes the endianness of the target.
1546   bool isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
1547                        unsigned &SplatBitSize, bool &HasAnyUndefs,
1548                        unsigned MinSplatBits = 0,
1549                        bool isBigEndian = false) const;
1550
1551   /// \brief Returns the splatted value or a null value if this is not a splat.
1552   ///
1553   /// If passed a non-null UndefElements bitvector, it will resize it to match
1554   /// the vector width and set the bits where elements are undef.
1555   SDValue getSplatValue(BitVector *UndefElements = nullptr) const;
1556
1557   /// \brief Returns the splatted constant or null if this is not a constant
1558   /// splat.
1559   ///
1560   /// If passed a non-null UndefElements bitvector, it will resize it to match
1561   /// the vector width and set the bits where elements are undef.
1562   ConstantSDNode *
1563   getConstantSplatNode(BitVector *UndefElements = nullptr) const;
1564
1565   /// \brief Returns the splatted constant FP or null if this is not a constant
1566   /// FP splat.
1567   ///
1568   /// If passed a non-null UndefElements bitvector, it will resize it to match
1569   /// the vector width and set the bits where elements are undef.
1570   ConstantFPSDNode *
1571   getConstantFPSplatNode(BitVector *UndefElements = nullptr) const;
1572
1573   /// \brief If this is a constant FP splat and the splatted constant FP is an
1574   /// exact power or 2, return the log base 2 integer value.  Otherwise,
1575   /// return -1.
1576   ///
1577   /// The BitWidth specifies the necessary bit precision.
1578   int32_t getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
1579                                           uint32_t BitWidth) const;
1580
1581   bool isConstant() const;
1582
1583   static inline bool classof(const SDNode *N) {
1584     return N->getOpcode() == ISD::BUILD_VECTOR;
1585   }
1586 };
1587
1588 /// An SDNode that holds an arbitrary LLVM IR Value. This is
1589 /// used when the SelectionDAG needs to make a simple reference to something
1590 /// in the LLVM IR representation.
1591 ///
1592 class SrcValueSDNode : public SDNode {
1593   const Value *V;
1594   friend class SelectionDAG;
1595   /// Create a SrcValue for a general value.
1596   explicit SrcValueSDNode(const Value *v)
1597     : SDNode(ISD::SRCVALUE, 0, DebugLoc(), getSDVTList(MVT::Other)), V(v) {}
1598
1599 public:
1600   /// Return the contained Value.
1601   const Value *getValue() const { return V; }
1602
1603   static bool classof(const SDNode *N) {
1604     return N->getOpcode() == ISD::SRCVALUE;
1605   }
1606 };
1607
1608 class MDNodeSDNode : public SDNode {
1609   const MDNode *MD;
1610   friend class SelectionDAG;
1611   explicit MDNodeSDNode(const MDNode *md)
1612   : SDNode(ISD::MDNODE_SDNODE, 0, DebugLoc(), getSDVTList(MVT::Other)), MD(md)
1613   {}
1614 public:
1615
1616   const MDNode *getMD() const { return MD; }
1617
1618   static bool classof(const SDNode *N) {
1619     return N->getOpcode() == ISD::MDNODE_SDNODE;
1620   }
1621 };
1622
1623 class RegisterSDNode : public SDNode {
1624   unsigned Reg;
1625   friend class SelectionDAG;
1626   RegisterSDNode(unsigned reg, EVT VT)
1627     : SDNode(ISD::Register, 0, DebugLoc(), getSDVTList(VT)), Reg(reg) {
1628   }
1629 public:
1630
1631   unsigned getReg() const { return Reg; }
1632
1633   static bool classof(const SDNode *N) {
1634     return N->getOpcode() == ISD::Register;
1635   }
1636 };
1637
1638 class RegisterMaskSDNode : public SDNode {
1639   // The memory for RegMask is not owned by the node.
1640   const uint32_t *RegMask;
1641   friend class SelectionDAG;
1642   RegisterMaskSDNode(const uint32_t *mask)
1643     : SDNode(ISD::RegisterMask, 0, DebugLoc(), getSDVTList(MVT::Untyped)),
1644       RegMask(mask) {}
1645 public:
1646
1647   const uint32_t *getRegMask() const { return RegMask; }
1648
1649   static bool classof(const SDNode *N) {
1650     return N->getOpcode() == ISD::RegisterMask;
1651   }
1652 };
1653
1654 class BlockAddressSDNode : public SDNode {
1655   const BlockAddress *BA;
1656   int64_t Offset;
1657   unsigned char TargetFlags;
1658   friend class SelectionDAG;
1659   BlockAddressSDNode(unsigned NodeTy, EVT VT, const BlockAddress *ba,
1660                      int64_t o, unsigned char Flags)
1661     : SDNode(NodeTy, 0, DebugLoc(), getSDVTList(VT)),
1662              BA(ba), Offset(o), TargetFlags(Flags) {
1663   }
1664 public:
1665   const BlockAddress *getBlockAddress() const { return BA; }
1666   int64_t getOffset() const { return Offset; }
1667   unsigned char getTargetFlags() const { return TargetFlags; }
1668
1669   static bool classof(const SDNode *N) {
1670     return N->getOpcode() == ISD::BlockAddress ||
1671            N->getOpcode() == ISD::TargetBlockAddress;
1672   }
1673 };
1674
1675 class EHLabelSDNode : public SDNode {
1676   MCSymbol *Label;
1677   friend class SelectionDAG;
1678   EHLabelSDNode(unsigned Order, const DebugLoc &dl, MCSymbol *L)
1679       : SDNode(ISD::EH_LABEL, Order, dl, getSDVTList(MVT::Other)), Label(L) {}
1680
1681 public:
1682   MCSymbol *getLabel() const { return Label; }
1683
1684   static bool classof(const SDNode *N) {
1685     return N->getOpcode() == ISD::EH_LABEL;
1686   }
1687 };
1688
1689 class ExternalSymbolSDNode : public SDNode {
1690   const char *Symbol;
1691   unsigned char TargetFlags;
1692
1693   friend class SelectionDAG;
1694   ExternalSymbolSDNode(bool isTarget, const char *Sym, unsigned char TF, EVT VT)
1695     : SDNode(isTarget ? ISD::TargetExternalSymbol : ISD::ExternalSymbol,
1696              0, DebugLoc(), getSDVTList(VT)), Symbol(Sym), TargetFlags(TF) {
1697   }
1698 public:
1699
1700   const char *getSymbol() const { return Symbol; }
1701   unsigned char getTargetFlags() const { return TargetFlags; }
1702
1703   static bool classof(const SDNode *N) {
1704     return N->getOpcode() == ISD::ExternalSymbol ||
1705            N->getOpcode() == ISD::TargetExternalSymbol;
1706   }
1707 };
1708
1709 class MCSymbolSDNode : public SDNode {
1710   MCSymbol *Symbol;
1711
1712   friend class SelectionDAG;
1713   MCSymbolSDNode(MCSymbol *Symbol, EVT VT)
1714       : SDNode(ISD::MCSymbol, 0, DebugLoc(), getSDVTList(VT)), Symbol(Symbol) {}
1715
1716 public:
1717   MCSymbol *getMCSymbol() const { return Symbol; }
1718
1719   static bool classof(const SDNode *N) {
1720     return N->getOpcode() == ISD::MCSymbol;
1721   }
1722 };
1723
1724 class CondCodeSDNode : public SDNode {
1725   ISD::CondCode Condition;
1726   friend class SelectionDAG;
1727   explicit CondCodeSDNode(ISD::CondCode Cond)
1728     : SDNode(ISD::CONDCODE, 0, DebugLoc(), getSDVTList(MVT::Other)),
1729       Condition(Cond) {
1730   }
1731 public:
1732
1733   ISD::CondCode get() const { return Condition; }
1734
1735   static bool classof(const SDNode *N) {
1736     return N->getOpcode() == ISD::CONDCODE;
1737   }
1738 };
1739
1740 /// NOTE: avoid using this node as this may disappear in the
1741 /// future and most targets don't support it.
1742 class CvtRndSatSDNode : public SDNode {
1743   ISD::CvtCode CvtCode;
1744   friend class SelectionDAG;
1745   explicit CvtRndSatSDNode(EVT VT, unsigned Order, const DebugLoc &dl,
1746                            ISD::CvtCode Code)
1747       : SDNode(ISD::CONVERT_RNDSAT, Order, dl, getSDVTList(VT)), CvtCode(Code) {
1748   }
1749
1750 public:
1751   ISD::CvtCode getCvtCode() const { return CvtCode; }
1752
1753   static bool classof(const SDNode *N) {
1754     return N->getOpcode() == ISD::CONVERT_RNDSAT;
1755   }
1756 };
1757
1758 /// This class is used to represent EVT's, which are used
1759 /// to parameterize some operations.
1760 class VTSDNode : public SDNode {
1761   EVT ValueType;
1762   friend class SelectionDAG;
1763   explicit VTSDNode(EVT VT)
1764     : SDNode(ISD::VALUETYPE, 0, DebugLoc(), getSDVTList(MVT::Other)),
1765       ValueType(VT) {
1766   }
1767 public:
1768
1769   EVT getVT() const { return ValueType; }
1770
1771   static bool classof(const SDNode *N) {
1772     return N->getOpcode() == ISD::VALUETYPE;
1773   }
1774 };
1775
1776 /// Base class for LoadSDNode and StoreSDNode
1777 class LSBaseSDNode : public MemSDNode {
1778 public:
1779   LSBaseSDNode(ISD::NodeType NodeTy, unsigned Order, const DebugLoc &dl,
1780                SDVTList VTs, ISD::MemIndexedMode AM, EVT MemVT,
1781                MachineMemOperand *MMO)
1782       : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
1783     SubclassData |= AM << 2;
1784     assert(getAddressingMode() == AM && "MemIndexedMode encoding error!");
1785   }
1786
1787   const SDValue &getOffset() const {
1788     return getOperand(getOpcode() == ISD::LOAD ? 2 : 3);
1789   }
1790
1791   /// Return the addressing mode for this load or store:
1792   /// unindexed, pre-inc, pre-dec, post-inc, or post-dec.
1793   ISD::MemIndexedMode getAddressingMode() const {
1794     return ISD::MemIndexedMode((SubclassData >> 2) & 7);
1795   }
1796
1797   /// Return true if this is a pre/post inc/dec load/store.
1798   bool isIndexed() const { return getAddressingMode() != ISD::UNINDEXED; }
1799
1800   /// Return true if this is NOT a pre/post inc/dec load/store.
1801   bool isUnindexed() const { return getAddressingMode() == ISD::UNINDEXED; }
1802
1803   static bool classof(const SDNode *N) {
1804     return N->getOpcode() == ISD::LOAD ||
1805            N->getOpcode() == ISD::STORE;
1806   }
1807 };
1808
1809 /// This class is used to represent ISD::LOAD nodes.
1810 class LoadSDNode : public LSBaseSDNode {
1811   friend class SelectionDAG;
1812   LoadSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
1813              ISD::MemIndexedMode AM, ISD::LoadExtType ETy, EVT MemVT,
1814              MachineMemOperand *MMO)
1815       : LSBaseSDNode(ISD::LOAD, Order, dl, VTs, AM, MemVT, MMO) {
1816     SubclassData |= (unsigned short)ETy;
1817     assert(getExtensionType() == ETy && "LoadExtType encoding error!");
1818     assert(readMem() && "Load MachineMemOperand is not a load!");
1819     assert(!writeMem() && "Load MachineMemOperand is a store!");
1820   }
1821 public:
1822
1823   /// Return whether this is a plain node,
1824   /// or one of the varieties of value-extending loads.
1825   ISD::LoadExtType getExtensionType() const {
1826     return ISD::LoadExtType(SubclassData & 3);
1827   }
1828
1829   const SDValue &getBasePtr() const { return getOperand(1); }
1830   const SDValue &getOffset() const { return getOperand(2); }
1831
1832   static bool classof(const SDNode *N) {
1833     return N->getOpcode() == ISD::LOAD;
1834   }
1835 };
1836
1837 /// This class is used to represent ISD::STORE nodes.
1838 class StoreSDNode : public LSBaseSDNode {
1839   friend class SelectionDAG;
1840   StoreSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
1841               ISD::MemIndexedMode AM, bool isTrunc, EVT MemVT,
1842               MachineMemOperand *MMO)
1843       : LSBaseSDNode(ISD::STORE, Order, dl, VTs, AM, MemVT, MMO) {
1844     SubclassData |= (unsigned short)isTrunc;
1845     assert(isTruncatingStore() == isTrunc && "isTrunc encoding error!");
1846     assert(!readMem() && "Store MachineMemOperand is a load!");
1847     assert(writeMem() && "Store MachineMemOperand is not a store!");
1848   }
1849 public:
1850
1851   /// Return true if the op does a truncation before store.
1852   /// For integers this is the same as doing a TRUNCATE and storing the result.
1853   /// For floats, it is the same as doing an FP_ROUND and storing the result.
1854   bool isTruncatingStore() const { return SubclassData & 1; }
1855
1856   const SDValue &getValue() const { return getOperand(1); }
1857   const SDValue &getBasePtr() const { return getOperand(2); }
1858   const SDValue &getOffset() const { return getOperand(3); }
1859
1860   static bool classof(const SDNode *N) {
1861     return N->getOpcode() == ISD::STORE;
1862   }
1863 };
1864
1865 /// This base class is used to represent MLOAD and MSTORE nodes
1866 class MaskedLoadStoreSDNode : public MemSDNode {
1867 public:
1868   friend class SelectionDAG;
1869   MaskedLoadStoreSDNode(ISD::NodeType NodeTy, unsigned Order,
1870                         const DebugLoc &dl, SDVTList VTs, EVT MemVT,
1871                         MachineMemOperand *MMO)
1872       : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {}
1873
1874   // In the both nodes address is Op1, mask is Op2:
1875   // MaskedLoadSDNode (Chain, ptr, mask, src0), src0 is a passthru value
1876   // MaskedStoreSDNode (Chain, ptr, mask, data)
1877   // Mask is a vector of i1 elements
1878   const SDValue &getBasePtr() const { return getOperand(1); }
1879   const SDValue &getMask() const    { return getOperand(2); }
1880
1881   static bool classof(const SDNode *N) {
1882     return N->getOpcode() == ISD::MLOAD ||
1883            N->getOpcode() == ISD::MSTORE;
1884   }
1885 };
1886
1887 /// This class is used to represent an MLOAD node
1888 class MaskedLoadSDNode : public MaskedLoadStoreSDNode {
1889 public:
1890   friend class SelectionDAG;
1891   MaskedLoadSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
1892                    ISD::LoadExtType ETy, EVT MemVT, MachineMemOperand *MMO)
1893       : MaskedLoadStoreSDNode(ISD::MLOAD, Order, dl, VTs, MemVT, MMO) {
1894     SubclassData |= (unsigned short)ETy;
1895   }
1896
1897   ISD::LoadExtType getExtensionType() const {
1898     return ISD::LoadExtType(SubclassData & 3);
1899   }
1900   const SDValue &getSrc0() const { return getOperand(3); }
1901   static bool classof(const SDNode *N) {
1902     return N->getOpcode() == ISD::MLOAD;
1903   }
1904 };
1905
1906 /// This class is used to represent an MSTORE node
1907 class MaskedStoreSDNode : public MaskedLoadStoreSDNode {
1908
1909 public:
1910   friend class SelectionDAG;
1911   MaskedStoreSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
1912                     bool isTrunc, EVT MemVT, MachineMemOperand *MMO)
1913       : MaskedLoadStoreSDNode(ISD::MSTORE, Order, dl, VTs, MemVT, MMO) {
1914     SubclassData |= (unsigned short)isTrunc;
1915   }
1916   /// Return true if the op does a truncation before store.
1917   /// For integers this is the same as doing a TRUNCATE and storing the result.
1918   /// For floats, it is the same as doing an FP_ROUND and storing the result.
1919   bool isTruncatingStore() const { return SubclassData & 1; }
1920
1921   const SDValue &getValue() const { return getOperand(3); }
1922
1923   static bool classof(const SDNode *N) {
1924     return N->getOpcode() == ISD::MSTORE;
1925   }
1926 };
1927
1928 /// This is a base class used to represent
1929 /// MGATHER and MSCATTER nodes
1930 ///
1931 class MaskedGatherScatterSDNode : public MemSDNode {
1932 public:
1933   friend class SelectionDAG;
1934   MaskedGatherScatterSDNode(ISD::NodeType NodeTy, unsigned Order,
1935                             const DebugLoc &dl, SDVTList VTs, EVT MemVT,
1936                             MachineMemOperand *MMO)
1937       : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {}
1938
1939   // In the both nodes address is Op1, mask is Op2:
1940   // MaskedGatherSDNode  (Chain, src0, mask, base, index), src0 is a passthru value
1941   // MaskedScatterSDNode (Chain, value, mask, base, index)
1942   // Mask is a vector of i1 elements
1943   const SDValue &getBasePtr() const { return getOperand(3); }
1944   const SDValue &getIndex()   const { return getOperand(4); }
1945   const SDValue &getMask()    const { return getOperand(2); }
1946   const SDValue &getValue()   const { return getOperand(1); }
1947
1948   static bool classof(const SDNode *N) {
1949     return N->getOpcode() == ISD::MGATHER ||
1950            N->getOpcode() == ISD::MSCATTER;
1951   }
1952 };
1953
1954 /// This class is used to represent an MGATHER node
1955 ///
1956 class MaskedGatherSDNode : public MaskedGatherScatterSDNode {
1957 public:
1958   friend class SelectionDAG;
1959   MaskedGatherSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
1960                      EVT MemVT, MachineMemOperand *MMO)
1961       : MaskedGatherScatterSDNode(ISD::MGATHER, Order, dl, VTs, MemVT, MMO) {}
1962
1963   static bool classof(const SDNode *N) {
1964     return N->getOpcode() == ISD::MGATHER;
1965   }
1966 };
1967
1968 /// This class is used to represent an MSCATTER node
1969 ///
1970 class MaskedScatterSDNode : public MaskedGatherScatterSDNode {
1971
1972 public:
1973   friend class SelectionDAG;
1974   MaskedScatterSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
1975                       EVT MemVT, MachineMemOperand *MMO)
1976       : MaskedGatherScatterSDNode(ISD::MSCATTER, Order, dl, VTs, MemVT, MMO) {}
1977
1978   static bool classof(const SDNode *N) {
1979     return N->getOpcode() == ISD::MSCATTER;
1980   }
1981 };
1982
1983 /// An SDNode that represents everything that will be needed
1984 /// to construct a MachineInstr. These nodes are created during the
1985 /// instruction selection proper phase.
1986 class MachineSDNode : public SDNode {
1987 public:
1988   typedef MachineMemOperand **mmo_iterator;
1989
1990 private:
1991   friend class SelectionDAG;
1992   MachineSDNode(unsigned Opc, unsigned Order, const DebugLoc &DL, SDVTList VTs)
1993       : SDNode(Opc, Order, DL, VTs), MemRefs(nullptr), MemRefsEnd(nullptr) {}
1994
1995   /// Memory reference descriptions for this instruction.
1996   mmo_iterator MemRefs;
1997   mmo_iterator MemRefsEnd;
1998
1999 public:
2000   mmo_iterator memoperands_begin() const { return MemRefs; }
2001   mmo_iterator memoperands_end() const { return MemRefsEnd; }
2002   bool memoperands_empty() const { return MemRefsEnd == MemRefs; }
2003
2004   /// Assign this MachineSDNodes's memory reference descriptor
2005   /// list. This does not transfer ownership.
2006   void setMemRefs(mmo_iterator NewMemRefs, mmo_iterator NewMemRefsEnd) {
2007     for (mmo_iterator MMI = NewMemRefs, MME = NewMemRefsEnd; MMI != MME; ++MMI)
2008       assert(*MMI && "Null mem ref detected!");
2009     MemRefs = NewMemRefs;
2010     MemRefsEnd = NewMemRefsEnd;
2011   }
2012
2013   static bool classof(const SDNode *N) {
2014     return N->isMachineOpcode();
2015   }
2016 };
2017
2018 class SDNodeIterator : public std::iterator<std::forward_iterator_tag,
2019                                             SDNode, ptrdiff_t> {
2020   const SDNode *Node;
2021   unsigned Operand;
2022
2023   SDNodeIterator(const SDNode *N, unsigned Op) : Node(N), Operand(Op) {}
2024 public:
2025   bool operator==(const SDNodeIterator& x) const {
2026     return Operand == x.Operand;
2027   }
2028   bool operator!=(const SDNodeIterator& x) const { return !operator==(x); }
2029
2030   pointer operator*() const {
2031     return Node->getOperand(Operand).getNode();
2032   }
2033   pointer operator->() const { return operator*(); }
2034
2035   SDNodeIterator& operator++() {                // Preincrement
2036     ++Operand;
2037     return *this;
2038   }
2039   SDNodeIterator operator++(int) { // Postincrement
2040     SDNodeIterator tmp = *this; ++*this; return tmp;
2041   }
2042   size_t operator-(SDNodeIterator Other) const {
2043     assert(Node == Other.Node &&
2044            "Cannot compare iterators of two different nodes!");
2045     return Operand - Other.Operand;
2046   }
2047
2048   static SDNodeIterator begin(const SDNode *N) { return SDNodeIterator(N, 0); }
2049   static SDNodeIterator end  (const SDNode *N) {
2050     return SDNodeIterator(N, N->getNumOperands());
2051   }
2052
2053   unsigned getOperand() const { return Operand; }
2054   const SDNode *getNode() const { return Node; }
2055 };
2056
2057 template <> struct GraphTraits<SDNode*> {
2058   typedef SDNode NodeType;
2059   typedef SDNodeIterator ChildIteratorType;
2060   static inline NodeType *getEntryNode(SDNode *N) { return N; }
2061   static inline ChildIteratorType child_begin(NodeType *N) {
2062     return SDNodeIterator::begin(N);
2063   }
2064   static inline ChildIteratorType child_end(NodeType *N) {
2065     return SDNodeIterator::end(N);
2066   }
2067 };
2068
2069 /// A representation of the largest SDNode, for use in sizeof().
2070 ///
2071 /// This needs to be a union because the largest node differs on 32 bit systems
2072 /// with 4 and 8 byte pointer alignment, respectively.
2073 typedef AlignedCharArrayUnion<AtomicSDNode, TargetIndexSDNode,
2074                               BlockAddressSDNode, GlobalAddressSDNode>
2075     LargestSDNode;
2076
2077 /// The SDNode class with the greatest alignment requirement.
2078 typedef GlobalAddressSDNode MostAlignedSDNode;
2079
2080 namespace ISD {
2081   /// Returns true if the specified node is a non-extending and unindexed load.
2082   inline bool isNormalLoad(const SDNode *N) {
2083     const LoadSDNode *Ld = dyn_cast<LoadSDNode>(N);
2084     return Ld && Ld->getExtensionType() == ISD::NON_EXTLOAD &&
2085       Ld->getAddressingMode() == ISD::UNINDEXED;
2086   }
2087
2088   /// Returns true if the specified node is a non-extending load.
2089   inline bool isNON_EXTLoad(const SDNode *N) {
2090     return isa<LoadSDNode>(N) &&
2091       cast<LoadSDNode>(N)->getExtensionType() == ISD::NON_EXTLOAD;
2092   }
2093
2094   /// Returns true if the specified node is a EXTLOAD.
2095   inline bool isEXTLoad(const SDNode *N) {
2096     return isa<LoadSDNode>(N) &&
2097       cast<LoadSDNode>(N)->getExtensionType() == ISD::EXTLOAD;
2098   }
2099
2100   /// Returns true if the specified node is a SEXTLOAD.
2101   inline bool isSEXTLoad(const SDNode *N) {
2102     return isa<LoadSDNode>(N) &&
2103       cast<LoadSDNode>(N)->getExtensionType() == ISD::SEXTLOAD;
2104   }
2105
2106   /// Returns true if the specified node is a ZEXTLOAD.
2107   inline bool isZEXTLoad(const SDNode *N) {
2108     return isa<LoadSDNode>(N) &&
2109       cast<LoadSDNode>(N)->getExtensionType() == ISD::ZEXTLOAD;
2110   }
2111
2112   /// Returns true if the specified node is an unindexed load.
2113   inline bool isUNINDEXEDLoad(const SDNode *N) {
2114     return isa<LoadSDNode>(N) &&
2115       cast<LoadSDNode>(N)->getAddressingMode() == ISD::UNINDEXED;
2116   }
2117
2118   /// Returns true if the specified node is a non-truncating
2119   /// and unindexed store.
2120   inline bool isNormalStore(const SDNode *N) {
2121     const StoreSDNode *St = dyn_cast<StoreSDNode>(N);
2122     return St && !St->isTruncatingStore() &&
2123       St->getAddressingMode() == ISD::UNINDEXED;
2124   }
2125
2126   /// Returns true if the specified node is a non-truncating store.
2127   inline bool isNON_TRUNCStore(const SDNode *N) {
2128     return isa<StoreSDNode>(N) && !cast<StoreSDNode>(N)->isTruncatingStore();
2129   }
2130
2131   /// Returns true if the specified node is a truncating store.
2132   inline bool isTRUNCStore(const SDNode *N) {
2133     return isa<StoreSDNode>(N) && cast<StoreSDNode>(N)->isTruncatingStore();
2134   }
2135
2136   /// Returns true if the specified node is an unindexed store.
2137   inline bool isUNINDEXEDStore(const SDNode *N) {
2138     return isa<StoreSDNode>(N) &&
2139       cast<StoreSDNode>(N)->getAddressingMode() == ISD::UNINDEXED;
2140   }
2141 }
2142
2143 } // end llvm namespace
2144
2145 #endif