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