SelectionDAGNodes.h revision 9373a81e53ce5f9f2c06c4209b8b886605aece08
1//===-- llvm/CodeGen/SelectionDAGNodes.h - SelectionDAG Nodes ---*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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/CodeGen/ValueTypes.h"
23#include "llvm/Value.h"
24#include "llvm/ADT/GraphTraits.h"
25#include "llvm/ADT/GraphTraits.h"
26#include "llvm/ADT/iterator"
27#include "llvm/Support/DataTypes.h"
28#include <cassert>
29#include <vector>
30
31namespace llvm {
32
33class SelectionDAG;
34class GlobalValue;
35class MachineBasicBlock;
36class SDNode;
37template <typename T> struct simplify_type;
38
39/// ISD namespace - This namespace contains an enum which represents all of the
40/// SelectionDAG node types and value types.
41///
42namespace ISD {
43  //===--------------------------------------------------------------------===//
44  /// ISD::NodeType enum - This enum defines all of the operators valid in a
45  /// SelectionDAG.
46  ///
47  enum NodeType {
48    // EntryToken - This is the marker used to indicate the start of the region.
49    EntryToken,
50
51    // Token factor - This node is takes multiple tokens as input and produces a
52    // single token result.  This is used to represent the fact that the operand
53    // operators are independent of each other.
54    TokenFactor,
55
56    // Various leaf nodes.
57    Constant, ConstantFP, GlobalAddress, FrameIndex, ConstantPool,
58    BasicBlock, ExternalSymbol, VALUETYPE, CONDCODE,
59
60    // CopyToReg - This node has chain and child nodes, and an associated
61    // register number.  The instruction selector must guarantee that the value
62    // of the value node is available in the register stored in the RegSDNode
63    // object.
64    CopyToReg,
65
66    // CopyFromReg - This node indicates that the input value is a virtual or
67    // physical register that is defined outside of the scope of this
68    // SelectionDAG.  The register is available from the RegSDNode object.
69    CopyFromReg,
70
71    // ImplicitDef - This node indicates that the specified register is
72    // implicitly defined by some operation (e.g. its a live-in argument).  This
73    // register is indicated in the RegSDNode object.  The only operand to this
74    // is the token chain coming in, the only result is the token chain going
75    // out.
76    ImplicitDef,
77
78    // UNDEF - An undefined node
79    UNDEF,
80
81    // EXTRACT_ELEMENT - This is used to get the first or second (determined by
82    // a Constant, which is required to be operand #1), element of the aggregate
83    // value specified as operand #0.  This is only for use before legalization,
84    // for values that will be broken into multiple registers.
85    EXTRACT_ELEMENT,
86
87    // BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.  Given
88    // two values of the same integer value type, this produces a value twice as
89    // big.  Like EXTRACT_ELEMENT, this can only be used before legalization.
90    BUILD_PAIR,
91
92
93    // Simple binary arithmetic operators.
94    ADD, SUB, MUL, SDIV, UDIV, SREM, UREM,
95
96    // MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing
97    // an unsigned/signed value of type i[2*n], then return the top part.
98    MULHU, MULHS,
99
100    // Bitwise operators.
101    AND, OR, XOR, SHL, SRA, SRL,
102
103    // Counting operators
104    CTTZ, CTLZ, CTPOP,
105
106    // Select
107    SELECT,
108
109    // Select with condition operator - This selects between a true value and
110    // a false value (ops #2 and #3) based on the boolean result of comparing
111    // the lhs and rhs (ops #0 and #1) of a conditional expression with the
112    // condition code in op #4, a CondCodeSDNode.
113    SELECT_CC,
114
115    // SetCC operator - This evaluates to a boolean (i1) true value if the
116    // condition is true.  The operands to this are the left and right operands
117    // to compare (ops #0, and #1) and the condition code to compare them with
118    // (op #2) as a CondCodeSDNode.
119    SETCC,
120
121    // ADD_PARTS/SUB_PARTS - These operators take two logical operands which are
122    // broken into a multiple pieces each, and return the resulting pieces of
123    // doing an atomic add/sub operation.  This is used to handle add/sub of
124    // expanded types.  The operation ordering is:
125    //       [Lo,Hi] = op [LoLHS,HiLHS], [LoRHS,HiRHS]
126    ADD_PARTS, SUB_PARTS,
127
128    // SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded
129    // integer shift operations, just like ADD/SUB_PARTS.  The operation
130    // ordering is:
131    //       [Lo,Hi] = op [LoLHS,HiLHS], Amt
132    SHL_PARTS, SRA_PARTS, SRL_PARTS,
133
134    // Conversion operators.  These are all single input single output
135    // operations.  For all of these, the result type must be strictly
136    // wider or narrower (depending on the operation) than the source
137    // type.
138
139    // SIGN_EXTEND - Used for integer types, replicating the sign bit
140    // into new bits.
141    SIGN_EXTEND,
142
143    // ZERO_EXTEND - Used for integer types, zeroing the new bits.
144    ZERO_EXTEND,
145
146    // TRUNCATE - Completely drop the high bits.
147    TRUNCATE,
148
149    // [SU]INT_TO_FP - These operators convert integers (whose interpreted sign
150    // depends on the first letter) to floating point.
151    SINT_TO_FP,
152    UINT_TO_FP,
153
154    // SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to
155    // sign extend a small value in a large integer register (e.g. sign
156    // extending the low 8 bits of a 32-bit register to fill the top 24 bits
157    // with the 7th bit).  The size of the smaller type is indicated by the 1th
158    // operand, a ValueType node.
159    SIGN_EXTEND_INREG,
160
161    // FP_TO_[US]INT - Convert a floating point value to a signed or unsigned
162    // integer.
163    FP_TO_SINT,
164    FP_TO_UINT,
165
166    // FP_ROUND - Perform a rounding operation from the current
167    // precision down to the specified precision (currently always 64->32).
168    FP_ROUND,
169
170    // FP_ROUND_INREG - This operator takes a floating point register, and
171    // rounds it to a floating point value.  It then promotes it and returns it
172    // in a register of the same size.  This operation effectively just discards
173    // excess precision.  The type to round down to is specified by the 1th
174    // operation, a VTSDNode (currently always 64->32->64).
175    FP_ROUND_INREG,
176
177    // FP_EXTEND - Extend a smaller FP type into a larger FP type.
178    FP_EXTEND,
179
180    // FNEG, FABS, FSQRT, FSIN, FCOS - Perform unary floating point negation,
181    // absolute value, square root, sine and cosine operations.
182    FNEG, FABS, FSQRT, FSIN, FCOS,
183
184    // Other operators.  LOAD and STORE have token chains as their first
185    // operand, then the same operands as an LLVM load/store instruction, then a
186    // SRCVALUE node that provides alias analysis information.
187    LOAD, STORE,
188
189    // EXTLOAD, SEXTLOAD, ZEXTLOAD - These three operators all load a value from
190    // memory and extend them to a larger value (e.g. load a byte into a word
191    // register).  All three of these have four operands, a token chain, a
192    // pointer to load from, a SRCVALUE for alias analysis, and a VALUETYPE node
193    // indicating the type to load.
194    //
195    // SEXTLOAD loads the integer operand and sign extends it to a larger
196    //          integer result type.
197    // ZEXTLOAD loads the integer operand and zero extends it to a larger
198    //          integer result type.
199    // EXTLOAD  is used for two things: floating point extending loads, and
200    //          integer extending loads where it doesn't matter what the high
201    //          bits are set to.  The code generator is allowed to codegen this
202    //          into whichever operation is more efficient.
203    EXTLOAD, SEXTLOAD, ZEXTLOAD,
204
205    // TRUNCSTORE - This operators truncates (for integer) or rounds (for FP) a
206    // value and stores it to memory in one operation.  This can be used for
207    // either integer or floating point operands.  The first four operands of
208    // this are the same as a standard store.  The fifth is the ValueType to
209    // store it as (which will be smaller than the source value).
210    TRUNCSTORE,
211
212    // DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned
213    // to a specified boundary.  The first operand is the token chain, the
214    // second is the number of bytes to allocate, and the third is the alignment
215    // boundary.
216    DYNAMIC_STACKALLOC,
217
218    // Control flow instructions.  These all have token chains.
219
220    // BR - Unconditional branch.  The first operand is the chain
221    // operand, the second is the MBB to branch to.
222    BR,
223
224    // BRCOND - Conditional branch.  The first operand is the chain,
225    // the second is the condition, the third is the block to branch
226    // to if the condition is true.
227    BRCOND,
228
229    // BRCONDTWOWAY - Two-way conditional branch.  The first operand is the
230    // chain, the second is the condition, the third is the block to branch to
231    // if true, and the forth is the block to branch to if false.  Targets
232    // usually do not implement this, preferring to have legalize demote the
233    // operation to BRCOND/BR pairs when necessary.
234    BRCONDTWOWAY,
235
236    // RET - Return from function.  The first operand is the chain,
237    // and any subsequent operands are the return values for the
238    // function.  This operation can have variable number of operands.
239    RET,
240
241    // CALL - Call to a function pointer.  The first operand is the chain, the
242    // second is the destination function pointer (a GlobalAddress for a direct
243    // call).  Arguments have already been lowered to explicit DAGs according to
244    // the calling convention in effect here.  TAILCALL is the same as CALL, but
245    // the callee is known not to access the stack of the caller.
246    CALL,
247    TAILCALL,
248
249    // MEMSET/MEMCPY/MEMMOVE - The first operand is the chain, and the rest
250    // correspond to the operands of the LLVM intrinsic functions.  The only
251    // result is a token chain.  The alignment argument is guaranteed to be a
252    // Constant node.
253    MEMSET,
254    MEMMOVE,
255    MEMCPY,
256
257    // CALLSEQ_START/CALLSEQ_END - These operators mark the beginning and end of
258    // a call sequence, and carry arbitrary information that target might want
259    // to know.  The first operand is a chain, the rest are specified by the
260    // target and not touched by the DAG optimizers.
261    CALLSEQ_START,  // Beginning of a call sequence
262    CALLSEQ_END,    // End of a call sequence
263
264    // SRCVALUE - This corresponds to a Value*, and is used to associate memory
265    // locations with their value.  This allows one use alias analysis
266    // information in the backend.
267    SRCVALUE,
268
269    // PCMARKER - This corresponds to the pcmarker intrinsic.
270    PCMARKER,
271
272    // READPORT, WRITEPORT, READIO, WRITEIO - These correspond to the LLVM
273    // intrinsics of the same name.  The first operand is a token chain, the
274    // other operands match the intrinsic.  These produce a token chain in
275    // addition to a value (if any).
276    READPORT, WRITEPORT, READIO, WRITEIO,
277
278    // BUILTIN_OP_END - This must be the last enum value in this list.
279    BUILTIN_OP_END,
280  };
281
282  //===--------------------------------------------------------------------===//
283  /// ISD::CondCode enum - These are ordered carefully to make the bitfields
284  /// below work out, when considering SETFALSE (something that never exists
285  /// dynamically) as 0.  "U" -> Unsigned (for integer operands) or Unordered
286  /// (for floating point), "L" -> Less than, "G" -> Greater than, "E" -> Equal
287  /// to.  If the "N" column is 1, the result of the comparison is undefined if
288  /// the input is a NAN.
289  ///
290  /// All of these (except for the 'always folded ops') should be handled for
291  /// floating point.  For integer, only the SETEQ,SETNE,SETLT,SETLE,SETGT,
292  /// SETGE,SETULT,SETULE,SETUGT, and SETUGE opcodes are used.
293  ///
294  /// Note that these are laid out in a specific order to allow bit-twiddling
295  /// to transform conditions.
296  enum CondCode {
297    // Opcode          N U L G E       Intuitive operation
298    SETFALSE,      //    0 0 0 0       Always false (always folded)
299    SETOEQ,        //    0 0 0 1       True if ordered and equal
300    SETOGT,        //    0 0 1 0       True if ordered and greater than
301    SETOGE,        //    0 0 1 1       True if ordered and greater than or equal
302    SETOLT,        //    0 1 0 0       True if ordered and less than
303    SETOLE,        //    0 1 0 1       True if ordered and less than or equal
304    SETONE,        //    0 1 1 0       True if ordered and operands are unequal
305    SETO,          //    0 1 1 1       True if ordered (no nans)
306    SETUO,         //    1 0 0 0       True if unordered: isnan(X) | isnan(Y)
307    SETUEQ,        //    1 0 0 1       True if unordered or equal
308    SETUGT,        //    1 0 1 0       True if unordered or greater than
309    SETUGE,        //    1 0 1 1       True if unordered, greater than, or equal
310    SETULT,        //    1 1 0 0       True if unordered or less than
311    SETULE,        //    1 1 0 1       True if unordered, less than, or equal
312    SETUNE,        //    1 1 1 0       True if unordered or not equal
313    SETTRUE,       //    1 1 1 1       Always true (always folded)
314    // Don't care operations: undefined if the input is a nan.
315    SETFALSE2,     //  1 X 0 0 0       Always false (always folded)
316    SETEQ,         //  1 X 0 0 1       True if equal
317    SETGT,         //  1 X 0 1 0       True if greater than
318    SETGE,         //  1 X 0 1 1       True if greater than or equal
319    SETLT,         //  1 X 1 0 0       True if less than
320    SETLE,         //  1 X 1 0 1       True if less than or equal
321    SETNE,         //  1 X 1 1 0       True if not equal
322    SETTRUE2,      //  1 X 1 1 1       Always true (always folded)
323
324    SETCC_INVALID,      // Marker value.
325  };
326
327  /// isSignedIntSetCC - Return true if this is a setcc instruction that
328  /// performs a signed comparison when used with integer operands.
329  inline bool isSignedIntSetCC(CondCode Code) {
330    return Code == SETGT || Code == SETGE || Code == SETLT || Code == SETLE;
331  }
332
333  /// isUnsignedIntSetCC - Return true if this is a setcc instruction that
334  /// performs an unsigned comparison when used with integer operands.
335  inline bool isUnsignedIntSetCC(CondCode Code) {
336    return Code == SETUGT || Code == SETUGE || Code == SETULT || Code == SETULE;
337  }
338
339  /// isTrueWhenEqual - Return true if the specified condition returns true if
340  /// the two operands to the condition are equal.  Note that if one of the two
341  /// operands is a NaN, this value is meaningless.
342  inline bool isTrueWhenEqual(CondCode Cond) {
343    return ((int)Cond & 1) != 0;
344  }
345
346  /// getUnorderedFlavor - This function returns 0 if the condition is always
347  /// false if an operand is a NaN, 1 if the condition is always true if the
348  /// operand is a NaN, and 2 if the condition is undefined if the operand is a
349  /// NaN.
350  inline unsigned getUnorderedFlavor(CondCode Cond) {
351    return ((int)Cond >> 3) & 3;
352  }
353
354  /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
355  /// 'op' is a valid SetCC operation.
356  CondCode getSetCCInverse(CondCode Operation, bool isInteger);
357
358  /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
359  /// when given the operation for (X op Y).
360  CondCode getSetCCSwappedOperands(CondCode Operation);
361
362  /// getSetCCOrOperation - Return the result of a logical OR between different
363  /// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This
364  /// function returns SETCC_INVALID if it is not possible to represent the
365  /// resultant comparison.
366  CondCode getSetCCOrOperation(CondCode Op1, CondCode Op2, bool isInteger);
367
368  /// getSetCCAndOperation - Return the result of a logical AND between
369  /// different comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
370  /// function returns SETCC_INVALID if it is not possible to represent the
371  /// resultant comparison.
372  CondCode getSetCCAndOperation(CondCode Op1, CondCode Op2, bool isInteger);
373}  // end llvm::ISD namespace
374
375
376//===----------------------------------------------------------------------===//
377/// SDOperand - Unlike LLVM values, Selection DAG nodes may return multiple
378/// values as the result of a computation.  Many nodes return multiple values,
379/// from loads (which define a token and a return value) to ADDC (which returns
380/// a result and a carry value), to calls (which may return an arbitrary number
381/// of values).
382///
383/// As such, each use of a SelectionDAG computation must indicate the node that
384/// computes it as well as which return value to use from that node.  This pair
385/// of information is represented with the SDOperand value type.
386///
387class SDOperand {
388public:
389  SDNode *Val;        // The node defining the value we are using.
390  unsigned ResNo;     // Which return value of the node we are using.
391
392  SDOperand() : Val(0) {}
393  SDOperand(SDNode *val, unsigned resno) : Val(val), ResNo(resno) {}
394
395  bool operator==(const SDOperand &O) const {
396    return Val == O.Val && ResNo == O.ResNo;
397  }
398  bool operator!=(const SDOperand &O) const {
399    return !operator==(O);
400  }
401  bool operator<(const SDOperand &O) const {
402    return Val < O.Val || (Val == O.Val && ResNo < O.ResNo);
403  }
404
405  SDOperand getValue(unsigned R) const {
406    return SDOperand(Val, R);
407  }
408
409  /// getValueType - Return the ValueType of the referenced return value.
410  ///
411  inline MVT::ValueType getValueType() const;
412
413  // Forwarding methods - These forward to the corresponding methods in SDNode.
414  inline unsigned getOpcode() const;
415  inline unsigned getNodeDepth() const;
416  inline unsigned getNumOperands() const;
417  inline const SDOperand &getOperand(unsigned i) const;
418
419  /// hasOneUse - Return true if there is exactly one operation using this
420  /// result value of the defining operator.
421  inline bool hasOneUse() const;
422};
423
424
425/// simplify_type specializations - Allow casting operators to work directly on
426/// SDOperands as if they were SDNode*'s.
427template<> struct simplify_type<SDOperand> {
428  typedef SDNode* SimpleType;
429  static SimpleType getSimplifiedValue(const SDOperand &Val) {
430    return static_cast<SimpleType>(Val.Val);
431  }
432};
433template<> struct simplify_type<const SDOperand> {
434  typedef SDNode* SimpleType;
435  static SimpleType getSimplifiedValue(const SDOperand &Val) {
436    return static_cast<SimpleType>(Val.Val);
437  }
438};
439
440
441/// SDNode - Represents one node in the SelectionDAG.
442///
443class SDNode {
444  /// NodeType - The operation that this node performs.
445  ///
446  unsigned short NodeType;
447
448  /// NodeDepth - Node depth is defined as MAX(Node depth of children)+1.  This
449  /// means that leaves have a depth of 1, things that use only leaves have a
450  /// depth of 2, etc.
451  unsigned short NodeDepth;
452
453  /// Operands - The values that are used by this operation.
454  ///
455  std::vector<SDOperand> Operands;
456
457  /// Values - The types of the values this node defines.  SDNode's may define
458  /// multiple values simultaneously.
459  std::vector<MVT::ValueType> Values;
460
461  /// Uses - These are all of the SDNode's that use a value produced by this
462  /// node.
463  std::vector<SDNode*> Uses;
464public:
465
466  //===--------------------------------------------------------------------===//
467  //  Accessors
468  //
469  unsigned getOpcode()  const { return NodeType; }
470
471  size_t use_size() const { return Uses.size(); }
472  bool use_empty() const { return Uses.empty(); }
473  bool hasOneUse() const { return Uses.size() == 1; }
474
475  /// getNodeDepth - Return the distance from this node to the leaves in the
476  /// graph.  The leaves have a depth of 1.
477  unsigned getNodeDepth() const { return NodeDepth; }
478
479  typedef std::vector<SDNode*>::const_iterator use_iterator;
480  use_iterator use_begin() const { return Uses.begin(); }
481  use_iterator use_end() const { return Uses.end(); }
482
483  /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
484  /// indicated value.  This method ignores uses of other values defined by this
485  /// operation.
486  bool hasNUsesOfValue(unsigned NUses, unsigned Value);
487
488  /// getNumOperands - Return the number of values used by this operation.
489  ///
490  unsigned getNumOperands() const { return Operands.size(); }
491
492  const SDOperand &getOperand(unsigned Num) {
493    assert(Num < Operands.size() && "Invalid child # of SDNode!");
494    return Operands[Num];
495  }
496
497  const SDOperand &getOperand(unsigned Num) const {
498    assert(Num < Operands.size() && "Invalid child # of SDNode!");
499    return Operands[Num];
500  }
501  typedef std::vector<SDOperand>::const_iterator op_iterator;
502  op_iterator op_begin() const { return Operands.begin(); }
503  op_iterator op_end() const { return Operands.end(); }
504
505
506  /// getNumValues - Return the number of values defined/returned by this
507  /// operator.
508  ///
509  unsigned getNumValues() const { return Values.size(); }
510
511  /// getValueType - Return the type of a specified result.
512  ///
513  MVT::ValueType getValueType(unsigned ResNo) const {
514    assert(ResNo < Values.size() && "Illegal result number!");
515    return Values[ResNo];
516  }
517
518  typedef std::vector<MVT::ValueType>::const_iterator value_iterator;
519  value_iterator value_begin() const { return Values.begin(); }
520  value_iterator value_end() const { return Values.end(); }
521
522  /// getOperationName - Return the opcode of this operation for printing.
523  ///
524  const char* getOperationName() const;
525  void dump() const;
526
527  static bool classof(const SDNode *) { return true; }
528
529
530  /// setAdjCallChain - This method should only be used by the legalizer.
531  void setAdjCallChain(SDOperand N);
532
533protected:
534  friend class SelectionDAG;
535
536  SDNode(unsigned NT, MVT::ValueType VT) : NodeType(NT), NodeDepth(1) {
537    Values.reserve(1);
538    Values.push_back(VT);
539  }
540  SDNode(unsigned NT, SDOperand Op)
541    : NodeType(NT), NodeDepth(Op.Val->getNodeDepth()+1) {
542    Operands.reserve(1); Operands.push_back(Op);
543    Op.Val->Uses.push_back(this);
544  }
545  SDNode(unsigned NT, SDOperand N1, SDOperand N2)
546    : NodeType(NT) {
547    if (N1.Val->getNodeDepth() > N2.Val->getNodeDepth())
548      NodeDepth = N1.Val->getNodeDepth()+1;
549    else
550      NodeDepth = N2.Val->getNodeDepth()+1;
551    Operands.reserve(2); Operands.push_back(N1); Operands.push_back(N2);
552    N1.Val->Uses.push_back(this); N2.Val->Uses.push_back(this);
553  }
554  SDNode(unsigned NT, SDOperand N1, SDOperand N2, SDOperand N3)
555    : NodeType(NT) {
556    unsigned ND = N1.Val->getNodeDepth();
557    if (ND < N2.Val->getNodeDepth())
558      ND = N2.Val->getNodeDepth();
559    if (ND < N3.Val->getNodeDepth())
560      ND = N3.Val->getNodeDepth();
561    NodeDepth = ND+1;
562
563    Operands.reserve(3); Operands.push_back(N1); Operands.push_back(N2);
564    Operands.push_back(N3);
565    N1.Val->Uses.push_back(this); N2.Val->Uses.push_back(this);
566    N3.Val->Uses.push_back(this);
567  }
568  SDNode(unsigned NT, SDOperand N1, SDOperand N2, SDOperand N3, SDOperand N4)
569    : NodeType(NT) {
570    unsigned ND = N1.Val->getNodeDepth();
571    if (ND < N2.Val->getNodeDepth())
572      ND = N2.Val->getNodeDepth();
573    if (ND < N3.Val->getNodeDepth())
574      ND = N3.Val->getNodeDepth();
575    if (ND < N4.Val->getNodeDepth())
576      ND = N4.Val->getNodeDepth();
577    NodeDepth = ND+1;
578
579    Operands.reserve(4); Operands.push_back(N1); Operands.push_back(N2);
580    Operands.push_back(N3); Operands.push_back(N4);
581    N1.Val->Uses.push_back(this); N2.Val->Uses.push_back(this);
582    N3.Val->Uses.push_back(this); N4.Val->Uses.push_back(this);
583  }
584  SDNode(unsigned NT, std::vector<SDOperand> &Nodes) : NodeType(NT) {
585    Operands.swap(Nodes);
586    unsigned ND = 0;
587    for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
588      Operands[i].Val->Uses.push_back(this);
589      if (ND < Operands[i].Val->getNodeDepth())
590        ND = Operands[i].Val->getNodeDepth();
591    }
592    NodeDepth = ND+1;
593  }
594
595  virtual ~SDNode() {
596    // FIXME: Drop uses.
597  }
598
599  void setValueTypes(MVT::ValueType VT) {
600    Values.reserve(1);
601    Values.push_back(VT);
602  }
603  void setValueTypes(MVT::ValueType VT1, MVT::ValueType VT2) {
604    Values.reserve(2);
605    Values.push_back(VT1);
606    Values.push_back(VT2);
607  }
608  /// Note: this method destroys the vector passed in.
609  void setValueTypes(std::vector<MVT::ValueType> &VTs) {
610    std::swap(Values, VTs);
611  }
612
613  void removeUser(SDNode *User) {
614    // Remove this user from the operand's use list.
615    for (unsigned i = Uses.size(); ; --i) {
616      assert(i != 0 && "Didn't find user!");
617      if (Uses[i-1] == User) {
618        Uses.erase(Uses.begin()+i-1);
619        break;
620      }
621    }
622  }
623};
624
625
626// Define inline functions from the SDOperand class.
627
628inline unsigned SDOperand::getOpcode() const {
629  return Val->getOpcode();
630}
631inline unsigned SDOperand::getNodeDepth() const {
632  return Val->getNodeDepth();
633}
634inline MVT::ValueType SDOperand::getValueType() const {
635  return Val->getValueType(ResNo);
636}
637inline unsigned SDOperand::getNumOperands() const {
638  return Val->getNumOperands();
639}
640inline const SDOperand &SDOperand::getOperand(unsigned i) const {
641  return Val->getOperand(i);
642}
643inline bool SDOperand::hasOneUse() const {
644  return Val->hasNUsesOfValue(1, ResNo);
645}
646
647
648class ConstantSDNode : public SDNode {
649  uint64_t Value;
650protected:
651  friend class SelectionDAG;
652  ConstantSDNode(uint64_t val, MVT::ValueType VT)
653    : SDNode(ISD::Constant, VT), Value(val) {
654  }
655public:
656
657  uint64_t getValue() const { return Value; }
658
659  int64_t getSignExtended() const {
660    unsigned Bits = MVT::getSizeInBits(getValueType(0));
661    return ((int64_t)Value << (64-Bits)) >> (64-Bits);
662  }
663
664  bool isNullValue() const { return Value == 0; }
665  bool isAllOnesValue() const {
666    int NumBits = MVT::getSizeInBits(getValueType(0));
667    if (NumBits == 64) return Value+1 == 0;
668    return Value == (1ULL << NumBits)-1;
669  }
670
671  static bool classof(const ConstantSDNode *) { return true; }
672  static bool classof(const SDNode *N) {
673    return N->getOpcode() == ISD::Constant;
674  }
675};
676
677class ConstantFPSDNode : public SDNode {
678  double Value;
679protected:
680  friend class SelectionDAG;
681  ConstantFPSDNode(double val, MVT::ValueType VT)
682    : SDNode(ISD::ConstantFP, VT), Value(val) {
683  }
684public:
685
686  double getValue() const { return Value; }
687
688  /// isExactlyValue - We don't rely on operator== working on double values, as
689  /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
690  /// As such, this method can be used to do an exact bit-for-bit comparison of
691  /// two floating point values.
692  bool isExactlyValue(double V) const {
693    union {
694      double V;
695      uint64_t I;
696    } T1;
697    T1.V = Value;
698    union {
699      double V;
700      uint64_t I;
701    } T2;
702    T2.V = V;
703    return T1.I == T2.I;
704  }
705
706  static bool classof(const ConstantFPSDNode *) { return true; }
707  static bool classof(const SDNode *N) {
708    return N->getOpcode() == ISD::ConstantFP;
709  }
710};
711
712class GlobalAddressSDNode : public SDNode {
713  GlobalValue *TheGlobal;
714protected:
715  friend class SelectionDAG;
716  GlobalAddressSDNode(const GlobalValue *GA, MVT::ValueType VT)
717    : SDNode(ISD::GlobalAddress, VT) {
718    TheGlobal = const_cast<GlobalValue*>(GA);
719  }
720public:
721
722  GlobalValue *getGlobal() const { return TheGlobal; }
723
724  static bool classof(const GlobalAddressSDNode *) { return true; }
725  static bool classof(const SDNode *N) {
726    return N->getOpcode() == ISD::GlobalAddress;
727  }
728};
729
730
731class FrameIndexSDNode : public SDNode {
732  int FI;
733protected:
734  friend class SelectionDAG;
735  FrameIndexSDNode(int fi, MVT::ValueType VT)
736    : SDNode(ISD::FrameIndex, VT), FI(fi) {}
737public:
738
739  int getIndex() const { return FI; }
740
741  static bool classof(const FrameIndexSDNode *) { return true; }
742  static bool classof(const SDNode *N) {
743    return N->getOpcode() == ISD::FrameIndex;
744  }
745};
746
747class ConstantPoolSDNode : public SDNode {
748  unsigned CPI;
749protected:
750  friend class SelectionDAG;
751  ConstantPoolSDNode(unsigned cpi, MVT::ValueType VT)
752    : SDNode(ISD::ConstantPool, VT), CPI(cpi) {}
753public:
754
755  unsigned getIndex() const { return CPI; }
756
757  static bool classof(const ConstantPoolSDNode *) { return true; }
758  static bool classof(const SDNode *N) {
759    return N->getOpcode() == ISD::ConstantPool;
760  }
761};
762
763class BasicBlockSDNode : public SDNode {
764  MachineBasicBlock *MBB;
765protected:
766  friend class SelectionDAG;
767  BasicBlockSDNode(MachineBasicBlock *mbb)
768    : SDNode(ISD::BasicBlock, MVT::Other), MBB(mbb) {}
769public:
770
771  MachineBasicBlock *getBasicBlock() const { return MBB; }
772
773  static bool classof(const BasicBlockSDNode *) { return true; }
774  static bool classof(const SDNode *N) {
775    return N->getOpcode() == ISD::BasicBlock;
776  }
777};
778
779class SrcValueSDNode : public SDNode {
780  const Value *V;
781  int offset;
782protected:
783  friend class SelectionDAG;
784  SrcValueSDNode(const Value* v, int o)
785    : SDNode(ISD::SRCVALUE, MVT::Other), V(v), offset(o) {}
786
787public:
788  const Value *getValue() const { return V; }
789  int getOffset() const { return offset; }
790
791  static bool classof(const SrcValueSDNode *) { return true; }
792  static bool classof(const SDNode *N) {
793    return N->getOpcode() == ISD::SRCVALUE;
794  }
795};
796
797
798class RegSDNode : public SDNode {
799  unsigned Reg;
800protected:
801  friend class SelectionDAG;
802  RegSDNode(unsigned Opc, SDOperand Chain, SDOperand Src, unsigned reg)
803    : SDNode(Opc, Chain, Src), Reg(reg) {
804  }
805  RegSDNode(unsigned Opc, SDOperand Chain, unsigned reg)
806    : SDNode(Opc, Chain), Reg(reg) {}
807public:
808
809  unsigned getReg() const { return Reg; }
810
811  static bool classof(const RegSDNode *) { return true; }
812  static bool classof(const SDNode *N) {
813    return N->getOpcode() == ISD::CopyToReg ||
814           N->getOpcode() == ISD::CopyFromReg ||
815           N->getOpcode() == ISD::ImplicitDef;
816  }
817};
818
819class ExternalSymbolSDNode : public SDNode {
820  const char *Symbol;
821protected:
822  friend class SelectionDAG;
823  ExternalSymbolSDNode(const char *Sym, MVT::ValueType VT)
824    : SDNode(ISD::ExternalSymbol, VT), Symbol(Sym) {
825    }
826public:
827
828  const char *getSymbol() const { return Symbol; }
829
830  static bool classof(const ExternalSymbolSDNode *) { return true; }
831  static bool classof(const SDNode *N) {
832    return N->getOpcode() == ISD::ExternalSymbol;
833  }
834};
835
836class CondCodeSDNode : public SDNode {
837  ISD::CondCode Condition;
838protected:
839  friend class SelectionDAG;
840  CondCodeSDNode(ISD::CondCode Cond)
841    : SDNode(ISD::CONDCODE, MVT::Other), Condition(Cond) {
842  }
843public:
844
845  ISD::CondCode get() const { return Condition; }
846
847  static bool classof(const CondCodeSDNode *) { return true; }
848  static bool classof(const SDNode *N) {
849    return N->getOpcode() == ISD::CONDCODE;
850  }
851};
852
853/// VTSDNode - This class is used to represent MVT::ValueType's, which are used
854/// to parameterize some operations.
855class VTSDNode : public SDNode {
856  MVT::ValueType ValueType;
857protected:
858  friend class SelectionDAG;
859  VTSDNode(MVT::ValueType VT)
860    : SDNode(ISD::VALUETYPE, MVT::Other), ValueType(VT) {}
861public:
862
863  MVT::ValueType getVT() const { return ValueType; }
864
865  static bool classof(const VTSDNode *) { return true; }
866  static bool classof(const SDNode *N) {
867    return N->getOpcode() == ISD::VALUETYPE;
868  }
869};
870
871
872class SDNodeIterator : public forward_iterator<SDNode, ptrdiff_t> {
873  SDNode *Node;
874  unsigned Operand;
875
876  SDNodeIterator(SDNode *N, unsigned Op) : Node(N), Operand(Op) {}
877public:
878  bool operator==(const SDNodeIterator& x) const {
879    return Operand == x.Operand;
880  }
881  bool operator!=(const SDNodeIterator& x) const { return !operator==(x); }
882
883  const SDNodeIterator &operator=(const SDNodeIterator &I) {
884    assert(I.Node == Node && "Cannot assign iterators to two different nodes!");
885    Operand = I.Operand;
886    return *this;
887  }
888
889  pointer operator*() const {
890    return Node->getOperand(Operand).Val;
891  }
892  pointer operator->() const { return operator*(); }
893
894  SDNodeIterator& operator++() {                // Preincrement
895    ++Operand;
896    return *this;
897  }
898  SDNodeIterator operator++(int) { // Postincrement
899    SDNodeIterator tmp = *this; ++*this; return tmp;
900  }
901
902  static SDNodeIterator begin(SDNode *N) { return SDNodeIterator(N, 0); }
903  static SDNodeIterator end  (SDNode *N) {
904    return SDNodeIterator(N, N->getNumOperands());
905  }
906
907  unsigned getOperand() const { return Operand; }
908  const SDNode *getNode() const { return Node; }
909};
910
911template <> struct GraphTraits<SDNode*> {
912  typedef SDNode NodeType;
913  typedef SDNodeIterator ChildIteratorType;
914  static inline NodeType *getEntryNode(SDNode *N) { return N; }
915  static inline ChildIteratorType child_begin(NodeType *N) {
916    return SDNodeIterator::begin(N);
917  }
918  static inline ChildIteratorType child_end(NodeType *N) {
919    return SDNodeIterator::end(N);
920  }
921};
922
923} // end llvm namespace
924
925#endif
926