SelectionDAGNodes.h revision df0f659517f688d18922d5b377380366c8a6dfe9
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/iterator"
26#include "llvm/Support/DataTypes.h"
27#include <cassert>
28#include <vector>
29
30namespace llvm {
31
32class SelectionDAG;
33class GlobalValue;
34class MachineBasicBlock;
35class SDNode;
36template <typename T> struct simplify_type;
37template <typename T> struct ilist_traits;
38template<typename NodeTy, typename Traits> class iplist;
39template<typename NodeTy> class ilist_iterator;
40
41/// ISD namespace - This namespace contains an enum which represents all of the
42/// SelectionDAG node types and value types.
43///
44namespace ISD {
45  //===--------------------------------------------------------------------===//
46  /// ISD::NodeType enum - This enum defines all of the operators valid in a
47  /// SelectionDAG.
48  ///
49  enum NodeType {
50    // EntryToken - This is the marker used to indicate the start of the region.
51    EntryToken,
52
53    // Token factor - This node takes multiple tokens as input and produces a
54    // single token result.  This is used to represent the fact that the operand
55    // operators are independent of each other.
56    TokenFactor,
57
58    // AssertSext, AssertZext - These nodes record if a register contains a
59    // value that has already been zero or sign extended from a narrower type.
60    // These nodes take two operands.  The first is the node that has already
61    // been extended, and the second is a value type node indicating the width
62    // of the extension
63    AssertSext, AssertZext,
64
65    // Various leaf nodes.
66    Constant, ConstantFP, STRING,
67    GlobalAddress, FrameIndex, ConstantPool,
68    BasicBlock, ExternalSymbol, VALUETYPE, CONDCODE, Register,
69
70    // ConstantVec works like Constant or ConstantFP, except that it is not a
71    // leaf node.  All operands are either Constant or ConstantFP nodes.
72    ConstantVec,
73
74    // TargetConstant - Like Constant, but the DAG does not do any folding or
75    // simplification of the constant.  This is used by the DAG->DAG selector.
76    TargetConstant,
77
78    // TargetGlobalAddress - Like GlobalAddress, but the DAG does no folding or
79    // anything else with this node, and this is valid in the target-specific
80    // dag, turning into a GlobalAddress operand.
81    TargetGlobalAddress,
82    TargetFrameIndex,
83    TargetConstantPool,
84    TargetExternalSymbol,
85
86    // CopyToReg - This node has three operands: a chain, a register number to
87    // set to this value, and a value.
88    CopyToReg,
89
90    // CopyFromReg - This node indicates that the input value is a virtual or
91    // physical register that is defined outside of the scope of this
92    // SelectionDAG.  The register is available from the RegSDNode object.
93    CopyFromReg,
94
95    // UNDEF - An undefined node
96    UNDEF,
97
98    // EXTRACT_ELEMENT - This is used to get the first or second (determined by
99    // a Constant, which is required to be operand #1), element of the aggregate
100    // value specified as operand #0.  This is only for use before legalization,
101    // for values that will be broken into multiple registers.
102    EXTRACT_ELEMENT,
103
104    // BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.  Given
105    // two values of the same integer value type, this produces a value twice as
106    // big.  Like EXTRACT_ELEMENT, this can only be used before legalization.
107    BUILD_PAIR,
108
109    // MERGE_VALUES - This node takes multiple discrete operands and returns
110    // them all as its individual results.  This nodes has exactly the same
111    // number of inputs and outputs, and is only valid before legalization.
112    // This node is useful for some pieces of the code generator that want to
113    // think about a single node with multiple results, not multiple nodes.
114    MERGE_VALUES,
115
116    // Simple integer binary arithmetic operators.
117    ADD, SUB, MUL, SDIV, UDIV, SREM, UREM,
118
119    // Simple binary floating point operators.
120    FADD, FSUB, FMUL, FDIV, FREM,
121
122    // Simple abstract vector operators.  Unlike the integer and floating point
123    // binary operators, these nodes also take two additional operands:
124    // a constant element count, and a value type node indicating the type of
125    // the elements.  The order is op0, op1, count, type.  All vector opcodes,
126    // including VLOAD, must currently have count and type as their 3rd and 4th
127    // arguments.
128    VADD, VSUB, VMUL,
129
130    // MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing
131    // an unsigned/signed value of type i[2*n], then return the top part.
132    MULHU, MULHS,
133
134    // Bitwise operators.
135    AND, OR, XOR, SHL, SRA, SRL,
136
137    // Counting operators
138    CTTZ, CTLZ, CTPOP,
139
140    // Select
141    SELECT,
142
143    // Select with condition operator - This selects between a true value and
144    // a false value (ops #2 and #3) based on the boolean result of comparing
145    // the lhs and rhs (ops #0 and #1) of a conditional expression with the
146    // condition code in op #4, a CondCodeSDNode.
147    SELECT_CC,
148
149    // SetCC operator - This evaluates to a boolean (i1) true value if the
150    // condition is true.  The operands to this are the left and right operands
151    // to compare (ops #0, and #1) and the condition code to compare them with
152    // (op #2) as a CondCodeSDNode.
153    SETCC,
154
155    // ADD_PARTS/SUB_PARTS - These operators take two logical operands which are
156    // broken into a multiple pieces each, and return the resulting pieces of
157    // doing an atomic add/sub operation.  This is used to handle add/sub of
158    // expanded types.  The operation ordering is:
159    //       [Lo,Hi] = op [LoLHS,HiLHS], [LoRHS,HiRHS]
160    ADD_PARTS, SUB_PARTS,
161
162    // SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded
163    // integer shift operations, just like ADD/SUB_PARTS.  The operation
164    // ordering is:
165    //       [Lo,Hi] = op [LoLHS,HiLHS], Amt
166    SHL_PARTS, SRA_PARTS, SRL_PARTS,
167
168    // Conversion operators.  These are all single input single output
169    // operations.  For all of these, the result type must be strictly
170    // wider or narrower (depending on the operation) than the source
171    // type.
172
173    // SIGN_EXTEND - Used for integer types, replicating the sign bit
174    // into new bits.
175    SIGN_EXTEND,
176
177    // ZERO_EXTEND - Used for integer types, zeroing the new bits.
178    ZERO_EXTEND,
179
180    // ANY_EXTEND - Used for integer types.  The high bits are undefined.
181    ANY_EXTEND,
182
183    // TRUNCATE - Completely drop the high bits.
184    TRUNCATE,
185
186    // [SU]INT_TO_FP - These operators convert integers (whose interpreted sign
187    // depends on the first letter) to floating point.
188    SINT_TO_FP,
189    UINT_TO_FP,
190
191    // SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to
192    // sign extend a small value in a large integer register (e.g. sign
193    // extending the low 8 bits of a 32-bit register to fill the top 24 bits
194    // with the 7th bit).  The size of the smaller type is indicated by the 1th
195    // operand, a ValueType node.
196    SIGN_EXTEND_INREG,
197
198    // FP_TO_[US]INT - Convert a floating point value to a signed or unsigned
199    // integer.
200    FP_TO_SINT,
201    FP_TO_UINT,
202
203    // FP_ROUND - Perform a rounding operation from the current
204    // precision down to the specified precision (currently always 64->32).
205    FP_ROUND,
206
207    // FP_ROUND_INREG - This operator takes a floating point register, and
208    // rounds it to a floating point value.  It then promotes it and returns it
209    // in a register of the same size.  This operation effectively just discards
210    // excess precision.  The type to round down to is specified by the 1th
211    // operation, a VTSDNode (currently always 64->32->64).
212    FP_ROUND_INREG,
213
214    // FP_EXTEND - Extend a smaller FP type into a larger FP type.
215    FP_EXTEND,
216
217    // BIT_CONVERT - Theis operator converts between integer and FP values, as
218    // if one was stored to memory as integer and the other was loaded from the
219    // same address (or equivalently for vector format conversions, etc).  The
220    // source and result are required to have the same bit size (e.g.
221    // f32 <-> i32).  This can also be used for int-to-int or fp-to-fp
222    // conversions, but that is a noop, deleted by getNode().
223    BIT_CONVERT,
224
225    // FNEG, FABS, FSQRT, FSIN, FCOS - Perform unary floating point negation,
226    // absolute value, square root, sine and cosine operations.
227    FNEG, FABS, FSQRT, FSIN, FCOS,
228
229    // Other operators.  LOAD and STORE have token chains as their first
230    // operand, then the same operands as an LLVM load/store instruction, then a
231    // SRCVALUE node that provides alias analysis information.
232    LOAD, STORE,
233
234    // Abstract vector version of LOAD.  VLOAD has a token chain as the first
235    // operand, followed by a pointer operand, a constant element count, a value
236    // type node indicating the type of the elements, and a SRCVALUE node.
237    VLOAD,
238
239    // EXTLOAD, SEXTLOAD, ZEXTLOAD - These three operators all load a value from
240    // memory and extend them to a larger value (e.g. load a byte into a word
241    // register).  All three of these have four operands, a token chain, a
242    // pointer to load from, a SRCVALUE for alias analysis, and a VALUETYPE node
243    // indicating the type to load.
244    //
245    // SEXTLOAD loads the integer operand and sign extends it to a larger
246    //          integer result type.
247    // ZEXTLOAD loads the integer operand and zero extends it to a larger
248    //          integer result type.
249    // EXTLOAD  is used for two things: floating point extending loads, and
250    //          integer extending loads where it doesn't matter what the high
251    //          bits are set to.  The code generator is allowed to codegen this
252    //          into whichever operation is more efficient.
253    EXTLOAD, SEXTLOAD, ZEXTLOAD,
254
255    // TRUNCSTORE - This operators truncates (for integer) or rounds (for FP) a
256    // value and stores it to memory in one operation.  This can be used for
257    // either integer or floating point operands.  The first four operands of
258    // this are the same as a standard store.  The fifth is the ValueType to
259    // store it as (which will be smaller than the source value).
260    TRUNCSTORE,
261
262    // DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned
263    // to a specified boundary.  The first operand is the token chain, the
264    // second is the number of bytes to allocate, and the third is the alignment
265    // boundary.  The size is guaranteed to be a multiple of the stack
266    // alignment, and the alignment is guaranteed to be bigger than the stack
267    // alignment (if required) or 0 to get standard stack alignment.
268    DYNAMIC_STACKALLOC,
269
270    // Control flow instructions.  These all have token chains.
271
272    // BR - Unconditional branch.  The first operand is the chain
273    // operand, the second is the MBB to branch to.
274    BR,
275
276    // BRCOND - Conditional branch.  The first operand is the chain,
277    // the second is the condition, the third is the block to branch
278    // to if the condition is true.
279    BRCOND,
280
281    // BRCONDTWOWAY - Two-way conditional branch.  The first operand is the
282    // chain, the second is the condition, the third is the block to branch to
283    // if true, and the forth is the block to branch to if false.  Targets
284    // usually do not implement this, preferring to have legalize demote the
285    // operation to BRCOND/BR pairs when necessary.
286    BRCONDTWOWAY,
287
288    // BR_CC - Conditional branch.  The behavior is like that of SELECT_CC, in
289    // that the condition is represented as condition code, and two nodes to
290    // compare, rather than as a combined SetCC node.  The operands in order are
291    // chain, cc, lhs, rhs, block to branch to if condition is true.
292    BR_CC,
293
294    // BRTWOWAY_CC - Two-way conditional branch.  The operands in order are
295    // chain, cc, lhs, rhs, block to branch to if condition is true, block to
296    // branch to if condition is false.  Targets usually do not implement this,
297    // preferring to have legalize demote the operation to BRCOND/BR pairs.
298    BRTWOWAY_CC,
299
300    // RET - Return from function.  The first operand is the chain,
301    // and any subsequent operands are the return values for the
302    // function.  This operation can have variable number of operands.
303    RET,
304
305    // CALL - Call to a function pointer.  The first operand is the chain, the
306    // second is the destination function pointer (a GlobalAddress for a direct
307    // call).  Arguments have already been lowered to explicit DAGs according to
308    // the calling convention in effect here.  TAILCALL is the same as CALL, but
309    // the callee is known not to access the stack of the caller.
310    CALL,
311    TAILCALL,
312
313    // MEMSET/MEMCPY/MEMMOVE - The first operand is the chain, and the rest
314    // correspond to the operands of the LLVM intrinsic functions.  The only
315    // result is a token chain.  The alignment argument is guaranteed to be a
316    // Constant node.
317    MEMSET,
318    MEMMOVE,
319    MEMCPY,
320
321    // CALLSEQ_START/CALLSEQ_END - These operators mark the beginning and end of
322    // a call sequence, and carry arbitrary information that target might want
323    // to know.  The first operand is a chain, the rest are specified by the
324    // target and not touched by the DAG optimizers.
325    CALLSEQ_START,  // Beginning of a call sequence
326    CALLSEQ_END,    // End of a call sequence
327
328    // SRCVALUE - This corresponds to a Value*, and is used to associate memory
329    // locations with their value.  This allows one use alias analysis
330    // information in the backend.
331    SRCVALUE,
332
333    // PCMARKER - This corresponds to the pcmarker intrinsic.
334    PCMARKER,
335
336    // READCYCLECOUNTER - This corresponds to the readcyclecounter intrinsic.
337    // The only operand is a chain and a value and a chain are produced.  The
338    // value is the contents of the architecture specific cycle counter like
339    // register (or other high accuracy low latency clock source)
340    READCYCLECOUNTER,
341
342    // READPORT, WRITEPORT, READIO, WRITEIO - These correspond to the LLVM
343    // intrinsics of the same name.  The first operand is a token chain, the
344    // other operands match the intrinsic.  These produce a token chain in
345    // addition to a value (if any).
346    READPORT, WRITEPORT, READIO, WRITEIO,
347
348    // HANDLENODE node - Used as a handle for various purposes.
349    HANDLENODE,
350
351    // LOCATION - This node is used to represent a source location for debug
352    // info.  It takes token chain as input, then a line number, then a column
353    // number, then a filename, then a working dir.  It produces a token chain
354    // as output.
355    LOCATION,
356
357    // DEBUG_LOC - This node is used to represent source line information
358    // embedded in the code.  It takes a token chain as input, then a line
359    // number, then a column then a file id (provided by MachineDebugInfo.) It
360    // produces a token chain as output.
361    DEBUG_LOC,
362
363    // DEBUG_LABEL - This node is used to mark a location in the code where a
364    // label should be generated for use by the debug information.  It takes a
365    // token chain as input and then a unique id (provided by MachineDebugInfo.)
366    // It produces a token chain as output.
367    DEBUG_LABEL,
368
369    // BUILTIN_OP_END - This must be the last enum value in this list.
370    BUILTIN_OP_END,
371  };
372
373  //===--------------------------------------------------------------------===//
374  /// ISD::CondCode enum - These are ordered carefully to make the bitfields
375  /// below work out, when considering SETFALSE (something that never exists
376  /// dynamically) as 0.  "U" -> Unsigned (for integer operands) or Unordered
377  /// (for floating point), "L" -> Less than, "G" -> Greater than, "E" -> Equal
378  /// to.  If the "N" column is 1, the result of the comparison is undefined if
379  /// the input is a NAN.
380  ///
381  /// All of these (except for the 'always folded ops') should be handled for
382  /// floating point.  For integer, only the SETEQ,SETNE,SETLT,SETLE,SETGT,
383  /// SETGE,SETULT,SETULE,SETUGT, and SETUGE opcodes are used.
384  ///
385  /// Note that these are laid out in a specific order to allow bit-twiddling
386  /// to transform conditions.
387  enum CondCode {
388    // Opcode          N U L G E       Intuitive operation
389    SETFALSE,      //    0 0 0 0       Always false (always folded)
390    SETOEQ,        //    0 0 0 1       True if ordered and equal
391    SETOGT,        //    0 0 1 0       True if ordered and greater than
392    SETOGE,        //    0 0 1 1       True if ordered and greater than or equal
393    SETOLT,        //    0 1 0 0       True if ordered and less than
394    SETOLE,        //    0 1 0 1       True if ordered and less than or equal
395    SETONE,        //    0 1 1 0       True if ordered and operands are unequal
396    SETO,          //    0 1 1 1       True if ordered (no nans)
397    SETUO,         //    1 0 0 0       True if unordered: isnan(X) | isnan(Y)
398    SETUEQ,        //    1 0 0 1       True if unordered or equal
399    SETUGT,        //    1 0 1 0       True if unordered or greater than
400    SETUGE,        //    1 0 1 1       True if unordered, greater than, or equal
401    SETULT,        //    1 1 0 0       True if unordered or less than
402    SETULE,        //    1 1 0 1       True if unordered, less than, or equal
403    SETUNE,        //    1 1 1 0       True if unordered or not equal
404    SETTRUE,       //    1 1 1 1       Always true (always folded)
405    // Don't care operations: undefined if the input is a nan.
406    SETFALSE2,     //  1 X 0 0 0       Always false (always folded)
407    SETEQ,         //  1 X 0 0 1       True if equal
408    SETGT,         //  1 X 0 1 0       True if greater than
409    SETGE,         //  1 X 0 1 1       True if greater than or equal
410    SETLT,         //  1 X 1 0 0       True if less than
411    SETLE,         //  1 X 1 0 1       True if less than or equal
412    SETNE,         //  1 X 1 1 0       True if not equal
413    SETTRUE2,      //  1 X 1 1 1       Always true (always folded)
414
415    SETCC_INVALID,      // Marker value.
416  };
417
418  /// isSignedIntSetCC - Return true if this is a setcc instruction that
419  /// performs a signed comparison when used with integer operands.
420  inline bool isSignedIntSetCC(CondCode Code) {
421    return Code == SETGT || Code == SETGE || Code == SETLT || Code == SETLE;
422  }
423
424  /// isUnsignedIntSetCC - Return true if this is a setcc instruction that
425  /// performs an unsigned comparison when used with integer operands.
426  inline bool isUnsignedIntSetCC(CondCode Code) {
427    return Code == SETUGT || Code == SETUGE || Code == SETULT || Code == SETULE;
428  }
429
430  /// isTrueWhenEqual - Return true if the specified condition returns true if
431  /// the two operands to the condition are equal.  Note that if one of the two
432  /// operands is a NaN, this value is meaningless.
433  inline bool isTrueWhenEqual(CondCode Cond) {
434    return ((int)Cond & 1) != 0;
435  }
436
437  /// getUnorderedFlavor - This function returns 0 if the condition is always
438  /// false if an operand is a NaN, 1 if the condition is always true if the
439  /// operand is a NaN, and 2 if the condition is undefined if the operand is a
440  /// NaN.
441  inline unsigned getUnorderedFlavor(CondCode Cond) {
442    return ((int)Cond >> 3) & 3;
443  }
444
445  /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
446  /// 'op' is a valid SetCC operation.
447  CondCode getSetCCInverse(CondCode Operation, bool isInteger);
448
449  /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
450  /// when given the operation for (X op Y).
451  CondCode getSetCCSwappedOperands(CondCode Operation);
452
453  /// getSetCCOrOperation - Return the result of a logical OR between different
454  /// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This
455  /// function returns SETCC_INVALID if it is not possible to represent the
456  /// resultant comparison.
457  CondCode getSetCCOrOperation(CondCode Op1, CondCode Op2, bool isInteger);
458
459  /// getSetCCAndOperation - Return the result of a logical AND between
460  /// different comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
461  /// function returns SETCC_INVALID if it is not possible to represent the
462  /// resultant comparison.
463  CondCode getSetCCAndOperation(CondCode Op1, CondCode Op2, bool isInteger);
464}  // end llvm::ISD namespace
465
466
467//===----------------------------------------------------------------------===//
468/// SDOperand - Unlike LLVM values, Selection DAG nodes may return multiple
469/// values as the result of a computation.  Many nodes return multiple values,
470/// from loads (which define a token and a return value) to ADDC (which returns
471/// a result and a carry value), to calls (which may return an arbitrary number
472/// of values).
473///
474/// As such, each use of a SelectionDAG computation must indicate the node that
475/// computes it as well as which return value to use from that node.  This pair
476/// of information is represented with the SDOperand value type.
477///
478class SDOperand {
479public:
480  SDNode *Val;        // The node defining the value we are using.
481  unsigned ResNo;     // Which return value of the node we are using.
482
483  SDOperand() : Val(0) {}
484  SDOperand(SDNode *val, unsigned resno) : Val(val), ResNo(resno) {}
485
486  bool operator==(const SDOperand &O) const {
487    return Val == O.Val && ResNo == O.ResNo;
488  }
489  bool operator!=(const SDOperand &O) const {
490    return !operator==(O);
491  }
492  bool operator<(const SDOperand &O) const {
493    return Val < O.Val || (Val == O.Val && ResNo < O.ResNo);
494  }
495
496  SDOperand getValue(unsigned R) const {
497    return SDOperand(Val, R);
498  }
499
500  /// getValueType - Return the ValueType of the referenced return value.
501  ///
502  inline MVT::ValueType getValueType() const;
503
504  // Forwarding methods - These forward to the corresponding methods in SDNode.
505  inline unsigned getOpcode() const;
506  inline unsigned getNodeDepth() const;
507  inline unsigned getNumOperands() const;
508  inline const SDOperand &getOperand(unsigned i) const;
509  inline bool isTargetOpcode() const;
510  inline unsigned getTargetOpcode() const;
511
512  /// hasOneUse - Return true if there is exactly one operation using this
513  /// result value of the defining operator.
514  inline bool hasOneUse() const;
515};
516
517
518/// simplify_type specializations - Allow casting operators to work directly on
519/// SDOperands as if they were SDNode*'s.
520template<> struct simplify_type<SDOperand> {
521  typedef SDNode* SimpleType;
522  static SimpleType getSimplifiedValue(const SDOperand &Val) {
523    return static_cast<SimpleType>(Val.Val);
524  }
525};
526template<> struct simplify_type<const SDOperand> {
527  typedef SDNode* SimpleType;
528  static SimpleType getSimplifiedValue(const SDOperand &Val) {
529    return static_cast<SimpleType>(Val.Val);
530  }
531};
532
533
534/// SDNode - Represents one node in the SelectionDAG.
535///
536class SDNode {
537  /// NodeType - The operation that this node performs.
538  ///
539  unsigned short NodeType;
540
541  /// NodeDepth - Node depth is defined as MAX(Node depth of children)+1.  This
542  /// means that leaves have a depth of 1, things that use only leaves have a
543  /// depth of 2, etc.
544  unsigned short NodeDepth;
545
546  /// OperandList - The values that are used by this operation.
547  ///
548  SDOperand *OperandList;
549
550  /// ValueList - The types of the values this node defines.  SDNode's may
551  /// define multiple values simultaneously.
552  MVT::ValueType *ValueList;
553
554  /// NumOperands/NumValues - The number of entries in the Operand/Value list.
555  unsigned short NumOperands, NumValues;
556
557  /// Prev/Next pointers - These pointers form the linked list of of the
558  /// AllNodes list in the current DAG.
559  SDNode *Prev, *Next;
560  friend struct ilist_traits<SDNode>;
561
562  /// Uses - These are all of the SDNode's that use a value produced by this
563  /// node.
564  std::vector<SDNode*> Uses;
565public:
566  virtual ~SDNode() {
567    assert(NumOperands == 0 && "Operand list not cleared before deletion");
568  }
569
570  //===--------------------------------------------------------------------===//
571  //  Accessors
572  //
573  unsigned getOpcode()  const { return NodeType; }
574  bool isTargetOpcode() const { return NodeType >= ISD::BUILTIN_OP_END; }
575  unsigned getTargetOpcode() const {
576    assert(isTargetOpcode() && "Not a target opcode!");
577    return NodeType - ISD::BUILTIN_OP_END;
578  }
579
580  size_t use_size() const { return Uses.size(); }
581  bool use_empty() const { return Uses.empty(); }
582  bool hasOneUse() const { return Uses.size() == 1; }
583
584  /// getNodeDepth - Return the distance from this node to the leaves in the
585  /// graph.  The leaves have a depth of 1.
586  unsigned getNodeDepth() const { return NodeDepth; }
587
588  typedef std::vector<SDNode*>::const_iterator use_iterator;
589  use_iterator use_begin() const { return Uses.begin(); }
590  use_iterator use_end() const { return Uses.end(); }
591
592  /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
593  /// indicated value.  This method ignores uses of other values defined by this
594  /// operation.
595  bool hasNUsesOfValue(unsigned NUses, unsigned Value);
596
597  /// getNumOperands - Return the number of values used by this operation.
598  ///
599  unsigned getNumOperands() const { return NumOperands; }
600
601  const SDOperand &getOperand(unsigned Num) const {
602    assert(Num < NumOperands && "Invalid child # of SDNode!");
603    return OperandList[Num];
604  }
605  typedef const SDOperand* op_iterator;
606  op_iterator op_begin() const { return OperandList; }
607  op_iterator op_end() const { return OperandList+NumOperands; }
608
609
610  /// getNumValues - Return the number of values defined/returned by this
611  /// operator.
612  ///
613  unsigned getNumValues() const { return NumValues; }
614
615  /// getValueType - Return the type of a specified result.
616  ///
617  MVT::ValueType getValueType(unsigned ResNo) const {
618    assert(ResNo < NumValues && "Illegal result number!");
619    return ValueList[ResNo];
620  }
621
622  typedef const MVT::ValueType* value_iterator;
623  value_iterator value_begin() const { return ValueList; }
624  value_iterator value_end() const { return ValueList+NumValues; }
625
626  /// getOperationName - Return the opcode of this operation for printing.
627  ///
628  const char* getOperationName(const SelectionDAG *G = 0) const;
629  void dump() const;
630  void dump(const SelectionDAG *G) const;
631
632  static bool classof(const SDNode *) { return true; }
633
634
635  /// setAdjCallChain - This method should only be used by the legalizer.
636  void setAdjCallChain(SDOperand N);
637
638protected:
639  friend class SelectionDAG;
640
641  /// getValueTypeList - Return a pointer to the specified value type.
642  ///
643  static MVT::ValueType *getValueTypeList(MVT::ValueType VT);
644
645  SDNode(unsigned NT, MVT::ValueType VT) : NodeType(NT), NodeDepth(1) {
646    OperandList = 0; NumOperands = 0;
647    ValueList = getValueTypeList(VT);
648    NumValues = 1;
649    Prev = 0; Next = 0;
650  }
651  SDNode(unsigned NT, SDOperand Op)
652    : NodeType(NT), NodeDepth(Op.Val->getNodeDepth()+1) {
653    OperandList = new SDOperand[1];
654    OperandList[0] = Op;
655    NumOperands = 1;
656    Op.Val->Uses.push_back(this);
657    ValueList = 0;
658    NumValues = 0;
659    Prev = 0; Next = 0;
660  }
661  SDNode(unsigned NT, SDOperand N1, SDOperand N2)
662    : NodeType(NT) {
663    if (N1.Val->getNodeDepth() > N2.Val->getNodeDepth())
664      NodeDepth = N1.Val->getNodeDepth()+1;
665    else
666      NodeDepth = N2.Val->getNodeDepth()+1;
667    OperandList = new SDOperand[2];
668    OperandList[0] = N1;
669    OperandList[1] = N2;
670    NumOperands = 2;
671    N1.Val->Uses.push_back(this); N2.Val->Uses.push_back(this);
672    ValueList = 0;
673    NumValues = 0;
674    Prev = 0; Next = 0;
675  }
676  SDNode(unsigned NT, SDOperand N1, SDOperand N2, SDOperand N3)
677    : NodeType(NT) {
678    unsigned ND = N1.Val->getNodeDepth();
679    if (ND < N2.Val->getNodeDepth())
680      ND = N2.Val->getNodeDepth();
681    if (ND < N3.Val->getNodeDepth())
682      ND = N3.Val->getNodeDepth();
683    NodeDepth = ND+1;
684
685    OperandList = new SDOperand[3];
686    OperandList[0] = N1;
687    OperandList[1] = N2;
688    OperandList[2] = N3;
689    NumOperands = 3;
690
691    N1.Val->Uses.push_back(this); N2.Val->Uses.push_back(this);
692    N3.Val->Uses.push_back(this);
693    ValueList = 0;
694    NumValues = 0;
695    Prev = 0; Next = 0;
696  }
697  SDNode(unsigned NT, SDOperand N1, SDOperand N2, SDOperand N3, SDOperand N4)
698    : NodeType(NT) {
699    unsigned ND = N1.Val->getNodeDepth();
700    if (ND < N2.Val->getNodeDepth())
701      ND = N2.Val->getNodeDepth();
702    if (ND < N3.Val->getNodeDepth())
703      ND = N3.Val->getNodeDepth();
704    if (ND < N4.Val->getNodeDepth())
705      ND = N4.Val->getNodeDepth();
706    NodeDepth = ND+1;
707
708    OperandList = new SDOperand[4];
709    OperandList[0] = N1;
710    OperandList[1] = N2;
711    OperandList[2] = N3;
712    OperandList[3] = N4;
713    NumOperands = 4;
714
715    N1.Val->Uses.push_back(this); N2.Val->Uses.push_back(this);
716    N3.Val->Uses.push_back(this); N4.Val->Uses.push_back(this);
717    ValueList = 0;
718    NumValues = 0;
719    Prev = 0; Next = 0;
720  }
721  SDNode(unsigned Opc, const std::vector<SDOperand> &Nodes) : NodeType(Opc) {
722    NumOperands = Nodes.size();
723    OperandList = new SDOperand[NumOperands];
724
725    unsigned ND = 0;
726    for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
727      OperandList[i] = Nodes[i];
728      SDNode *N = OperandList[i].Val;
729      N->Uses.push_back(this);
730      if (ND < N->getNodeDepth()) ND = N->getNodeDepth();
731    }
732    NodeDepth = ND+1;
733    ValueList = 0;
734    NumValues = 0;
735    Prev = 0; Next = 0;
736  }
737
738  /// MorphNodeTo - This clears the return value and operands list, and sets the
739  /// opcode of the node to the specified value.  This should only be used by
740  /// the SelectionDAG class.
741  void MorphNodeTo(unsigned Opc) {
742    NodeType = Opc;
743    ValueList = 0;
744    NumValues = 0;
745
746    // Clear the operands list, updating used nodes to remove this from their
747    // use list.
748    for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
749      I->Val->removeUser(this);
750    delete [] OperandList;
751    OperandList = 0;
752    NumOperands = 0;
753  }
754
755  void setValueTypes(MVT::ValueType VT) {
756    assert(NumValues == 0 && "Should not have values yet!");
757    ValueList = getValueTypeList(VT);
758    NumValues = 1;
759  }
760  void setValueTypes(MVT::ValueType *List, unsigned NumVal) {
761    assert(NumValues == 0 && "Should not have values yet!");
762    ValueList = List;
763    NumValues = NumVal;
764  }
765
766  void setOperands(SDOperand Op0) {
767    assert(NumOperands == 0 && "Should not have operands yet!");
768    OperandList = new SDOperand[1];
769    OperandList[0] = Op0;
770    NumOperands = 1;
771    Op0.Val->Uses.push_back(this);
772  }
773  void setOperands(SDOperand Op0, SDOperand Op1) {
774    assert(NumOperands == 0 && "Should not have operands yet!");
775    OperandList = new SDOperand[2];
776    OperandList[0] = Op0;
777    OperandList[1] = Op1;
778    NumOperands = 2;
779    Op0.Val->Uses.push_back(this); Op1.Val->Uses.push_back(this);
780  }
781  void setOperands(SDOperand Op0, SDOperand Op1, SDOperand Op2) {
782    assert(NumOperands == 0 && "Should not have operands yet!");
783    OperandList = new SDOperand[3];
784    OperandList[0] = Op0;
785    OperandList[1] = Op1;
786    OperandList[2] = Op2;
787    NumOperands = 3;
788    Op0.Val->Uses.push_back(this); Op1.Val->Uses.push_back(this);
789    Op2.Val->Uses.push_back(this);
790  }
791  void setOperands(SDOperand Op0, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
792    assert(NumOperands == 0 && "Should not have operands yet!");
793    OperandList = new SDOperand[4];
794    OperandList[0] = Op0;
795    OperandList[1] = Op1;
796    OperandList[2] = Op2;
797    OperandList[3] = Op3;
798    NumOperands = 4;
799    Op0.Val->Uses.push_back(this); Op1.Val->Uses.push_back(this);
800    Op2.Val->Uses.push_back(this); Op3.Val->Uses.push_back(this);
801  }
802  void setOperands(SDOperand Op0, SDOperand Op1, SDOperand Op2, SDOperand Op3,
803                   SDOperand Op4) {
804    assert(NumOperands == 0 && "Should not have operands yet!");
805    OperandList = new SDOperand[5];
806    OperandList[0] = Op0;
807    OperandList[1] = Op1;
808    OperandList[2] = Op2;
809    OperandList[3] = Op3;
810    OperandList[4] = Op4;
811    NumOperands = 5;
812    Op0.Val->Uses.push_back(this); Op1.Val->Uses.push_back(this);
813    Op2.Val->Uses.push_back(this); Op3.Val->Uses.push_back(this);
814    Op4.Val->Uses.push_back(this);
815  }
816  void setOperands(SDOperand Op0, SDOperand Op1, SDOperand Op2, SDOperand Op3,
817                   SDOperand Op4, SDOperand Op5) {
818    assert(NumOperands == 0 && "Should not have operands yet!");
819    OperandList = new SDOperand[6];
820    OperandList[0] = Op0;
821    OperandList[1] = Op1;
822    OperandList[2] = Op2;
823    OperandList[3] = Op3;
824    OperandList[4] = Op4;
825    OperandList[5] = Op5;
826    NumOperands = 6;
827    Op0.Val->Uses.push_back(this); Op1.Val->Uses.push_back(this);
828    Op2.Val->Uses.push_back(this); Op3.Val->Uses.push_back(this);
829    Op4.Val->Uses.push_back(this); Op5.Val->Uses.push_back(this);
830  }
831  void addUser(SDNode *User) {
832    Uses.push_back(User);
833  }
834  void removeUser(SDNode *User) {
835    // Remove this user from the operand's use list.
836    for (unsigned i = Uses.size(); ; --i) {
837      assert(i != 0 && "Didn't find user!");
838      if (Uses[i-1] == User) {
839        Uses[i-1] = Uses.back();
840        Uses.pop_back();
841        return;
842      }
843    }
844  }
845};
846
847
848// Define inline functions from the SDOperand class.
849
850inline unsigned SDOperand::getOpcode() const {
851  return Val->getOpcode();
852}
853inline unsigned SDOperand::getNodeDepth() const {
854  return Val->getNodeDepth();
855}
856inline MVT::ValueType SDOperand::getValueType() const {
857  return Val->getValueType(ResNo);
858}
859inline unsigned SDOperand::getNumOperands() const {
860  return Val->getNumOperands();
861}
862inline const SDOperand &SDOperand::getOperand(unsigned i) const {
863  return Val->getOperand(i);
864}
865inline bool SDOperand::isTargetOpcode() const {
866  return Val->isTargetOpcode();
867}
868inline unsigned SDOperand::getTargetOpcode() const {
869  return Val->getTargetOpcode();
870}
871inline bool SDOperand::hasOneUse() const {
872  return Val->hasNUsesOfValue(1, ResNo);
873}
874
875/// HandleSDNode - This class is used to form a handle around another node that
876/// is persistant and is updated across invocations of replaceAllUsesWith on its
877/// operand.  This node should be directly created by end-users and not added to
878/// the AllNodes list.
879class HandleSDNode : public SDNode {
880public:
881  HandleSDNode(SDOperand X) : SDNode(ISD::HANDLENODE, X) {}
882  ~HandleSDNode() {
883    MorphNodeTo(ISD::HANDLENODE);  // Drops operand uses.
884  }
885
886  SDOperand getValue() const { return getOperand(0); }
887};
888
889class StringSDNode : public SDNode {
890  std::string Value;
891protected:
892  friend class SelectionDAG;
893  StringSDNode(const std::string &val)
894    : SDNode(ISD::STRING, MVT::Other), Value(val) {
895  }
896public:
897  const std::string &getValue() const { return Value; }
898  static bool classof(const StringSDNode *) { return true; }
899  static bool classof(const SDNode *N) {
900    return N->getOpcode() == ISD::STRING;
901  }
902};
903
904class ConstantSDNode : public SDNode {
905  uint64_t Value;
906protected:
907  friend class SelectionDAG;
908  ConstantSDNode(bool isTarget, uint64_t val, MVT::ValueType VT)
909    : SDNode(isTarget ? ISD::TargetConstant : ISD::Constant, VT), Value(val) {
910  }
911public:
912
913  uint64_t getValue() const { return Value; }
914
915  int64_t getSignExtended() const {
916    unsigned Bits = MVT::getSizeInBits(getValueType(0));
917    return ((int64_t)Value << (64-Bits)) >> (64-Bits);
918  }
919
920  bool isNullValue() const { return Value == 0; }
921  bool isAllOnesValue() const {
922    int NumBits = MVT::getSizeInBits(getValueType(0));
923    if (NumBits == 64) return Value+1 == 0;
924    return Value == (1ULL << NumBits)-1;
925  }
926
927  static bool classof(const ConstantSDNode *) { return true; }
928  static bool classof(const SDNode *N) {
929    return N->getOpcode() == ISD::Constant ||
930           N->getOpcode() == ISD::TargetConstant;
931  }
932};
933
934class ConstantFPSDNode : public SDNode {
935  double Value;
936protected:
937  friend class SelectionDAG;
938  ConstantFPSDNode(double val, MVT::ValueType VT)
939    : SDNode(ISD::ConstantFP, VT), Value(val) {
940  }
941public:
942
943  double getValue() const { return Value; }
944
945  /// isExactlyValue - We don't rely on operator== working on double values, as
946  /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
947  /// As such, this method can be used to do an exact bit-for-bit comparison of
948  /// two floating point values.
949  bool isExactlyValue(double V) const;
950
951  static bool classof(const ConstantFPSDNode *) { return true; }
952  static bool classof(const SDNode *N) {
953    return N->getOpcode() == ISD::ConstantFP;
954  }
955};
956
957class GlobalAddressSDNode : public SDNode {
958  GlobalValue *TheGlobal;
959  int offset;
960protected:
961  friend class SelectionDAG;
962  GlobalAddressSDNode(bool isTarget, const GlobalValue *GA, MVT::ValueType VT,
963                      int o=0)
964    : SDNode(isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress, VT) {
965    TheGlobal = const_cast<GlobalValue*>(GA);
966    offset = o;
967  }
968public:
969
970  GlobalValue *getGlobal() const { return TheGlobal; }
971  int getOffset() const { return offset; }
972
973  static bool classof(const GlobalAddressSDNode *) { return true; }
974  static bool classof(const SDNode *N) {
975    return N->getOpcode() == ISD::GlobalAddress ||
976           N->getOpcode() == ISD::TargetGlobalAddress;
977  }
978};
979
980
981class FrameIndexSDNode : public SDNode {
982  int FI;
983protected:
984  friend class SelectionDAG;
985  FrameIndexSDNode(int fi, MVT::ValueType VT, bool isTarg)
986    : SDNode(isTarg ? ISD::TargetFrameIndex : ISD::FrameIndex, VT), FI(fi) {}
987public:
988
989  int getIndex() const { return FI; }
990
991  static bool classof(const FrameIndexSDNode *) { return true; }
992  static bool classof(const SDNode *N) {
993    return N->getOpcode() == ISD::FrameIndex ||
994           N->getOpcode() == ISD::TargetFrameIndex;
995  }
996};
997
998class ConstantPoolSDNode : public SDNode {
999  Constant *C;
1000protected:
1001  friend class SelectionDAG;
1002  ConstantPoolSDNode(Constant *c, MVT::ValueType VT, bool isTarget)
1003    : SDNode(isTarget ? ISD::TargetConstantPool : ISD::ConstantPool, VT),
1004    C(c) {}
1005public:
1006
1007  Constant *get() const { return C; }
1008
1009  static bool classof(const ConstantPoolSDNode *) { return true; }
1010  static bool classof(const SDNode *N) {
1011    return N->getOpcode() == ISD::ConstantPool ||
1012           N->getOpcode() == ISD::TargetConstantPool;
1013  }
1014};
1015
1016class BasicBlockSDNode : public SDNode {
1017  MachineBasicBlock *MBB;
1018protected:
1019  friend class SelectionDAG;
1020  BasicBlockSDNode(MachineBasicBlock *mbb)
1021    : SDNode(ISD::BasicBlock, MVT::Other), MBB(mbb) {}
1022public:
1023
1024  MachineBasicBlock *getBasicBlock() const { return MBB; }
1025
1026  static bool classof(const BasicBlockSDNode *) { return true; }
1027  static bool classof(const SDNode *N) {
1028    return N->getOpcode() == ISD::BasicBlock;
1029  }
1030};
1031
1032class SrcValueSDNode : public SDNode {
1033  const Value *V;
1034  int offset;
1035protected:
1036  friend class SelectionDAG;
1037  SrcValueSDNode(const Value* v, int o)
1038    : SDNode(ISD::SRCVALUE, MVT::Other), V(v), offset(o) {}
1039
1040public:
1041  const Value *getValue() const { return V; }
1042  int getOffset() const { return offset; }
1043
1044  static bool classof(const SrcValueSDNode *) { return true; }
1045  static bool classof(const SDNode *N) {
1046    return N->getOpcode() == ISD::SRCVALUE;
1047  }
1048};
1049
1050
1051class RegisterSDNode : public SDNode {
1052  unsigned Reg;
1053protected:
1054  friend class SelectionDAG;
1055  RegisterSDNode(unsigned reg, MVT::ValueType VT)
1056    : SDNode(ISD::Register, VT), Reg(reg) {}
1057public:
1058
1059  unsigned getReg() const { return Reg; }
1060
1061  static bool classof(const RegisterSDNode *) { return true; }
1062  static bool classof(const SDNode *N) {
1063    return N->getOpcode() == ISD::Register;
1064  }
1065};
1066
1067class ExternalSymbolSDNode : public SDNode {
1068  const char *Symbol;
1069protected:
1070  friend class SelectionDAG;
1071  ExternalSymbolSDNode(bool isTarget, const char *Sym, MVT::ValueType VT)
1072    : SDNode(isTarget ? ISD::TargetExternalSymbol : ISD::ExternalSymbol, VT),
1073      Symbol(Sym) {
1074    }
1075public:
1076
1077  const char *getSymbol() const { return Symbol; }
1078
1079  static bool classof(const ExternalSymbolSDNode *) { return true; }
1080  static bool classof(const SDNode *N) {
1081    return N->getOpcode() == ISD::ExternalSymbol ||
1082           N->getOpcode() == ISD::TargetExternalSymbol;
1083  }
1084};
1085
1086class CondCodeSDNode : public SDNode {
1087  ISD::CondCode Condition;
1088protected:
1089  friend class SelectionDAG;
1090  CondCodeSDNode(ISD::CondCode Cond)
1091    : SDNode(ISD::CONDCODE, MVT::Other), Condition(Cond) {
1092  }
1093public:
1094
1095  ISD::CondCode get() const { return Condition; }
1096
1097  static bool classof(const CondCodeSDNode *) { return true; }
1098  static bool classof(const SDNode *N) {
1099    return N->getOpcode() == ISD::CONDCODE;
1100  }
1101};
1102
1103/// VTSDNode - This class is used to represent MVT::ValueType's, which are used
1104/// to parameterize some operations.
1105class VTSDNode : public SDNode {
1106  MVT::ValueType ValueType;
1107protected:
1108  friend class SelectionDAG;
1109  VTSDNode(MVT::ValueType VT)
1110    : SDNode(ISD::VALUETYPE, MVT::Other), ValueType(VT) {}
1111public:
1112
1113  MVT::ValueType getVT() const { return ValueType; }
1114
1115  static bool classof(const VTSDNode *) { return true; }
1116  static bool classof(const SDNode *N) {
1117    return N->getOpcode() == ISD::VALUETYPE;
1118  }
1119};
1120
1121
1122class SDNodeIterator : public forward_iterator<SDNode, ptrdiff_t> {
1123  SDNode *Node;
1124  unsigned Operand;
1125
1126  SDNodeIterator(SDNode *N, unsigned Op) : Node(N), Operand(Op) {}
1127public:
1128  bool operator==(const SDNodeIterator& x) const {
1129    return Operand == x.Operand;
1130  }
1131  bool operator!=(const SDNodeIterator& x) const { return !operator==(x); }
1132
1133  const SDNodeIterator &operator=(const SDNodeIterator &I) {
1134    assert(I.Node == Node && "Cannot assign iterators to two different nodes!");
1135    Operand = I.Operand;
1136    return *this;
1137  }
1138
1139  pointer operator*() const {
1140    return Node->getOperand(Operand).Val;
1141  }
1142  pointer operator->() const { return operator*(); }
1143
1144  SDNodeIterator& operator++() {                // Preincrement
1145    ++Operand;
1146    return *this;
1147  }
1148  SDNodeIterator operator++(int) { // Postincrement
1149    SDNodeIterator tmp = *this; ++*this; return tmp;
1150  }
1151
1152  static SDNodeIterator begin(SDNode *N) { return SDNodeIterator(N, 0); }
1153  static SDNodeIterator end  (SDNode *N) {
1154    return SDNodeIterator(N, N->getNumOperands());
1155  }
1156
1157  unsigned getOperand() const { return Operand; }
1158  const SDNode *getNode() const { return Node; }
1159};
1160
1161template <> struct GraphTraits<SDNode*> {
1162  typedef SDNode NodeType;
1163  typedef SDNodeIterator ChildIteratorType;
1164  static inline NodeType *getEntryNode(SDNode *N) { return N; }
1165  static inline ChildIteratorType child_begin(NodeType *N) {
1166    return SDNodeIterator::begin(N);
1167  }
1168  static inline ChildIteratorType child_end(NodeType *N) {
1169    return SDNodeIterator::end(N);
1170  }
1171};
1172
1173template<>
1174struct ilist_traits<SDNode> {
1175  static SDNode *getPrev(const SDNode *N) { return N->Prev; }
1176  static SDNode *getNext(const SDNode *N) { return N->Next; }
1177
1178  static void setPrev(SDNode *N, SDNode *Prev) { N->Prev = Prev; }
1179  static void setNext(SDNode *N, SDNode *Next) { N->Next = Next; }
1180
1181  static SDNode *createSentinel() {
1182    return new SDNode(ISD::EntryToken, MVT::Other);
1183  }
1184  static void destroySentinel(SDNode *N) { delete N; }
1185  //static SDNode *createNode(const SDNode &V) { return new SDNode(V); }
1186
1187
1188  void addNodeToList(SDNode *NTy) {}
1189  void removeNodeFromList(SDNode *NTy) {}
1190  void transferNodesFromList(iplist<SDNode, ilist_traits> &L2,
1191                             const ilist_iterator<SDNode> &X,
1192                             const ilist_iterator<SDNode> &Y) {}
1193};
1194
1195} // end llvm namespace
1196
1197#endif
1198