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