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