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