SelectionDAG.cpp revision a2daa8c78d8749d6b4743e8bbfe4d522cd13a669
1//===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
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 implements the SelectionDAG class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/CodeGen/SelectionDAG.h"
15#include "llvm/Constants.h"
16#include "llvm/GlobalValue.h"
17#include "llvm/Assembly/Writer.h"
18#include "llvm/CodeGen/MachineBasicBlock.h"
19#include "llvm/Target/TargetLowering.h"
20#include <iostream>
21#include <set>
22#include <cmath>
23#include <algorithm>
24using namespace llvm;
25
26static bool isCommutativeBinOp(unsigned Opcode) {
27  switch (Opcode) {
28  case ISD::ADD:
29  case ISD::MUL:
30  case ISD::AND:
31  case ISD::OR:
32  case ISD::XOR: return true;
33  default: return false; // FIXME: Need commutative info for user ops!
34  }
35}
36
37static bool isAssociativeBinOp(unsigned Opcode) {
38  switch (Opcode) {
39  case ISD::ADD:
40  case ISD::MUL:
41  case ISD::AND:
42  case ISD::OR:
43  case ISD::XOR: return true;
44  default: return false; // FIXME: Need associative info for user ops!
45  }
46}
47
48static unsigned ExactLog2(uint64_t Val) {
49  unsigned Count = 0;
50  while (Val != 1) {
51    Val >>= 1;
52    ++Count;
53  }
54  return Count;
55}
56
57// isInvertibleForFree - Return true if there is no cost to emitting the logical
58// inverse of this node.
59static bool isInvertibleForFree(SDOperand N) {
60  if (isa<ConstantSDNode>(N.Val)) return true;
61  if (isa<SetCCSDNode>(N.Val) && N.Val->hasOneUse())
62    return true;
63  return false;
64}
65
66
67/// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
68/// when given the operation for (X op Y).
69ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
70  // To perform this operation, we just need to swap the L and G bits of the
71  // operation.
72  unsigned OldL = (Operation >> 2) & 1;
73  unsigned OldG = (Operation >> 1) & 1;
74  return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
75                       (OldL << 1) |       // New G bit
76                       (OldG << 2));        // New L bit.
77}
78
79/// getSetCCInverse - Return the operation corresponding to !(X op Y), where
80/// 'op' is a valid SetCC operation.
81ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
82  unsigned Operation = Op;
83  if (isInteger)
84    Operation ^= 7;   // Flip L, G, E bits, but not U.
85  else
86    Operation ^= 15;  // Flip all of the condition bits.
87  if (Operation > ISD::SETTRUE2)
88    Operation &= ~8;     // Don't let N and U bits get set.
89  return ISD::CondCode(Operation);
90}
91
92
93/// isSignedOp - For an integer comparison, return 1 if the comparison is a
94/// signed operation and 2 if the result is an unsigned comparison.  Return zero
95/// if the operation does not depend on the sign of the input (setne and seteq).
96static int isSignedOp(ISD::CondCode Opcode) {
97  switch (Opcode) {
98  default: assert(0 && "Illegal integer setcc operation!");
99  case ISD::SETEQ:
100  case ISD::SETNE: return 0;
101  case ISD::SETLT:
102  case ISD::SETLE:
103  case ISD::SETGT:
104  case ISD::SETGE: return 1;
105  case ISD::SETULT:
106  case ISD::SETULE:
107  case ISD::SETUGT:
108  case ISD::SETUGE: return 2;
109  }
110}
111
112/// getSetCCOrOperation - Return the result of a logical OR between different
113/// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This function
114/// returns SETCC_INVALID if it is not possible to represent the resultant
115/// comparison.
116ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
117                                       bool isInteger) {
118  if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
119    // Cannot fold a signed integer setcc with an unsigned integer setcc.
120    return ISD::SETCC_INVALID;
121
122  unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
123
124  // If the N and U bits get set then the resultant comparison DOES suddenly
125  // care about orderedness, and is true when ordered.
126  if (Op > ISD::SETTRUE2)
127    Op &= ~16;     // Clear the N bit.
128  return ISD::CondCode(Op);
129}
130
131/// getSetCCAndOperation - Return the result of a logical AND between different
132/// comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
133/// function returns zero if it is not possible to represent the resultant
134/// comparison.
135ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
136                                        bool isInteger) {
137  if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
138    // Cannot fold a signed setcc with an unsigned setcc.
139    return ISD::SETCC_INVALID;
140
141  // Combine all of the condition bits.
142  return ISD::CondCode(Op1 & Op2);
143}
144
145const TargetMachine &SelectionDAG::getTarget() const {
146  return TLI.getTargetMachine();
147}
148
149
150/// RemoveDeadNodes - This method deletes all unreachable nodes in the
151/// SelectionDAG, including nodes (like loads) that have uses of their token
152/// chain but no other uses and no side effect.  If a node is passed in as an
153/// argument, it is used as the seed for node deletion.
154void SelectionDAG::RemoveDeadNodes(SDNode *N) {
155  std::set<SDNode*> AllNodeSet(AllNodes.begin(), AllNodes.end());
156
157  // Create a dummy node (which is not added to allnodes), that adds a reference
158  // to the root node, preventing it from being deleted.
159  SDNode *DummyNode = new SDNode(ISD::EntryToken, getRoot());
160
161  DeleteNodeIfDead(N, &AllNodeSet);
162
163 Restart:
164  unsigned NumNodes = AllNodeSet.size();
165  for (std::set<SDNode*>::iterator I = AllNodeSet.begin(), E = AllNodeSet.end();
166       I != E; ++I) {
167    // Try to delete this node.
168    DeleteNodeIfDead(*I, &AllNodeSet);
169
170    // If we actually deleted any nodes, do not use invalid iterators in
171    // AllNodeSet.
172    if (AllNodeSet.size() != NumNodes)
173      goto Restart;
174  }
175
176  // Restore AllNodes.
177  if (AllNodes.size() != NumNodes)
178    AllNodes.assign(AllNodeSet.begin(), AllNodeSet.end());
179
180  // If the root changed (e.g. it was a dead load, update the root).
181  setRoot(DummyNode->getOperand(0));
182
183  // Now that we are done with the dummy node, delete it.
184  DummyNode->getOperand(0).Val->removeUser(DummyNode);
185  delete DummyNode;
186}
187
188void SelectionDAG::DeleteNodeIfDead(SDNode *N, void *NodeSet) {
189  if (!N->use_empty())
190    return;
191
192  // Okay, we really are going to delete this node.  First take this out of the
193  // appropriate CSE map.
194  switch (N->getOpcode()) {
195  case ISD::Constant:
196    Constants.erase(std::make_pair(cast<ConstantSDNode>(N)->getValue(),
197                                   N->getValueType(0)));
198    break;
199  case ISD::ConstantFP: {
200    union {
201      double DV;
202      uint64_t IV;
203    };
204    DV = cast<ConstantFPSDNode>(N)->getValue();
205    ConstantFPs.erase(std::make_pair(IV, N->getValueType(0)));
206    break;
207  }
208  case ISD::GlobalAddress:
209    GlobalValues.erase(cast<GlobalAddressSDNode>(N)->getGlobal());
210    break;
211  case ISD::FrameIndex:
212    FrameIndices.erase(cast<FrameIndexSDNode>(N)->getIndex());
213    break;
214  case ISD::ConstantPool:
215    ConstantPoolIndices.erase(cast<ConstantPoolSDNode>(N)->getIndex());
216    break;
217  case ISD::BasicBlock:
218    BBNodes.erase(cast<BasicBlockSDNode>(N)->getBasicBlock());
219    break;
220  case ISD::ExternalSymbol:
221    ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
222    break;
223
224  case ISD::LOAD:
225    Loads.erase(std::make_pair(N->getOperand(1),
226                               std::make_pair(N->getOperand(0),
227                                              N->getValueType(0))));
228    break;
229  case ISD::SETCC:
230    SetCCs.erase(std::make_pair(std::make_pair(N->getOperand(0),
231                                               N->getOperand(1)),
232                                std::make_pair(
233                                     cast<SetCCSDNode>(N)->getCondition(),
234                                     N->getValueType(0))));
235    break;
236  case ISD::TRUNCSTORE:
237  case ISD::SIGN_EXTEND_INREG:
238  case ISD::ZERO_EXTEND_INREG:
239  case ISD::FP_ROUND_INREG:
240  case ISD::EXTLOAD:
241  case ISD::SEXTLOAD:
242  case ISD::ZEXTLOAD: {
243    EVTStruct NN;
244    NN.Opcode = N->getOpcode();
245    NN.VT = N->getValueType(0);
246    NN.EVT = cast<MVTSDNode>(N)->getExtraValueType();
247    for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
248      NN.Ops.push_back(N->getOperand(i));
249    MVTSDNodes.erase(NN);
250    break;
251  }
252  default:
253    if (N->getNumOperands() == 1)
254      UnaryOps.erase(std::make_pair(N->getOpcode(),
255                                    std::make_pair(N->getOperand(0),
256                                                   N->getValueType(0))));
257    else if (N->getNumOperands() == 2)
258      BinaryOps.erase(std::make_pair(N->getOpcode(),
259                                     std::make_pair(N->getOperand(0),
260                                                    N->getOperand(1))));
261    break;
262  }
263
264  // Next, brutally remove the operand list.
265  while (!N->Operands.empty()) {
266    SDNode *O = N->Operands.back().Val;
267    N->Operands.pop_back();
268    O->removeUser(N);
269
270    // Now that we removed this operand, see if there are no uses of it left.
271    DeleteNodeIfDead(O, NodeSet);
272  }
273
274  // Remove the node from the nodes set and delete it.
275  std::set<SDNode*> &AllNodeSet = *(std::set<SDNode*>*)NodeSet;
276  AllNodeSet.erase(N);
277
278  // Now that the node is gone, check to see if any of the operands of this node
279  // are dead now.
280  delete N;
281}
282
283
284SelectionDAG::~SelectionDAG() {
285  for (unsigned i = 0, e = AllNodes.size(); i != e; ++i)
286    delete AllNodes[i];
287}
288
289SDOperand SelectionDAG::getConstant(uint64_t Val, MVT::ValueType VT) {
290  assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
291  // Mask out any bits that are not valid for this constant.
292  if (VT != MVT::i64)
293    Val &= ((uint64_t)1 << MVT::getSizeInBits(VT)) - 1;
294
295  SDNode *&N = Constants[std::make_pair(Val, VT)];
296  if (N) return SDOperand(N, 0);
297  N = new ConstantSDNode(Val, VT);
298  AllNodes.push_back(N);
299  return SDOperand(N, 0);
300}
301
302SDOperand SelectionDAG::getConstantFP(double Val, MVT::ValueType VT) {
303  assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
304  if (VT == MVT::f32)
305    Val = (float)Val;  // Mask out extra precision.
306
307  // Do the map lookup using the actual bit pattern for the floating point
308  // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
309  // we don't have issues with SNANs.
310  union {
311    double DV;
312    uint64_t IV;
313  };
314
315  DV = Val;
316
317  SDNode *&N = ConstantFPs[std::make_pair(IV, VT)];
318  if (N) return SDOperand(N, 0);
319  N = new ConstantFPSDNode(Val, VT);
320  AllNodes.push_back(N);
321  return SDOperand(N, 0);
322}
323
324
325
326SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
327                                         MVT::ValueType VT) {
328  SDNode *&N = GlobalValues[GV];
329  if (N) return SDOperand(N, 0);
330  N = new GlobalAddressSDNode(GV,VT);
331  AllNodes.push_back(N);
332  return SDOperand(N, 0);
333}
334
335SDOperand SelectionDAG::getFrameIndex(int FI, MVT::ValueType VT) {
336  SDNode *&N = FrameIndices[FI];
337  if (N) return SDOperand(N, 0);
338  N = new FrameIndexSDNode(FI, VT);
339  AllNodes.push_back(N);
340  return SDOperand(N, 0);
341}
342
343SDOperand SelectionDAG::getConstantPool(unsigned CPIdx, MVT::ValueType VT) {
344  SDNode *N = ConstantPoolIndices[CPIdx];
345  if (N) return SDOperand(N, 0);
346  N = new ConstantPoolSDNode(CPIdx, VT);
347  AllNodes.push_back(N);
348  return SDOperand(N, 0);
349}
350
351SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
352  SDNode *&N = BBNodes[MBB];
353  if (N) return SDOperand(N, 0);
354  N = new BasicBlockSDNode(MBB);
355  AllNodes.push_back(N);
356  return SDOperand(N, 0);
357}
358
359SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT::ValueType VT) {
360  SDNode *&N = ExternalSymbols[Sym];
361  if (N) return SDOperand(N, 0);
362  N = new ExternalSymbolSDNode(Sym, VT);
363  AllNodes.push_back(N);
364  return SDOperand(N, 0);
365}
366
367SDOperand SelectionDAG::getSetCC(ISD::CondCode Cond, MVT::ValueType VT,
368                                 SDOperand N1, SDOperand N2) {
369  // These setcc operations always fold.
370  switch (Cond) {
371  default: break;
372  case ISD::SETFALSE:
373  case ISD::SETFALSE2: return getConstant(0, VT);
374  case ISD::SETTRUE:
375  case ISD::SETTRUE2:  return getConstant(1, VT);
376  }
377
378  if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
379    uint64_t C2 = N2C->getValue();
380    if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
381      uint64_t C1 = N1C->getValue();
382
383      // Sign extend the operands if required
384      if (ISD::isSignedIntSetCC(Cond)) {
385        C1 = N1C->getSignExtended();
386        C2 = N2C->getSignExtended();
387      }
388
389      switch (Cond) {
390      default: assert(0 && "Unknown integer setcc!");
391      case ISD::SETEQ:  return getConstant(C1 == C2, VT);
392      case ISD::SETNE:  return getConstant(C1 != C2, VT);
393      case ISD::SETULT: return getConstant(C1 <  C2, VT);
394      case ISD::SETUGT: return getConstant(C1 >  C2, VT);
395      case ISD::SETULE: return getConstant(C1 <= C2, VT);
396      case ISD::SETUGE: return getConstant(C1 >= C2, VT);
397      case ISD::SETLT:  return getConstant((int64_t)C1 <  (int64_t)C2, VT);
398      case ISD::SETGT:  return getConstant((int64_t)C1 >  (int64_t)C2, VT);
399      case ISD::SETLE:  return getConstant((int64_t)C1 <= (int64_t)C2, VT);
400      case ISD::SETGE:  return getConstant((int64_t)C1 >= (int64_t)C2, VT);
401      }
402    } else {
403      uint64_t MinVal, MaxVal;
404      unsigned OperandBitSize = MVT::getSizeInBits(N2C->getValueType(0));
405      if (ISD::isSignedIntSetCC(Cond)) {
406        MinVal = 1ULL << (OperandBitSize-1);
407        if (OperandBitSize != 1)   // Avoid X >> 64, which is undefined.
408          MaxVal = ~0ULL >> (65-OperandBitSize);
409        else
410          MaxVal = 0;
411      } else {
412        MinVal = 0;
413        MaxVal = ~0ULL >> (64-OperandBitSize);
414      }
415
416      // Canonicalize GE/LE comparisons to use GT/LT comparisons.
417      if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
418        if (C2 == MinVal) return getConstant(1, VT);   // X >= MIN --> true
419        --C2;                                          // X >= C1 --> X > (C1-1)
420        Cond = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
421        N2 = getConstant(C2, N2.getValueType());
422        N2C = cast<ConstantSDNode>(N2.Val);
423      }
424
425      if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
426        if (C2 == MaxVal) return getConstant(1, VT);   // X <= MAX --> true
427        ++C2;                                          // X <= C1 --> X < (C1+1)
428        Cond = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
429        N2 = getConstant(C2, N2.getValueType());
430        N2C = cast<ConstantSDNode>(N2.Val);
431      }
432
433      // If we have "setcc X, C1", check to see if we can shrink the immediate
434      // by changing cc.
435
436      // SETUGT X, SINTMAX  -> SETLT X, 0
437      if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
438          C2 == (~0ULL >> (65-OperandBitSize)))
439        return getSetCC(ISD::SETLT, VT, N1, getConstant(0, N2.getValueType()));
440
441      // FIXME: Implement the rest of these.
442
443    }
444  } else if (isa<ConstantSDNode>(N1.Val)) {
445      // Ensure that the constant occurs on the RHS.
446    return getSetCC(ISD::getSetCCSwappedOperands(Cond), VT, N2, N1);
447  }
448
449  if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val))
450    if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
451      double C1 = N1C->getValue(), C2 = N2C->getValue();
452
453      switch (Cond) {
454      default: break; // FIXME: Implement the rest of these!
455      case ISD::SETEQ:  return getConstant(C1 == C2, VT);
456      case ISD::SETNE:  return getConstant(C1 != C2, VT);
457      case ISD::SETLT:  return getConstant(C1 < C2, VT);
458      case ISD::SETGT:  return getConstant(C1 > C2, VT);
459      case ISD::SETLE:  return getConstant(C1 <= C2, VT);
460      case ISD::SETGE:  return getConstant(C1 >= C2, VT);
461      }
462    } else {
463      // Ensure that the constant occurs on the RHS.
464      Cond = ISD::getSetCCSwappedOperands(Cond);
465      std::swap(N1, N2);
466    }
467
468  if (N1 == N2) {
469    // We can always fold X == Y for integer setcc's.
470    if (MVT::isInteger(N1.getValueType()))
471      return getConstant(ISD::isTrueWhenEqual(Cond), VT);
472    unsigned UOF = ISD::getUnorderedFlavor(Cond);
473    if (UOF == 2)   // FP operators that are undefined on NaNs.
474      return getConstant(ISD::isTrueWhenEqual(Cond), VT);
475    if (UOF == ISD::isTrueWhenEqual(Cond))
476      return getConstant(UOF, VT);
477    // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
478    // if it is not already.
479    Cond = UOF == 0 ? ISD::SETUO : ISD::SETO;
480  }
481
482  if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
483      MVT::isInteger(N1.getValueType())) {
484    if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
485        N1.getOpcode() == ISD::XOR) {
486      // Simplify (X+Y) == (X+Z) -->  Y == Z
487      if (N1.getOpcode() == N2.getOpcode()) {
488        if (N1.getOperand(0) == N2.getOperand(0))
489          return getSetCC(Cond, VT, N1.getOperand(1), N2.getOperand(1));
490        if (N1.getOperand(1) == N2.getOperand(1))
491          return getSetCC(Cond, VT, N1.getOperand(0), N2.getOperand(0));
492        if (isCommutativeBinOp(N1.getOpcode())) {
493          // If X op Y == Y op X, try other combinations.
494          if (N1.getOperand(0) == N2.getOperand(1))
495            return getSetCC(Cond, VT, N1.getOperand(1), N2.getOperand(0));
496          if (N1.getOperand(1) == N2.getOperand(0))
497            return getSetCC(Cond, VT, N1.getOperand(1), N2.getOperand(1));
498        }
499      }
500
501      // FIXME: move this stuff to the DAG Combiner when it exists!
502
503      // Simplify (X+Z) == X -->  Z == 0
504      if (N1.getOperand(0) == N2)
505        return getSetCC(Cond, VT, N1.getOperand(1),
506                        getConstant(0, N1.getValueType()));
507      if (N1.getOperand(1) == N2) {
508        if (isCommutativeBinOp(N1.getOpcode()))
509          return getSetCC(Cond, VT, N1.getOperand(0),
510                          getConstant(0, N1.getValueType()));
511        else {
512          assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
513          // (Z-X) == X  --> Z == X<<1
514          return getSetCC(Cond, VT, N1.getOperand(0),
515                          getNode(ISD::SHL, N2.getValueType(),
516                                  N2, getConstant(1, TLI.getShiftAmountTy())));
517        }
518      }
519    }
520
521    if (N2.getOpcode() == ISD::ADD || N2.getOpcode() == ISD::SUB ||
522        N2.getOpcode() == ISD::XOR) {
523      // Simplify  X == (X+Z) -->  Z == 0
524      if (N2.getOperand(0) == N1)
525        return getSetCC(Cond, VT, N2.getOperand(1),
526                        getConstant(0, N2.getValueType()));
527      else if (N2.getOperand(1) == N1)
528        return getSetCC(Cond, VT, N2.getOperand(0),
529                        getConstant(0, N2.getValueType()));
530    }
531  }
532
533  SetCCSDNode *&N = SetCCs[std::make_pair(std::make_pair(N1, N2),
534                                          std::make_pair(Cond, VT))];
535  if (N) return SDOperand(N, 0);
536  N = new SetCCSDNode(Cond, N1, N2);
537  N->setValueTypes(VT);
538  AllNodes.push_back(N);
539  return SDOperand(N, 0);
540}
541
542
543
544/// getNode - Gets or creates the specified node.
545///
546SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
547  SDNode *N = new SDNode(Opcode, VT);
548  AllNodes.push_back(N);
549  return SDOperand(N, 0);
550}
551
552SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
553                                SDOperand Operand) {
554  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
555    uint64_t Val = C->getValue();
556    switch (Opcode) {
557    default: break;
558    case ISD::SIGN_EXTEND: return getConstant(C->getSignExtended(), VT);
559    case ISD::ZERO_EXTEND: return getConstant(Val, VT);
560    case ISD::TRUNCATE:    return getConstant(Val, VT);
561    case ISD::SINT_TO_FP:  return getConstantFP(C->getSignExtended(), VT);
562    case ISD::UINT_TO_FP:  return getConstantFP(C->getValue(), VT);
563    }
564  }
565
566  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val))
567    switch (Opcode) {
568    case ISD::FNEG:
569      return getConstantFP(-C->getValue(), VT);
570    case ISD::FP_ROUND:
571    case ISD::FP_EXTEND:
572      return getConstantFP(C->getValue(), VT);
573    case ISD::FP_TO_SINT:
574      return getConstant((int64_t)C->getValue(), VT);
575    case ISD::FP_TO_UINT:
576      return getConstant((uint64_t)C->getValue(), VT);
577    }
578
579  unsigned OpOpcode = Operand.Val->getOpcode();
580  switch (Opcode) {
581  case ISD::TokenFactor:
582    return Operand;         // Factor of one node?  No factor.
583  case ISD::SIGN_EXTEND:
584    if (Operand.getValueType() == VT) return Operand;   // noop extension
585    if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
586      return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
587    break;
588  case ISD::ZERO_EXTEND:
589    if (Operand.getValueType() == VT) return Operand;   // noop extension
590    if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
591      return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
592    break;
593  case ISD::TRUNCATE:
594    if (Operand.getValueType() == VT) return Operand;   // noop truncate
595    if (OpOpcode == ISD::TRUNCATE)
596      return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
597    else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND) {
598      // If the source is smaller than the dest, we still need an extend.
599      if (Operand.Val->getOperand(0).getValueType() < VT)
600        return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
601      else if (Operand.Val->getOperand(0).getValueType() > VT)
602        return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
603      else
604        return Operand.Val->getOperand(0);
605    }
606    break;
607  case ISD::FNEG:
608    if (OpOpcode == ISD::SUB)   // -(X-Y) -> (Y-X)
609      return getNode(ISD::SUB, VT, Operand.Val->getOperand(1),
610                     Operand.Val->getOperand(0));
611    if (OpOpcode == ISD::FNEG)  // --X -> X
612      return Operand.Val->getOperand(0);
613    break;
614  case ISD::FABS:
615    if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
616      return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
617    break;
618  }
619
620  SDNode *&N = UnaryOps[std::make_pair(Opcode, std::make_pair(Operand, VT))];
621  if (N) return SDOperand(N, 0);
622  N = new SDNode(Opcode, Operand);
623  N->setValueTypes(VT);
624  AllNodes.push_back(N);
625  return SDOperand(N, 0);
626}
627
628SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
629                                SDOperand N1, SDOperand N2) {
630#ifndef NDEBUG
631  switch (Opcode) {
632  case ISD::TokenFactor:
633    assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
634           N2.getValueType() == MVT::Other && "Invalid token factor!");
635    break;
636  case ISD::AND:
637  case ISD::OR:
638  case ISD::XOR:
639  case ISD::UDIV:
640  case ISD::UREM:
641    assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
642    // fall through
643  case ISD::ADD:
644  case ISD::SUB:
645  case ISD::MUL:
646  case ISD::SDIV:
647  case ISD::SREM:
648    assert(N1.getValueType() == N2.getValueType() &&
649           N1.getValueType() == VT && "Binary operator types must match!");
650    break;
651
652  case ISD::SHL:
653  case ISD::SRA:
654  case ISD::SRL:
655    assert(VT == N1.getValueType() &&
656           "Shift operators return type must be the same as their first arg");
657    assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
658           VT != MVT::i1 && "Shifts only work on integers");
659    break;
660  default: break;
661  }
662#endif
663
664  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
665  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
666  if (N1C) {
667    if (N2C) {
668      uint64_t C1 = N1C->getValue(), C2 = N2C->getValue();
669      switch (Opcode) {
670      case ISD::ADD: return getConstant(C1 + C2, VT);
671      case ISD::SUB: return getConstant(C1 - C2, VT);
672      case ISD::MUL: return getConstant(C1 * C2, VT);
673      case ISD::UDIV:
674        if (C2) return getConstant(C1 / C2, VT);
675        break;
676      case ISD::UREM :
677        if (C2) return getConstant(C1 % C2, VT);
678        break;
679      case ISD::SDIV :
680        if (C2) return getConstant(N1C->getSignExtended() /
681                                   N2C->getSignExtended(), VT);
682        break;
683      case ISD::SREM :
684        if (C2) return getConstant(N1C->getSignExtended() %
685                                   N2C->getSignExtended(), VT);
686        break;
687      case ISD::AND  : return getConstant(C1 & C2, VT);
688      case ISD::OR   : return getConstant(C1 | C2, VT);
689      case ISD::XOR  : return getConstant(C1 ^ C2, VT);
690      case ISD::SHL  : return getConstant(C1 << (int)C2, VT);
691      case ISD::SRL  : return getConstant(C1 >> (unsigned)C2, VT);
692      case ISD::SRA  : return getConstant(N1C->getSignExtended() >>(int)C2, VT);
693      default: break;
694      }
695
696    } else {      // Cannonicalize constant to RHS if commutative
697      if (isCommutativeBinOp(Opcode)) {
698        std::swap(N1C, N2C);
699        std::swap(N1, N2);
700      }
701    }
702
703    switch (Opcode) {
704    default: break;
705    case ISD::SHL:    // shl  0, X -> 0
706      if (N1C->isNullValue()) return N1;
707      break;
708    case ISD::SRL:    // srl  0, X -> 0
709      if (N1C->isNullValue()) return N1;
710      break;
711    case ISD::SRA:    // sra -1, X -> -1
712      if (N1C->isAllOnesValue()) return N1;
713      break;
714    }
715  }
716
717  if (N2C) {
718    uint64_t C2 = N2C->getValue();
719
720    switch (Opcode) {
721    case ISD::ADD:
722      if (!C2) return N1;         // add X, 0 -> X
723      break;
724    case ISD::SUB:
725      if (!C2) return N1;         // sub X, 0 -> X
726      break;
727    case ISD::MUL:
728      if (!C2) return N2;         // mul X, 0 -> 0
729      if (N2C->isAllOnesValue()) // mul X, -1 -> 0-X
730        return getNode(ISD::SUB, VT, getConstant(0, VT), N1);
731
732      // FIXME: Move this to the DAG combiner when it exists.
733      if ((C2 & C2-1) == 0) {
734        SDOperand ShAmt = getConstant(ExactLog2(C2), TLI.getShiftAmountTy());
735        return getNode(ISD::SHL, VT, N1, ShAmt);
736      }
737      break;
738
739    case ISD::UDIV:
740      // FIXME: Move this to the DAG combiner when it exists.
741      if ((C2 & C2-1) == 0 && C2) {
742        SDOperand ShAmt = getConstant(ExactLog2(C2), TLI.getShiftAmountTy());
743        return getNode(ISD::SRL, VT, N1, ShAmt);
744      }
745      break;
746
747    case ISD::SHL:
748    case ISD::SRL:
749      // If the shift amount is bigger than the size of the data, simplify.
750      if (C2 >= MVT::getSizeInBits(N1.getValueType())) {
751        if (TLI.getShiftAmountFlavor() == TargetLowering::Mask) {
752          unsigned NewAmt =
753            C2 & ((1 << MVT::getSizeInBits(N1.getValueType()))-1);
754          return getNode(Opcode, VT, N1, getConstant(NewAmt,N2.getValueType()));
755        } else if (TLI.getShiftAmountFlavor() == TargetLowering::Extend) {
756          // Shifting all of the bits out?
757          return getConstant(0, N1.getValueType());
758        }
759      }
760      // FALL THROUGH.
761    case ISD::SRA:
762      if (C2 == 0) return N1;
763      break;
764
765    case ISD::AND:
766      if (!C2) return N2;         // X and 0 -> 0
767      if (N2C->isAllOnesValue())
768	return N1;                // X and -1 -> X
769
770      // and (zero_extend_inreg x:16:32), 1 -> and x, 1
771      if (N1.getOpcode() == ISD::ZERO_EXTEND_INREG ||
772          N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
773        // If we are masking out the part of our input that was extended, just
774        // mask the input to the extension directly.
775        unsigned ExtendBits =
776          MVT::getSizeInBits(cast<MVTSDNode>(N1)->getExtraValueType());
777        if ((C2 & (~0ULL << ExtendBits)) == 0)
778          return getNode(ISD::AND, VT, N1.getOperand(0), N2);
779      }
780      break;
781    case ISD::OR:
782      if (!C2)return N1;          // X or 0 -> X
783      if (N2C->isAllOnesValue())
784	return N2;                // X or -1 -> -1
785      break;
786    case ISD::XOR:
787      if (!C2) return N1;        // X xor 0 -> X
788      if (N2C->isAllOnesValue()) {
789        if (SetCCSDNode *SetCC = dyn_cast<SetCCSDNode>(N1.Val)){
790          // !(X op Y) -> (X !op Y)
791          bool isInteger = MVT::isInteger(SetCC->getOperand(0).getValueType());
792          return getSetCC(ISD::getSetCCInverse(SetCC->getCondition(),isInteger),
793                          SetCC->getValueType(0),
794                          SetCC->getOperand(0), SetCC->getOperand(1));
795        } else if (N1.getOpcode() == ISD::AND || N1.getOpcode() == ISD::OR) {
796          SDNode *Op = N1.Val;
797          // !(X or Y) -> (!X and !Y) iff X or Y are freely invertible
798          // !(X and Y) -> (!X or !Y) iff X or Y are freely invertible
799          SDOperand LHS = Op->getOperand(0), RHS = Op->getOperand(1);
800          if (isInvertibleForFree(RHS) || isInvertibleForFree(LHS)) {
801            LHS = getNode(ISD::XOR, VT, LHS, N2);  // RHS = ~LHS
802            RHS = getNode(ISD::XOR, VT, RHS, N2);  // RHS = ~RHS
803            if (Op->getOpcode() == ISD::AND)
804              return getNode(ISD::OR, VT, LHS, RHS);
805            return getNode(ISD::AND, VT, LHS, RHS);
806          }
807        }
808	// X xor -1 -> not(x)  ?
809      }
810      break;
811    }
812
813    // Reassociate ((X op C1) op C2) if possible.
814    if (N1.getOpcode() == Opcode && isAssociativeBinOp(Opcode))
815      if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N1.Val->getOperand(1)))
816        return getNode(Opcode, VT, N1.Val->getOperand(0),
817                       getNode(Opcode, VT, N2, N1.Val->getOperand(1)));
818  }
819
820  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
821  ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
822  if (N1CFP)
823    if (N2CFP) {
824      double C1 = N1CFP->getValue(), C2 = N2CFP->getValue();
825      switch (Opcode) {
826      case ISD::ADD: return getConstantFP(C1 + C2, VT);
827      case ISD::SUB: return getConstantFP(C1 - C2, VT);
828      case ISD::MUL: return getConstantFP(C1 * C2, VT);
829      case ISD::SDIV:
830        if (C2) return getConstantFP(C1 / C2, VT);
831        break;
832      case ISD::SREM :
833        if (C2) return getConstantFP(fmod(C1, C2), VT);
834        break;
835      default: break;
836      }
837
838    } else {      // Cannonicalize constant to RHS if commutative
839      if (isCommutativeBinOp(Opcode)) {
840        std::swap(N1CFP, N2CFP);
841        std::swap(N1, N2);
842      }
843    }
844
845  // Finally, fold operations that do not require constants.
846  switch (Opcode) {
847  case ISD::TokenFactor:
848    if (N1.getOpcode() == ISD::EntryToken)
849      return N2;
850    if (N2.getOpcode() == ISD::EntryToken)
851      return N1;
852    break;
853
854  case ISD::AND:
855  case ISD::OR:
856    if (SetCCSDNode *LHS = dyn_cast<SetCCSDNode>(N1.Val))
857      if (SetCCSDNode *RHS = dyn_cast<SetCCSDNode>(N2.Val)) {
858        SDOperand LL = LHS->getOperand(0), RL = RHS->getOperand(0);
859        SDOperand LR = LHS->getOperand(1), RR = RHS->getOperand(1);
860        ISD::CondCode Op2 = RHS->getCondition();
861
862        // (X op1 Y) | (Y op2 X) -> (X op1 Y) | (X swapop2 Y)
863        if (LL == RR && LR == RL) {
864          Op2 = ISD::getSetCCSwappedOperands(Op2);
865          goto MatchedBackwards;
866        }
867
868        if (LL == RL && LR == RR) {
869        MatchedBackwards:
870          ISD::CondCode Result;
871          bool isInteger = MVT::isInteger(LL.getValueType());
872          if (Opcode == ISD::OR)
873            Result = ISD::getSetCCOrOperation(LHS->getCondition(), Op2,
874                                              isInteger);
875          else
876            Result = ISD::getSetCCAndOperation(LHS->getCondition(), Op2,
877                                               isInteger);
878          if (Result != ISD::SETCC_INVALID)
879            return getSetCC(Result, LHS->getValueType(0), LL, LR);
880        }
881      }
882    break;
883  case ISD::XOR:
884    if (N1 == N2) return getConstant(0, VT);  // xor X, Y -> 0
885    break;
886  case ISD::ADD:
887    if (N2.getOpcode() == ISD::FNEG)          // (A+ (-B) -> A-B
888      return getNode(ISD::SUB, VT, N1, N2.getOperand(0));
889    if (N1.getOpcode() == ISD::FNEG)          // ((-A)+B) -> B-A
890      return getNode(ISD::SUB, VT, N2, N1.getOperand(0));
891    break;
892  case ISD::SUB:
893    if (N1.getOpcode() == ISD::ADD) {
894      if (N1.Val->getOperand(0) == N2)
895        return N1.Val->getOperand(1);         // (A+B)-A == B
896      if (N1.Val->getOperand(1) == N2)
897        return N1.Val->getOperand(0);         // (A+B)-B == A
898    }
899    if (N2.getOpcode() == ISD::FNEG)          // (A- (-B) -> A+B
900      return getNode(ISD::ADD, VT, N1, N2.getOperand(0));
901    break;
902  }
903
904  SDNode *&N = BinaryOps[std::make_pair(Opcode, std::make_pair(N1, N2))];
905  if (N) return SDOperand(N, 0);
906  N = new SDNode(Opcode, N1, N2);
907  N->setValueTypes(VT);
908
909  AllNodes.push_back(N);
910  return SDOperand(N, 0);
911}
912
913SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
914                                SDOperand Chain, SDOperand Ptr) {
915  SDNode *&N = Loads[std::make_pair(Ptr, std::make_pair(Chain, VT))];
916  if (N) return SDOperand(N, 0);
917  N = new SDNode(ISD::LOAD, Chain, Ptr);
918
919  // Loads have a token chain.
920  N->setValueTypes(VT, MVT::Other);
921  AllNodes.push_back(N);
922  return SDOperand(N, 0);
923}
924
925
926SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
927                                SDOperand N1, SDOperand N2, SDOperand N3) {
928  // Perform various simplifications.
929  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
930  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
931  ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
932  switch (Opcode) {
933  case ISD::SELECT:
934    if (N1C)
935      if (N1C->getValue())
936        return N2;             // select true, X, Y -> X
937      else
938        return N3;             // select false, X, Y -> Y
939
940    if (N2 == N3) return N2;   // select C, X, X -> X
941
942    if (VT == MVT::i1) {  // Boolean SELECT
943      if (N2C) {
944        if (N3C) {
945          if (N2C->getValue()) // select C, 1, 0 -> C
946            return N1;
947          return getNode(ISD::XOR, VT, N1, N3); // select C, 0, 1 -> ~C
948        }
949
950        if (N2C->getValue())   // select C, 1, X -> C | X
951          return getNode(ISD::OR, VT, N1, N3);
952        else                   // select C, 0, X -> ~C & X
953          return getNode(ISD::AND, VT,
954                         getNode(ISD::XOR, N1.getValueType(), N1,
955                                 getConstant(1, N1.getValueType())), N3);
956      } else if (N3C) {
957        if (N3C->getValue())   // select C, X, 1 -> ~C | X
958          return getNode(ISD::OR, VT,
959                         getNode(ISD::XOR, N1.getValueType(), N1,
960                                 getConstant(1, N1.getValueType())), N2);
961        else                   // select C, X, 0 -> C & X
962          return getNode(ISD::AND, VT, N1, N2);
963      }
964    }
965
966    // If this is a selectcc, check to see if we can simplify the result.
967    if (SetCCSDNode *SetCC = dyn_cast<SetCCSDNode>(N1)) {
968      if (ConstantFPSDNode *CFP =
969          dyn_cast<ConstantFPSDNode>(SetCC->getOperand(1)))
970        if (CFP->getValue() == 0.0) {   // Allow either -0.0 or 0.0
971          // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
972          if ((SetCC->getCondition() == ISD::SETGE ||
973               SetCC->getCondition() == ISD::SETGT) &&
974              N2 == SetCC->getOperand(0) && N3.getOpcode() == ISD::FNEG &&
975              N3.getOperand(0) == N2)
976            return getNode(ISD::FABS, VT, N2);
977
978          // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
979          if ((SetCC->getCondition() == ISD::SETLT ||
980               SetCC->getCondition() == ISD::SETLE) &&
981              N3 == SetCC->getOperand(0) && N2.getOpcode() == ISD::FNEG &&
982              N2.getOperand(0) == N3)
983            return getNode(ISD::FABS, VT, N3);
984        }
985
986    }
987    break;
988  case ISD::BRCOND:
989    if (N2C)
990      if (N2C->getValue()) // Unconditional branch
991        return getNode(ISD::BR, MVT::Other, N1, N3);
992      else
993        return N1;         // Never-taken branch
994    break;
995  }
996
997  SDNode *N = new SDNode(Opcode, N1, N2, N3);
998  switch (Opcode) {
999  default:
1000    N->setValueTypes(VT);
1001    break;
1002  case ISD::DYNAMIC_STACKALLOC: // DYNAMIC_STACKALLOC produces pointer and chain
1003    N->setValueTypes(VT, MVT::Other);
1004    break;
1005
1006  case ISD::SRA_PARTS:
1007  case ISD::SRL_PARTS:
1008  case ISD::SHL_PARTS: {
1009    std::vector<MVT::ValueType> V(N->getNumOperands()-1, VT);
1010    N->setValueTypes(V);
1011    break;
1012  }
1013  }
1014
1015  // FIXME: memoize NODES
1016  AllNodes.push_back(N);
1017  return SDOperand(N, 0);
1018}
1019
1020SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1021                                std::vector<SDOperand> &Children) {
1022  switch (Children.size()) {
1023  case 0: return getNode(Opcode, VT);
1024  case 1: return getNode(Opcode, VT, Children[0]);
1025  case 2: return getNode(Opcode, VT, Children[0], Children[1]);
1026  case 3: return getNode(Opcode, VT, Children[0], Children[1], Children[2]);
1027  default: break;
1028  }
1029
1030  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Children[1].Val);
1031  switch (Opcode) {
1032  default: break;
1033  case ISD::BRCONDTWOWAY:
1034    if (N1C)
1035      if (N1C->getValue()) // Unconditional branch to true dest.
1036        return getNode(ISD::BR, MVT::Other, Children[0], Children[2]);
1037      else                 // Unconditional branch to false dest.
1038        return getNode(ISD::BR, MVT::Other, Children[0], Children[3]);
1039    break;
1040  }
1041
1042  // FIXME: MEMOIZE!!
1043  SDNode *N = new SDNode(Opcode, Children);
1044  if (Opcode != ISD::ADD_PARTS && Opcode != ISD::SUB_PARTS) {
1045    N->setValueTypes(VT);
1046  } else {
1047    std::vector<MVT::ValueType> V(N->getNumOperands()/2, VT);
1048    N->setValueTypes(V);
1049  }
1050  AllNodes.push_back(N);
1051  return SDOperand(N, 0);
1052}
1053
1054SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,SDOperand N1,
1055                                MVT::ValueType EVT) {
1056
1057  switch (Opcode) {
1058  default: assert(0 && "Bad opcode for this accessor!");
1059  case ISD::FP_ROUND_INREG:
1060    assert(VT == N1.getValueType() && "Not an inreg round!");
1061    assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
1062           "Cannot FP_ROUND_INREG integer types");
1063    if (EVT == VT) return N1;  // Not actually rounding
1064    assert(EVT < VT && "Not rounding down!");
1065
1066    if (isa<ConstantFPSDNode>(N1))
1067      return getNode(ISD::FP_EXTEND, VT, getNode(ISD::FP_ROUND, EVT, N1));
1068    break;
1069  case ISD::ZERO_EXTEND_INREG:
1070  case ISD::SIGN_EXTEND_INREG:
1071    assert(VT == N1.getValueType() && "Not an inreg extend!");
1072    assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
1073           "Cannot *_EXTEND_INREG FP types");
1074    if (EVT == VT) return N1;  // Not actually extending
1075    assert(EVT < VT && "Not extending!");
1076
1077    // Extending a constant?  Just return the constant.
1078    if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1079      SDOperand Tmp = getNode(ISD::TRUNCATE, EVT, N1);
1080      if (Opcode == ISD::ZERO_EXTEND_INREG)
1081        return getNode(ISD::ZERO_EXTEND, VT, Tmp);
1082      else
1083        return getNode(ISD::SIGN_EXTEND, VT, Tmp);
1084    }
1085
1086    // If we are sign extending an extension, use the original source.
1087    if (N1.getOpcode() == ISD::ZERO_EXTEND_INREG ||
1088        N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1089      if (N1.getOpcode() == Opcode &&
1090          cast<MVTSDNode>(N1)->getExtraValueType() <= EVT)
1091        return N1;
1092    }
1093
1094    // If we are extending the result of a setcc, and we already know the
1095    // contents of the top bits, eliminate the extension.
1096    if (N1.getOpcode() == ISD::SETCC)
1097      switch (TLI.getSetCCResultContents()) {
1098      case TargetLowering::UndefinedSetCCResult: break;
1099      case TargetLowering::ZeroOrOneSetCCResult:
1100        if (Opcode == ISD::ZERO_EXTEND_INREG) return N1;
1101        break;
1102      case TargetLowering::ZeroOrNegativeOneSetCCResult:
1103        if (Opcode == ISD::SIGN_EXTEND_INREG) return N1;
1104        break;
1105      }
1106    break;
1107  }
1108
1109  EVTStruct NN;
1110  NN.Opcode = Opcode;
1111  NN.VT = VT;
1112  NN.EVT = EVT;
1113  NN.Ops.push_back(N1);
1114
1115  SDNode *&N = MVTSDNodes[NN];
1116  if (N) return SDOperand(N, 0);
1117  N = new MVTSDNode(Opcode, VT, N1, EVT);
1118  AllNodes.push_back(N);
1119  return SDOperand(N, 0);
1120}
1121
1122SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,SDOperand N1,
1123                                SDOperand N2, MVT::ValueType EVT) {
1124  switch (Opcode) {
1125  default:  assert(0 && "Bad opcode for this accessor!");
1126  case ISD::EXTLOAD:
1127  case ISD::SEXTLOAD:
1128  case ISD::ZEXTLOAD:
1129    // If they are asking for an extending loat from/to the same thing, return a
1130    // normal load.
1131    if (VT == EVT)
1132      return getNode(ISD::LOAD, VT, N1, N2);
1133    assert(EVT < VT && "Should only be an extending load, not truncating!");
1134    assert((Opcode == ISD::EXTLOAD || MVT::isInteger(VT)) &&
1135           "Cannot sign/zero extend a FP load!");
1136    assert(MVT::isInteger(VT) == MVT::isInteger(EVT) &&
1137           "Cannot convert from FP to Int or Int -> FP!");
1138    break;
1139  }
1140
1141  EVTStruct NN;
1142  NN.Opcode = Opcode;
1143  NN.VT = VT;
1144  NN.EVT = EVT;
1145  NN.Ops.push_back(N1);
1146  NN.Ops.push_back(N2);
1147
1148  SDNode *&N = MVTSDNodes[NN];
1149  if (N) return SDOperand(N, 0);
1150  N = new MVTSDNode(Opcode, VT, MVT::Other, N1, N2, EVT);
1151  AllNodes.push_back(N);
1152  return SDOperand(N, 0);
1153}
1154
1155SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,SDOperand N1,
1156                                SDOperand N2, SDOperand N3, MVT::ValueType EVT) {
1157  switch (Opcode) {
1158  default:  assert(0 && "Bad opcode for this accessor!");
1159  case ISD::TRUNCSTORE:
1160#if 0 // FIXME: If the target supports EVT natively, convert to a truncate/store
1161    // If this is a truncating store of a constant, convert to the desired type
1162    // and store it instead.
1163    if (isa<Constant>(N1)) {
1164      SDOperand Op = getNode(ISD::TRUNCATE, EVT, N1);
1165      if (isa<Constant>(Op))
1166        N1 = Op;
1167    }
1168    // Also for ConstantFP?
1169#endif
1170    if (N1.getValueType() == EVT)       // Normal store?
1171      return getNode(ISD::STORE, VT, N1, N2, N3);
1172    assert(N2.getValueType() > EVT && "Not a truncation?");
1173    assert(MVT::isInteger(N2.getValueType()) == MVT::isInteger(EVT) &&
1174           "Can't do FP-INT conversion!");
1175    break;
1176  }
1177
1178  EVTStruct NN;
1179  NN.Opcode = Opcode;
1180  NN.VT = VT;
1181  NN.EVT = EVT;
1182  NN.Ops.push_back(N1);
1183  NN.Ops.push_back(N2);
1184  NN.Ops.push_back(N3);
1185
1186  SDNode *&N = MVTSDNodes[NN];
1187  if (N) return SDOperand(N, 0);
1188  N = new MVTSDNode(Opcode, VT, N1, N2, N3, EVT);
1189  AllNodes.push_back(N);
1190  return SDOperand(N, 0);
1191}
1192
1193
1194/// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
1195/// indicated value.  This method ignores uses of other values defined by this
1196/// operation.
1197bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) {
1198  assert(Value < getNumValues() && "Bad value!");
1199
1200  // If there is only one value, this is easy.
1201  if (getNumValues() == 1)
1202    return use_size() == NUses;
1203  if (Uses.size() < NUses) return false;
1204
1205  SDOperand TheValue(this, Value);
1206
1207  std::set<SDNode*> UsersHandled;
1208
1209  for (std::vector<SDNode*>::iterator UI = Uses.begin(), E = Uses.end();
1210       UI != E; ++UI) {
1211    SDNode *User = *UI;
1212    if (User->getNumOperands() == 1 ||
1213        UsersHandled.insert(User).second)     // First time we've seen this?
1214      for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
1215        if (User->getOperand(i) == TheValue) {
1216          if (NUses == 0)
1217            return false;   // too many uses
1218          --NUses;
1219        }
1220  }
1221
1222  // Found exactly the right number of uses?
1223  return NUses == 0;
1224}
1225
1226
1227const char *SDNode::getOperationName() const {
1228  switch (getOpcode()) {
1229  default: return "<<Unknown>>";
1230  case ISD::PCMARKER:      return "PCMarker";
1231  case ISD::EntryToken:    return "EntryToken";
1232  case ISD::TokenFactor:   return "TokenFactor";
1233  case ISD::Constant:      return "Constant";
1234  case ISD::ConstantFP:    return "ConstantFP";
1235  case ISD::GlobalAddress: return "GlobalAddress";
1236  case ISD::FrameIndex:    return "FrameIndex";
1237  case ISD::BasicBlock:    return "BasicBlock";
1238  case ISD::ExternalSymbol: return "ExternalSymbol";
1239  case ISD::ConstantPool:  return "ConstantPoolIndex";
1240  case ISD::CopyToReg:     return "CopyToReg";
1241  case ISD::CopyFromReg:   return "CopyFromReg";
1242  case ISD::ImplicitDef:   return "ImplicitDef";
1243  case ISD::UNDEF:         return "undef";
1244
1245  // Unary operators
1246  case ISD::FABS:   return "fabs";
1247  case ISD::FNEG:   return "fneg";
1248
1249  // Binary operators
1250  case ISD::ADD:    return "add";
1251  case ISD::SUB:    return "sub";
1252  case ISD::MUL:    return "mul";
1253  case ISD::MULHU:  return "mulhu";
1254  case ISD::MULHS:  return "mulhs";
1255  case ISD::SDIV:   return "sdiv";
1256  case ISD::UDIV:   return "udiv";
1257  case ISD::SREM:   return "srem";
1258  case ISD::UREM:   return "urem";
1259  case ISD::AND:    return "and";
1260  case ISD::OR:     return "or";
1261  case ISD::XOR:    return "xor";
1262  case ISD::SHL:    return "shl";
1263  case ISD::SRA:    return "sra";
1264  case ISD::SRL:    return "srl";
1265
1266  case ISD::SELECT: return "select";
1267  case ISD::ADD_PARTS:   return "add_parts";
1268  case ISD::SUB_PARTS:   return "sub_parts";
1269  case ISD::SHL_PARTS:   return "shl_parts";
1270  case ISD::SRA_PARTS:   return "sra_parts";
1271  case ISD::SRL_PARTS:   return "srl_parts";
1272
1273    // Conversion operators.
1274  case ISD::SIGN_EXTEND: return "sign_extend";
1275  case ISD::ZERO_EXTEND: return "zero_extend";
1276  case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
1277  case ISD::ZERO_EXTEND_INREG: return "zero_extend_inreg";
1278  case ISD::TRUNCATE:    return "truncate";
1279  case ISD::FP_ROUND:    return "fp_round";
1280  case ISD::FP_ROUND_INREG: return "fp_round_inreg";
1281  case ISD::FP_EXTEND:   return "fp_extend";
1282
1283  case ISD::SINT_TO_FP:  return "sint_to_fp";
1284  case ISD::UINT_TO_FP:  return "uint_to_fp";
1285  case ISD::FP_TO_SINT:  return "fp_to_sint";
1286  case ISD::FP_TO_UINT:  return "fp_to_uint";
1287
1288    // Control flow instructions
1289  case ISD::BR:      return "br";
1290  case ISD::BRCOND:  return "brcond";
1291  case ISD::BRCONDTWOWAY:  return "brcondtwoway";
1292  case ISD::RET:     return "ret";
1293  case ISD::CALL:    return "call";
1294  case ISD::ADJCALLSTACKDOWN:  return "adjcallstackdown";
1295  case ISD::ADJCALLSTACKUP:    return "adjcallstackup";
1296
1297    // Other operators
1298  case ISD::LOAD:    return "load";
1299  case ISD::STORE:   return "store";
1300  case ISD::EXTLOAD:    return "extload";
1301  case ISD::SEXTLOAD:   return "sextload";
1302  case ISD::ZEXTLOAD:   return "zextload";
1303  case ISD::TRUNCSTORE: return "truncstore";
1304
1305  case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
1306  case ISD::EXTRACT_ELEMENT: return "extract_element";
1307  case ISD::BUILD_PAIR: return "build_pair";
1308  case ISD::MEMSET:  return "memset";
1309  case ISD::MEMCPY:  return "memcpy";
1310  case ISD::MEMMOVE: return "memmove";
1311
1312  case ISD::SETCC:
1313    const SetCCSDNode *SetCC = cast<SetCCSDNode>(this);
1314    switch (SetCC->getCondition()) {
1315    default: assert(0 && "Unknown setcc condition!");
1316    case ISD::SETOEQ:  return "setcc:setoeq";
1317    case ISD::SETOGT:  return "setcc:setogt";
1318    case ISD::SETOGE:  return "setcc:setoge";
1319    case ISD::SETOLT:  return "setcc:setolt";
1320    case ISD::SETOLE:  return "setcc:setole";
1321    case ISD::SETONE:  return "setcc:setone";
1322
1323    case ISD::SETO:    return "setcc:seto";
1324    case ISD::SETUO:   return "setcc:setuo";
1325    case ISD::SETUEQ:  return "setcc:setue";
1326    case ISD::SETUGT:  return "setcc:setugt";
1327    case ISD::SETUGE:  return "setcc:setuge";
1328    case ISD::SETULT:  return "setcc:setult";
1329    case ISD::SETULE:  return "setcc:setule";
1330    case ISD::SETUNE:  return "setcc:setune";
1331
1332    case ISD::SETEQ:   return "setcc:seteq";
1333    case ISD::SETGT:   return "setcc:setgt";
1334    case ISD::SETGE:   return "setcc:setge";
1335    case ISD::SETLT:   return "setcc:setlt";
1336    case ISD::SETLE:   return "setcc:setle";
1337    case ISD::SETNE:   return "setcc:setne";
1338    }
1339  }
1340}
1341
1342void SDNode::dump() const {
1343  std::cerr << (void*)this << ": ";
1344
1345  for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
1346    if (i) std::cerr << ",";
1347    if (getValueType(i) == MVT::Other)
1348      std::cerr << "ch";
1349    else
1350      std::cerr << MVT::getValueTypeString(getValueType(i));
1351  }
1352  std::cerr << " = " << getOperationName();
1353
1354  std::cerr << " ";
1355  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1356    if (i) std::cerr << ", ";
1357    std::cerr << (void*)getOperand(i).Val;
1358    if (unsigned RN = getOperand(i).ResNo)
1359      std::cerr << ":" << RN;
1360  }
1361
1362  if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
1363    std::cerr << "<" << CSDN->getValue() << ">";
1364  } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
1365    std::cerr << "<" << CSDN->getValue() << ">";
1366  } else if (const GlobalAddressSDNode *GADN =
1367             dyn_cast<GlobalAddressSDNode>(this)) {
1368    std::cerr << "<";
1369    WriteAsOperand(std::cerr, GADN->getGlobal()) << ">";
1370  } else if (const FrameIndexSDNode *FIDN =
1371	     dyn_cast<FrameIndexSDNode>(this)) {
1372    std::cerr << "<" << FIDN->getIndex() << ">";
1373  } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
1374    std::cerr << "<" << CP->getIndex() << ">";
1375  } else if (const BasicBlockSDNode *BBDN =
1376	     dyn_cast<BasicBlockSDNode>(this)) {
1377    std::cerr << "<";
1378    const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
1379    if (LBB)
1380      std::cerr << LBB->getName() << " ";
1381    std::cerr << (const void*)BBDN->getBasicBlock() << ">";
1382  } else if (const RegSDNode *C2V = dyn_cast<RegSDNode>(this)) {
1383    std::cerr << "<reg #" << C2V->getReg() << ">";
1384  } else if (const ExternalSymbolSDNode *ES =
1385             dyn_cast<ExternalSymbolSDNode>(this)) {
1386    std::cerr << "'" << ES->getSymbol() << "'";
1387  } else if (const MVTSDNode *M = dyn_cast<MVTSDNode>(this)) {
1388    std::cerr << " - Ty = " << MVT::getValueTypeString(M->getExtraValueType());
1389  }
1390}
1391
1392static void DumpNodes(SDNode *N, unsigned indent) {
1393  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1394    if (N->getOperand(i).Val->hasOneUse())
1395      DumpNodes(N->getOperand(i).Val, indent+2);
1396    else
1397      std::cerr << "\n" << std::string(indent+2, ' ')
1398                << (void*)N->getOperand(i).Val << ": <multiple use>";
1399
1400
1401  std::cerr << "\n" << std::string(indent, ' ');
1402  N->dump();
1403}
1404
1405void SelectionDAG::dump() const {
1406  std::cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
1407  std::vector<SDNode*> Nodes(AllNodes);
1408  std::sort(Nodes.begin(), Nodes.end());
1409
1410  for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1411    if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
1412      DumpNodes(Nodes[i], 2);
1413  }
1414
1415  DumpNodes(getRoot().Val, 2);
1416
1417  std::cerr << "\n\n";
1418}
1419
1420