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