SelectionDAG.cpp revision 5fa4fa4e0fde8aebc55a05258d2a274f3c7e1df6
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::FP_ROUND_INREG:
239  case ISD::EXTLOAD:
240  case ISD::SEXTLOAD:
241  case ISD::ZEXTLOAD: {
242    EVTStruct NN;
243    NN.Opcode = N->getOpcode();
244    NN.VT = N->getValueType(0);
245    NN.EVT = cast<MVTSDNode>(N)->getExtraValueType();
246    for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
247      NN.Ops.push_back(N->getOperand(i));
248    MVTSDNodes.erase(NN);
249    break;
250  }
251  default:
252    if (N->getNumOperands() == 1)
253      UnaryOps.erase(std::make_pair(N->getOpcode(),
254                                    std::make_pair(N->getOperand(0),
255                                                   N->getValueType(0))));
256    else if (N->getNumOperands() == 2)
257      BinaryOps.erase(std::make_pair(N->getOpcode(),
258                                     std::make_pair(N->getOperand(0),
259                                                    N->getOperand(1))));
260    else {
261      // Remove the node from the ArbitraryNodes map.
262      std::vector<MVT::ValueType> RV(N->value_begin(), N->value_end());
263      std::vector<SDOperand>     Ops(N->op_begin(), N->op_end());
264      ArbitraryNodes.erase(std::make_pair(N->getOpcode(),
265                                          std::make_pair(RV, Ops)));
266    }
267    break;
268  }
269
270  // Next, brutally remove the operand list.
271  while (!N->Operands.empty()) {
272    SDNode *O = N->Operands.back().Val;
273    N->Operands.pop_back();
274    O->removeUser(N);
275
276    // Now that we removed this operand, see if there are no uses of it left.
277    DeleteNodeIfDead(O, NodeSet);
278  }
279
280  // Remove the node from the nodes set and delete it.
281  std::set<SDNode*> &AllNodeSet = *(std::set<SDNode*>*)NodeSet;
282  AllNodeSet.erase(N);
283
284  // Now that the node is gone, check to see if any of the operands of this node
285  // are dead now.
286  delete N;
287}
288
289
290SelectionDAG::~SelectionDAG() {
291  for (unsigned i = 0, e = AllNodes.size(); i != e; ++i)
292    delete AllNodes[i];
293}
294
295SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT::ValueType VT) {
296  if (Op.getValueType() == VT) return Op;
297  int64_t Imm = ~0ULL >> (64-MVT::getSizeInBits(VT));
298  return getNode(ISD::AND, Op.getValueType(), Op,
299                 getConstant(Imm, Op.getValueType()));
300}
301
302SDOperand SelectionDAG::getConstant(uint64_t Val, MVT::ValueType VT) {
303  assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
304  // Mask out any bits that are not valid for this constant.
305  if (VT != MVT::i64)
306    Val &= ((uint64_t)1 << MVT::getSizeInBits(VT)) - 1;
307
308  SDNode *&N = Constants[std::make_pair(Val, VT)];
309  if (N) return SDOperand(N, 0);
310  N = new ConstantSDNode(Val, VT);
311  AllNodes.push_back(N);
312  return SDOperand(N, 0);
313}
314
315SDOperand SelectionDAG::getConstantFP(double Val, MVT::ValueType VT) {
316  assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
317  if (VT == MVT::f32)
318    Val = (float)Val;  // Mask out extra precision.
319
320  // Do the map lookup using the actual bit pattern for the floating point
321  // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
322  // we don't have issues with SNANs.
323  union {
324    double DV;
325    uint64_t IV;
326  };
327
328  DV = Val;
329
330  SDNode *&N = ConstantFPs[std::make_pair(IV, VT)];
331  if (N) return SDOperand(N, 0);
332  N = new ConstantFPSDNode(Val, VT);
333  AllNodes.push_back(N);
334  return SDOperand(N, 0);
335}
336
337
338
339SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
340                                         MVT::ValueType VT) {
341  SDNode *&N = GlobalValues[GV];
342  if (N) return SDOperand(N, 0);
343  N = new GlobalAddressSDNode(GV,VT);
344  AllNodes.push_back(N);
345  return SDOperand(N, 0);
346}
347
348SDOperand SelectionDAG::getFrameIndex(int FI, MVT::ValueType VT) {
349  SDNode *&N = FrameIndices[FI];
350  if (N) return SDOperand(N, 0);
351  N = new FrameIndexSDNode(FI, VT);
352  AllNodes.push_back(N);
353  return SDOperand(N, 0);
354}
355
356SDOperand SelectionDAG::getConstantPool(unsigned CPIdx, MVT::ValueType VT) {
357  SDNode *N = ConstantPoolIndices[CPIdx];
358  if (N) return SDOperand(N, 0);
359  N = new ConstantPoolSDNode(CPIdx, VT);
360  AllNodes.push_back(N);
361  return SDOperand(N, 0);
362}
363
364SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
365  SDNode *&N = BBNodes[MBB];
366  if (N) return SDOperand(N, 0);
367  N = new BasicBlockSDNode(MBB);
368  AllNodes.push_back(N);
369  return SDOperand(N, 0);
370}
371
372SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT::ValueType VT) {
373  SDNode *&N = ExternalSymbols[Sym];
374  if (N) return SDOperand(N, 0);
375  N = new ExternalSymbolSDNode(Sym, VT);
376  AllNodes.push_back(N);
377  return SDOperand(N, 0);
378}
379
380SDOperand SelectionDAG::getSetCC(ISD::CondCode Cond, MVT::ValueType VT,
381                                 SDOperand N1, SDOperand N2) {
382  // These setcc operations always fold.
383  switch (Cond) {
384  default: break;
385  case ISD::SETFALSE:
386  case ISD::SETFALSE2: return getConstant(0, VT);
387  case ISD::SETTRUE:
388  case ISD::SETTRUE2:  return getConstant(1, VT);
389  }
390
391  if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
392    uint64_t C2 = N2C->getValue();
393    if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
394      uint64_t C1 = N1C->getValue();
395
396      // Sign extend the operands if required
397      if (ISD::isSignedIntSetCC(Cond)) {
398        C1 = N1C->getSignExtended();
399        C2 = N2C->getSignExtended();
400      }
401
402      switch (Cond) {
403      default: assert(0 && "Unknown integer setcc!");
404      case ISD::SETEQ:  return getConstant(C1 == C2, VT);
405      case ISD::SETNE:  return getConstant(C1 != C2, VT);
406      case ISD::SETULT: return getConstant(C1 <  C2, VT);
407      case ISD::SETUGT: return getConstant(C1 >  C2, VT);
408      case ISD::SETULE: return getConstant(C1 <= C2, VT);
409      case ISD::SETUGE: return getConstant(C1 >= C2, VT);
410      case ISD::SETLT:  return getConstant((int64_t)C1 <  (int64_t)C2, VT);
411      case ISD::SETGT:  return getConstant((int64_t)C1 >  (int64_t)C2, VT);
412      case ISD::SETLE:  return getConstant((int64_t)C1 <= (int64_t)C2, VT);
413      case ISD::SETGE:  return getConstant((int64_t)C1 >= (int64_t)C2, VT);
414      }
415    } else {
416      // If the LHS is a ZERO_EXTEND and if this is an ==/!= comparison, perform
417      // the comparison on the input.
418      if (N1.getOpcode() == ISD::ZERO_EXTEND) {
419        unsigned InSize = MVT::getSizeInBits(N1.getOperand(0).getValueType());
420
421        // If the comparison constant has bits in the upper part, the
422        // zero-extended value could never match.
423        if (C2 & (~0ULL << InSize)) {
424          unsigned VSize = MVT::getSizeInBits(N1.getValueType());
425          switch (Cond) {
426          case ISD::SETUGT:
427          case ISD::SETUGE:
428          case ISD::SETEQ: return getConstant(0, VT);
429          case ISD::SETULT:
430          case ISD::SETULE:
431          case ISD::SETNE: return getConstant(1, VT);
432          case ISD::SETGT:
433          case ISD::SETGE:
434            // True if the sign bit of C2 is set.
435            return getConstant((C2 & (1ULL << VSize)) != 0, VT);
436          case ISD::SETLT:
437          case ISD::SETLE:
438            // True if the sign bit of C2 isn't set.
439            return getConstant((C2 & (1ULL << VSize)) == 0, VT);
440          default:
441            break;
442          }
443        }
444
445        // Otherwise, we can perform the comparison with the low bits.
446        switch (Cond) {
447        case ISD::SETEQ:
448        case ISD::SETNE:
449        case ISD::SETUGT:
450        case ISD::SETUGE:
451        case ISD::SETULT:
452        case ISD::SETULE:
453          return getSetCC(Cond, VT, N1.getOperand(0),
454                          getConstant(C2, N1.getOperand(0).getValueType()));
455        default:
456          break;   // todo, be more careful with signed comparisons
457        }
458      }
459
460
461      uint64_t MinVal, MaxVal;
462      unsigned OperandBitSize = MVT::getSizeInBits(N2C->getValueType(0));
463      if (ISD::isSignedIntSetCC(Cond)) {
464        MinVal = 1ULL << (OperandBitSize-1);
465        if (OperandBitSize != 1)   // Avoid X >> 64, which is undefined.
466          MaxVal = ~0ULL >> (65-OperandBitSize);
467        else
468          MaxVal = 0;
469      } else {
470        MinVal = 0;
471        MaxVal = ~0ULL >> (64-OperandBitSize);
472      }
473
474      // Canonicalize GE/LE comparisons to use GT/LT comparisons.
475      if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
476        if (C2 == MinVal) return getConstant(1, VT);   // X >= MIN --> true
477        --C2;                                          // X >= C1 --> X > (C1-1)
478        Cond = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
479        N2 = getConstant(C2, N2.getValueType());
480        N2C = cast<ConstantSDNode>(N2.Val);
481      }
482
483      if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
484        if (C2 == MaxVal) return getConstant(1, VT);   // X <= MAX --> true
485        ++C2;                                          // X <= C1 --> X < (C1+1)
486        Cond = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
487        N2 = getConstant(C2, N2.getValueType());
488        N2C = cast<ConstantSDNode>(N2.Val);
489      }
490
491      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C2 == MinVal)
492        return getConstant(0, VT);      // X < MIN --> false
493
494      // Canonicalize setgt X, Min --> setne X, Min
495      if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C2 == MinVal)
496        return getSetCC(ISD::SETNE, VT, N1, N2);
497
498      // If we have setult X, 1, turn it into seteq X, 0
499      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C2 == MinVal+1)
500        return getSetCC(ISD::SETEQ, VT, N1,
501                        getConstant(MinVal, N1.getValueType()));
502      // If we have setugt X, Max-1, turn it into seteq X, Max
503      else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C2 == MaxVal-1)
504        return getSetCC(ISD::SETEQ, VT, N1,
505                        getConstant(MaxVal, N1.getValueType()));
506
507      // If we have "setcc X, C1", check to see if we can shrink the immediate
508      // by changing cc.
509
510      // SETUGT X, SINTMAX  -> SETLT X, 0
511      if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
512          C2 == (~0ULL >> (65-OperandBitSize)))
513        return getSetCC(ISD::SETLT, VT, N1, getConstant(0, N2.getValueType()));
514
515      // FIXME: Implement the rest of these.
516
517
518      // Fold bit comparisons when we can.
519      if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
520          VT == N1.getValueType() && N1.getOpcode() == ISD::AND)
521        if (ConstantSDNode *AndRHS =
522                    dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
523          if (Cond == ISD::SETNE && C2 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
524            // Perform the xform if the AND RHS is a single bit.
525            if ((AndRHS->getValue() & (AndRHS->getValue()-1)) == 0) {
526              return getNode(ISD::SRL, VT, N1,
527                             getConstant(ExactLog2(AndRHS->getValue()),
528                                                   TLI.getShiftAmountTy()));
529            }
530          } else if (Cond == ISD::SETEQ && C2 == AndRHS->getValue()) {
531            // (X & 8) == 8  -->  (X & 8) >> 3
532            // Perform the xform if C2 is a single bit.
533            if ((C2 & (C2-1)) == 0) {
534              return getNode(ISD::SRL, VT, N1,
535                             getConstant(ExactLog2(C2),TLI.getShiftAmountTy()));
536            }
537          }
538        }
539    }
540  } else if (isa<ConstantSDNode>(N1.Val)) {
541      // Ensure that the constant occurs on the RHS.
542    return getSetCC(ISD::getSetCCSwappedOperands(Cond), VT, N2, N1);
543  }
544
545  if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val))
546    if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
547      double C1 = N1C->getValue(), C2 = N2C->getValue();
548
549      switch (Cond) {
550      default: break; // FIXME: Implement the rest of these!
551      case ISD::SETEQ:  return getConstant(C1 == C2, VT);
552      case ISD::SETNE:  return getConstant(C1 != C2, VT);
553      case ISD::SETLT:  return getConstant(C1 < C2, VT);
554      case ISD::SETGT:  return getConstant(C1 > C2, VT);
555      case ISD::SETLE:  return getConstant(C1 <= C2, VT);
556      case ISD::SETGE:  return getConstant(C1 >= C2, VT);
557      }
558    } else {
559      // Ensure that the constant occurs on the RHS.
560      Cond = ISD::getSetCCSwappedOperands(Cond);
561      std::swap(N1, N2);
562    }
563
564  if (N1 == N2) {
565    // We can always fold X == Y for integer setcc's.
566    if (MVT::isInteger(N1.getValueType()))
567      return getConstant(ISD::isTrueWhenEqual(Cond), VT);
568    unsigned UOF = ISD::getUnorderedFlavor(Cond);
569    if (UOF == 2)   // FP operators that are undefined on NaNs.
570      return getConstant(ISD::isTrueWhenEqual(Cond), VT);
571    if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
572      return getConstant(UOF, VT);
573    // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
574    // if it is not already.
575    Cond = UOF == 0 ? ISD::SETUO : ISD::SETO;
576  }
577
578  if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
579      MVT::isInteger(N1.getValueType())) {
580    if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
581        N1.getOpcode() == ISD::XOR) {
582      // Simplify (X+Y) == (X+Z) -->  Y == Z
583      if (N1.getOpcode() == N2.getOpcode()) {
584        if (N1.getOperand(0) == N2.getOperand(0))
585          return getSetCC(Cond, VT, N1.getOperand(1), N2.getOperand(1));
586        if (N1.getOperand(1) == N2.getOperand(1))
587          return getSetCC(Cond, VT, N1.getOperand(0), N2.getOperand(0));
588        if (isCommutativeBinOp(N1.getOpcode())) {
589          // If X op Y == Y op X, try other combinations.
590          if (N1.getOperand(0) == N2.getOperand(1))
591            return getSetCC(Cond, VT, N1.getOperand(1), N2.getOperand(0));
592          if (N1.getOperand(1) == N2.getOperand(0))
593            return getSetCC(Cond, VT, N1.getOperand(1), N2.getOperand(1));
594        }
595      }
596
597      // FIXME: move this stuff to the DAG Combiner when it exists!
598
599      // Simplify (X+Z) == X -->  Z == 0
600      if (N1.getOperand(0) == N2)
601        return getSetCC(Cond, VT, N1.getOperand(1),
602                        getConstant(0, N1.getValueType()));
603      if (N1.getOperand(1) == N2) {
604        if (isCommutativeBinOp(N1.getOpcode()))
605          return getSetCC(Cond, VT, N1.getOperand(0),
606                          getConstant(0, N1.getValueType()));
607        else {
608          assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
609          // (Z-X) == X  --> Z == X<<1
610          return getSetCC(Cond, VT, N1.getOperand(0),
611                          getNode(ISD::SHL, N2.getValueType(),
612                                  N2, getConstant(1, TLI.getShiftAmountTy())));
613        }
614      }
615    }
616
617    if (N2.getOpcode() == ISD::ADD || N2.getOpcode() == ISD::SUB ||
618        N2.getOpcode() == ISD::XOR) {
619      // Simplify  X == (X+Z) -->  Z == 0
620      if (N2.getOperand(0) == N1)
621        return getSetCC(Cond, VT, N2.getOperand(1),
622                        getConstant(0, N2.getValueType()));
623      else if (N2.getOperand(1) == N1)
624        return getSetCC(Cond, VT, N2.getOperand(0),
625                        getConstant(0, N2.getValueType()));
626    }
627  }
628
629  // Fold away ALL boolean setcc's.
630  if (N1.getValueType() == MVT::i1) {
631    switch (Cond) {
632    default: assert(0 && "Unknown integer setcc!");
633    case ISD::SETEQ:  // X == Y  -> (X^Y)^1
634      N1 = getNode(ISD::XOR, MVT::i1,
635                   getNode(ISD::XOR, MVT::i1, N1, N2),
636                   getConstant(1, MVT::i1));
637      break;
638    case ISD::SETNE:  // X != Y   -->  (X^Y)
639      N1 = getNode(ISD::XOR, MVT::i1, N1, N2);
640      break;
641    case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  X^1 & Y
642    case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  X^1 & Y
643      N1 = getNode(ISD::AND, MVT::i1, N2,
644                   getNode(ISD::XOR, MVT::i1, N1, getConstant(1, MVT::i1)));
645      break;
646    case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  Y^1 & X
647    case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  Y^1 & X
648      N1 = getNode(ISD::AND, MVT::i1, N1,
649                   getNode(ISD::XOR, MVT::i1, N2, getConstant(1, MVT::i1)));
650      break;
651    case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  X^1 | Y
652    case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  X^1 | Y
653      N1 = getNode(ISD::OR, MVT::i1, N2,
654                   getNode(ISD::XOR, MVT::i1, N1, getConstant(1, MVT::i1)));
655      break;
656    case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  Y^1 | X
657    case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  Y^1 | X
658      N1 = getNode(ISD::OR, MVT::i1, N1,
659                   getNode(ISD::XOR, MVT::i1, N2, getConstant(1, MVT::i1)));
660      break;
661    }
662    if (VT != MVT::i1)
663      N1 = getNode(ISD::ZERO_EXTEND, VT, N1);
664    return N1;
665  }
666
667
668  SetCCSDNode *&N = SetCCs[std::make_pair(std::make_pair(N1, N2),
669                                          std::make_pair(Cond, VT))];
670  if (N) return SDOperand(N, 0);
671  N = new SetCCSDNode(Cond, N1, N2);
672  N->setValueTypes(VT);
673  AllNodes.push_back(N);
674  return SDOperand(N, 0);
675}
676
677
678
679/// getNode - Gets or creates the specified node.
680///
681SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
682  SDNode *N = new SDNode(Opcode, VT);
683  AllNodes.push_back(N);
684  return SDOperand(N, 0);
685}
686
687SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
688                                SDOperand Operand) {
689  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
690    uint64_t Val = C->getValue();
691    switch (Opcode) {
692    default: break;
693    case ISD::SIGN_EXTEND: return getConstant(C->getSignExtended(), VT);
694    case ISD::ZERO_EXTEND: return getConstant(Val, VT);
695    case ISD::TRUNCATE:    return getConstant(Val, VT);
696    case ISD::SINT_TO_FP:  return getConstantFP(C->getSignExtended(), VT);
697    case ISD::UINT_TO_FP:  return getConstantFP(C->getValue(), VT);
698    }
699  }
700
701  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val))
702    switch (Opcode) {
703    case ISD::FNEG:
704      return getConstantFP(-C->getValue(), VT);
705    case ISD::FP_ROUND:
706    case ISD::FP_EXTEND:
707      return getConstantFP(C->getValue(), VT);
708    case ISD::FP_TO_SINT:
709      return getConstant((int64_t)C->getValue(), VT);
710    case ISD::FP_TO_UINT:
711      return getConstant((uint64_t)C->getValue(), VT);
712    }
713
714  unsigned OpOpcode = Operand.Val->getOpcode();
715  switch (Opcode) {
716  case ISD::TokenFactor:
717    return Operand;         // Factor of one node?  No factor.
718  case ISD::SIGN_EXTEND:
719    if (Operand.getValueType() == VT) return Operand;   // noop extension
720    if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
721      return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
722    break;
723  case ISD::ZERO_EXTEND:
724    if (Operand.getValueType() == VT) return Operand;   // noop extension
725    if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
726      return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
727    break;
728  case ISD::TRUNCATE:
729    if (Operand.getValueType() == VT) return Operand;   // noop truncate
730    if (OpOpcode == ISD::TRUNCATE)
731      return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
732    else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND) {
733      // If the source is smaller than the dest, we still need an extend.
734      if (Operand.Val->getOperand(0).getValueType() < VT)
735        return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
736      else if (Operand.Val->getOperand(0).getValueType() > VT)
737        return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
738      else
739        return Operand.Val->getOperand(0);
740    }
741    break;
742  case ISD::FNEG:
743    if (OpOpcode == ISD::SUB)   // -(X-Y) -> (Y-X)
744      return getNode(ISD::SUB, VT, Operand.Val->getOperand(1),
745                     Operand.Val->getOperand(0));
746    if (OpOpcode == ISD::FNEG)  // --X -> X
747      return Operand.Val->getOperand(0);
748    break;
749  case ISD::FABS:
750    if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
751      return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
752    break;
753  }
754
755  SDNode *&N = UnaryOps[std::make_pair(Opcode, std::make_pair(Operand, VT))];
756  if (N) return SDOperand(N, 0);
757  N = new SDNode(Opcode, Operand);
758  N->setValueTypes(VT);
759  AllNodes.push_back(N);
760  return SDOperand(N, 0);
761}
762
763/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
764/// this predicate to simplify operations downstream.  V and Mask are known to
765/// be the same type.
766static bool MaskedValueIsZero(const SDOperand &Op, uint64_t Mask,
767                              const TargetLowering &TLI) {
768  unsigned SrcBits;
769  if (Mask == 0) return true;
770
771  // If we know the result of a setcc has the top bits zero, use this info.
772  switch (Op.getOpcode()) {
773  case ISD::UNDEF:
774    return true;
775  case ISD::Constant:
776    return (cast<ConstantSDNode>(Op)->getValue() & Mask) == 0;
777
778  case ISD::SETCC:
779    return ((Mask & 1) == 0) &&
780           TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult;
781
782  case ISD::ZEXTLOAD:
783    SrcBits = MVT::getSizeInBits(cast<MVTSDNode>(Op)->getExtraValueType());
784    return (Mask & ((1ULL << SrcBits)-1)) == 0; // Returning only the zext bits.
785  case ISD::ZERO_EXTEND:
786    SrcBits = MVT::getSizeInBits(Op.getOperand(0).getValueType());
787    return MaskedValueIsZero(Op.getOperand(0),Mask & ((1ULL << SrcBits)-1),TLI);
788
789  case ISD::AND:
790    // (X & C1) & C2 == 0   iff   C1 & C2 == 0.
791    if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
792      return MaskedValueIsZero(Op.getOperand(0),AndRHS->getValue() & Mask, TLI);
793
794    // FALL THROUGH
795  case ISD::OR:
796  case ISD::XOR:
797    return MaskedValueIsZero(Op.getOperand(0), Mask, TLI) &&
798           MaskedValueIsZero(Op.getOperand(1), Mask, TLI);
799  case ISD::SELECT:
800    return MaskedValueIsZero(Op.getOperand(1), Mask, TLI) &&
801           MaskedValueIsZero(Op.getOperand(2), Mask, TLI);
802
803  case ISD::SRL:
804    // (ushr X, C1) & C2 == 0   iff  X & (C2 << C1) == 0
805    if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
806      uint64_t NewVal = Mask << ShAmt->getValue();
807      SrcBits = MVT::getSizeInBits(Op.getValueType());
808      if (SrcBits != 64) NewVal &= (1ULL << SrcBits)-1;
809      return MaskedValueIsZero(Op.getOperand(0), NewVal, TLI);
810    }
811    return false;
812  case ISD::SHL:
813    // (ushl X, C1) & C2 == 0   iff  X & (C2 >> C1) == 0
814    if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
815      uint64_t NewVal = Mask >> ShAmt->getValue();
816      return MaskedValueIsZero(Op.getOperand(0), NewVal, TLI);
817    }
818    return false;
819    // TODO we could handle some SRA cases here.
820  default: break;
821  }
822
823  return false;
824}
825
826
827
828SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
829                                SDOperand N1, SDOperand N2) {
830#ifndef NDEBUG
831  switch (Opcode) {
832  case ISD::TokenFactor:
833    assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
834           N2.getValueType() == MVT::Other && "Invalid token factor!");
835    break;
836  case ISD::AND:
837  case ISD::OR:
838  case ISD::XOR:
839  case ISD::UDIV:
840  case ISD::UREM:
841    assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
842    // fall through
843  case ISD::ADD:
844  case ISD::SUB:
845  case ISD::MUL:
846  case ISD::SDIV:
847  case ISD::SREM:
848    assert(N1.getValueType() == N2.getValueType() &&
849           N1.getValueType() == VT && "Binary operator types must match!");
850    break;
851
852  case ISD::SHL:
853  case ISD::SRA:
854  case ISD::SRL:
855    assert(VT == N1.getValueType() &&
856           "Shift operators return type must be the same as their first arg");
857    assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
858           VT != MVT::i1 && "Shifts only work on integers");
859    break;
860  default: break;
861  }
862#endif
863
864  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
865  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
866  if (N1C) {
867    if (N2C) {
868      uint64_t C1 = N1C->getValue(), C2 = N2C->getValue();
869      switch (Opcode) {
870      case ISD::ADD: return getConstant(C1 + C2, VT);
871      case ISD::SUB: return getConstant(C1 - C2, VT);
872      case ISD::MUL: return getConstant(C1 * C2, VT);
873      case ISD::UDIV:
874        if (C2) return getConstant(C1 / C2, VT);
875        break;
876      case ISD::UREM :
877        if (C2) return getConstant(C1 % C2, VT);
878        break;
879      case ISD::SDIV :
880        if (C2) return getConstant(N1C->getSignExtended() /
881                                   N2C->getSignExtended(), VT);
882        break;
883      case ISD::SREM :
884        if (C2) return getConstant(N1C->getSignExtended() %
885                                   N2C->getSignExtended(), VT);
886        break;
887      case ISD::AND  : return getConstant(C1 & C2, VT);
888      case ISD::OR   : return getConstant(C1 | C2, VT);
889      case ISD::XOR  : return getConstant(C1 ^ C2, VT);
890      case ISD::SHL  : return getConstant(C1 << (int)C2, VT);
891      case ISD::SRL  : return getConstant(C1 >> (unsigned)C2, VT);
892      case ISD::SRA  : return getConstant(N1C->getSignExtended() >>(int)C2, VT);
893      default: break;
894      }
895
896    } else {      // Cannonicalize constant to RHS if commutative
897      if (isCommutativeBinOp(Opcode)) {
898        std::swap(N1C, N2C);
899        std::swap(N1, N2);
900      }
901    }
902
903    switch (Opcode) {
904    default: break;
905    case ISD::SHL:    // shl  0, X -> 0
906      if (N1C->isNullValue()) return N1;
907      break;
908    case ISD::SRL:    // srl  0, X -> 0
909      if (N1C->isNullValue()) return N1;
910      break;
911    case ISD::SRA:    // sra -1, X -> -1
912      if (N1C->isAllOnesValue()) return N1;
913      break;
914    }
915  }
916
917  if (N2C) {
918    uint64_t C2 = N2C->getValue();
919
920    switch (Opcode) {
921    case ISD::ADD:
922      if (!C2) return N1;         // add X, 0 -> X
923      break;
924    case ISD::SUB:
925      if (!C2) return N1;         // sub X, 0 -> X
926      return getNode(ISD::ADD, VT, N1, getConstant(-C2, VT));
927    case ISD::MUL:
928      if (!C2) return N2;         // mul X, 0 -> 0
929      if (N2C->isAllOnesValue()) // mul X, -1 -> 0-X
930        return getNode(ISD::SUB, VT, getConstant(0, VT), N1);
931
932      // FIXME: Move this to the DAG combiner when it exists.
933      if ((C2 & C2-1) == 0) {
934        SDOperand ShAmt = getConstant(ExactLog2(C2), TLI.getShiftAmountTy());
935        return getNode(ISD::SHL, VT, N1, ShAmt);
936      }
937      break;
938
939    case ISD::UDIV:
940      // FIXME: Move this to the DAG combiner when it exists.
941      if ((C2 & C2-1) == 0 && C2) {
942        SDOperand ShAmt = getConstant(ExactLog2(C2), TLI.getShiftAmountTy());
943        return getNode(ISD::SRL, VT, N1, ShAmt);
944      }
945      break;
946
947    case ISD::SHL:
948    case ISD::SRL:
949    case ISD::SRA:
950      // If the shift amount is bigger than the size of the data, then all the
951      // bits are shifted out.  Simplify to undef.
952      if (C2 >= MVT::getSizeInBits(N1.getValueType())) {
953        return getNode(ISD::UNDEF, N1.getValueType());
954      }
955      if (C2 == 0) return N1;
956
957      if (Opcode == ISD::SHL && N1.getNumOperands() == 2)
958        if (ConstantSDNode *OpSA = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
959          unsigned OpSAC = OpSA->getValue();
960          if (N1.getOpcode() == ISD::SHL) {
961            if (C2+OpSAC >= MVT::getSizeInBits(N1.getValueType()))
962              return getConstant(0, N1.getValueType());
963            return getNode(ISD::SHL, N1.getValueType(), N1.getOperand(0),
964                           getConstant(C2+OpSAC, N2.getValueType()));
965          } else if (N1.getOpcode() == ISD::SRL) {
966            // (X >> C1) << C2:  if C2 > C1, ((X & ~0<<C1) << C2-C1)
967            SDOperand Mask = getNode(ISD::AND, VT, N1.getOperand(0),
968                                     getConstant(~0ULL << OpSAC, VT));
969            if (C2 > OpSAC) {
970              return getNode(ISD::SHL, VT, Mask,
971                             getConstant(C2-OpSAC, N2.getValueType()));
972            } else {
973              // (X >> C1) << C2:  if C2 <= C1, ((X & ~0<<C1) >> C1-C2)
974              return getNode(ISD::SRL, VT, Mask,
975                             getConstant(OpSAC-C2, N2.getValueType()));
976            }
977          } else if (N1.getOpcode() == ISD::SRA) {
978            // if C1 == C2, just mask out low bits.
979            if (C2 == OpSAC)
980              return getNode(ISD::AND, VT, N1.getOperand(0),
981                             getConstant(~0ULL << C2, VT));
982          }
983        }
984      break;
985
986    case ISD::AND:
987      if (!C2) return N2;         // X and 0 -> 0
988      if (N2C->isAllOnesValue())
989        return N1;                // X and -1 -> X
990
991      if (MaskedValueIsZero(N1, C2, TLI))  // X and 0 -> 0
992        return getConstant(0, VT);
993
994      {
995        uint64_t NotC2 = ~C2;
996        if (VT != MVT::i64)
997          NotC2 &= (1ULL << MVT::getSizeInBits(VT))-1;
998
999        if (MaskedValueIsZero(N1, NotC2, TLI))
1000          return N1;                // if (X & ~C2) -> 0, the and is redundant
1001      }
1002
1003      // FIXME: Should add a corresponding version of this for
1004      // ZERO_EXTEND/SIGN_EXTEND by converting them to an ANY_EXTEND node which
1005      // we don't have yet.
1006
1007      // and (sign_extend_inreg x:16:32), 1 -> and x, 1
1008      if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1009        // If we are masking out the part of our input that was extended, just
1010        // mask the input to the extension directly.
1011        unsigned ExtendBits =
1012          MVT::getSizeInBits(cast<MVTSDNode>(N1)->getExtraValueType());
1013        if ((C2 & (~0ULL << ExtendBits)) == 0)
1014          return getNode(ISD::AND, VT, N1.getOperand(0), N2);
1015      }
1016      break;
1017    case ISD::OR:
1018      if (!C2)return N1;          // X or 0 -> X
1019      if (N2C->isAllOnesValue())
1020        return N2;                // X or -1 -> -1
1021      break;
1022    case ISD::XOR:
1023      if (!C2) return N1;        // X xor 0 -> X
1024      if (N2C->isAllOnesValue()) {
1025        if (SetCCSDNode *SetCC = dyn_cast<SetCCSDNode>(N1.Val)){
1026          // !(X op Y) -> (X !op Y)
1027          bool isInteger = MVT::isInteger(SetCC->getOperand(0).getValueType());
1028          return getSetCC(ISD::getSetCCInverse(SetCC->getCondition(),isInteger),
1029                          SetCC->getValueType(0),
1030                          SetCC->getOperand(0), SetCC->getOperand(1));
1031        } else if (N1.getOpcode() == ISD::AND || N1.getOpcode() == ISD::OR) {
1032          SDNode *Op = N1.Val;
1033          // !(X or Y) -> (!X and !Y) iff X or Y are freely invertible
1034          // !(X and Y) -> (!X or !Y) iff X or Y are freely invertible
1035          SDOperand LHS = Op->getOperand(0), RHS = Op->getOperand(1);
1036          if (isInvertibleForFree(RHS) || isInvertibleForFree(LHS)) {
1037            LHS = getNode(ISD::XOR, VT, LHS, N2);  // RHS = ~LHS
1038            RHS = getNode(ISD::XOR, VT, RHS, N2);  // RHS = ~RHS
1039            if (Op->getOpcode() == ISD::AND)
1040              return getNode(ISD::OR, VT, LHS, RHS);
1041            return getNode(ISD::AND, VT, LHS, RHS);
1042          }
1043        }
1044        // X xor -1 -> not(x)  ?
1045      }
1046      break;
1047    }
1048
1049    // Reassociate ((X op C1) op C2) if possible.
1050    if (N1.getOpcode() == Opcode && isAssociativeBinOp(Opcode))
1051      if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N1.Val->getOperand(1)))
1052        return getNode(Opcode, VT, N1.Val->getOperand(0),
1053                       getNode(Opcode, VT, N2, N1.Val->getOperand(1)));
1054  }
1055
1056  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
1057  ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
1058  if (N1CFP)
1059    if (N2CFP) {
1060      double C1 = N1CFP->getValue(), C2 = N2CFP->getValue();
1061      switch (Opcode) {
1062      case ISD::ADD: return getConstantFP(C1 + C2, VT);
1063      case ISD::SUB: return getConstantFP(C1 - C2, VT);
1064      case ISD::MUL: return getConstantFP(C1 * C2, VT);
1065      case ISD::SDIV:
1066        if (C2) return getConstantFP(C1 / C2, VT);
1067        break;
1068      case ISD::SREM :
1069        if (C2) return getConstantFP(fmod(C1, C2), VT);
1070        break;
1071      default: break;
1072      }
1073
1074    } else {      // Cannonicalize constant to RHS if commutative
1075      if (isCommutativeBinOp(Opcode)) {
1076        std::swap(N1CFP, N2CFP);
1077        std::swap(N1, N2);
1078      }
1079    }
1080
1081  // Finally, fold operations that do not require constants.
1082  switch (Opcode) {
1083  case ISD::TokenFactor:
1084    if (N1.getOpcode() == ISD::EntryToken)
1085      return N2;
1086    if (N2.getOpcode() == ISD::EntryToken)
1087      return N1;
1088    break;
1089
1090  case ISD::AND:
1091  case ISD::OR:
1092    if (SetCCSDNode *LHS = dyn_cast<SetCCSDNode>(N1.Val))
1093      if (SetCCSDNode *RHS = dyn_cast<SetCCSDNode>(N2.Val)) {
1094        SDOperand LL = LHS->getOperand(0), RL = RHS->getOperand(0);
1095        SDOperand LR = LHS->getOperand(1), RR = RHS->getOperand(1);
1096        ISD::CondCode Op2 = RHS->getCondition();
1097
1098        if (LR == RR && isa<ConstantSDNode>(LR) &&
1099            Op2 == LHS->getCondition() && MVT::isInteger(LL.getValueType())) {
1100          // (X != 0) | (Y != 0) -> (X|Y != 0)
1101          // (X == 0) & (Y == 0) -> (X|Y == 0)
1102          // (X <  0) | (Y <  0) -> (X|Y < 0)
1103          if (cast<ConstantSDNode>(LR)->getValue() == 0 &&
1104              ((Op2 == ISD::SETEQ && Opcode == ISD::AND) ||
1105               (Op2 == ISD::SETNE && Opcode == ISD::OR) ||
1106               (Op2 == ISD::SETLT && Opcode == ISD::OR)))
1107            return getSetCC(Op2, VT,
1108                            getNode(ISD::OR, LR.getValueType(), LL, RL), LR);
1109
1110          if (cast<ConstantSDNode>(LR)->isAllOnesValue()) {
1111            // (X == -1) & (Y == -1) -> (X&Y == -1)
1112            // (X != -1) | (Y != -1) -> (X&Y != -1)
1113            // (X >  -1) | (Y >  -1) -> (X&Y >  -1)
1114            if ((Opcode == ISD::AND && Op2 == ISD::SETEQ) ||
1115                (Opcode == ISD::OR  && Op2 == ISD::SETNE) ||
1116                (Opcode == ISD::OR  && Op2 == ISD::SETGT))
1117              return getSetCC(Op2, VT,
1118                            getNode(ISD::AND, LR.getValueType(), LL, RL), LR);
1119            // (X >  -1) & (Y >  -1) -> (X|Y > -1)
1120            if (Opcode == ISD::AND && Op2 == ISD::SETGT)
1121              return getSetCC(Op2, VT,
1122                            getNode(ISD::OR, LR.getValueType(), LL, RL), LR);
1123          }
1124        }
1125
1126        // (X op1 Y) | (Y op2 X) -> (X op1 Y) | (X swapop2 Y)
1127        if (LL == RR && LR == RL) {
1128          Op2 = ISD::getSetCCSwappedOperands(Op2);
1129          goto MatchedBackwards;
1130        }
1131
1132        if (LL == RL && LR == RR) {
1133        MatchedBackwards:
1134          ISD::CondCode Result;
1135          bool isInteger = MVT::isInteger(LL.getValueType());
1136          if (Opcode == ISD::OR)
1137            Result = ISD::getSetCCOrOperation(LHS->getCondition(), Op2,
1138                                              isInteger);
1139          else
1140            Result = ISD::getSetCCAndOperation(LHS->getCondition(), Op2,
1141                                               isInteger);
1142          if (Result != ISD::SETCC_INVALID)
1143            return getSetCC(Result, LHS->getValueType(0), LL, LR);
1144        }
1145      }
1146
1147    // and/or zext(a), zext(b) -> zext(and/or a, b)
1148    if (N1.getOpcode() == ISD::ZERO_EXTEND &&
1149        N2.getOpcode() == ISD::ZERO_EXTEND &&
1150        N1.getOperand(0).getValueType() == N2.getOperand(0).getValueType())
1151      return getNode(ISD::ZERO_EXTEND, VT,
1152                     getNode(Opcode, N1.getOperand(0).getValueType(),
1153                             N1.getOperand(0), N2.getOperand(0)));
1154    break;
1155  case ISD::XOR:
1156    if (N1 == N2) return getConstant(0, VT);  // xor X, Y -> 0
1157    break;
1158  case ISD::ADD:
1159    if (N2.getOpcode() == ISD::FNEG)          // (A+ (-B) -> A-B
1160      return getNode(ISD::SUB, VT, N1, N2.getOperand(0));
1161    if (N1.getOpcode() == ISD::FNEG)          // ((-A)+B) -> B-A
1162      return getNode(ISD::SUB, VT, N2, N1.getOperand(0));
1163    if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1164        cast<ConstantSDNode>(N1.getOperand(0))->getValue() == 0)
1165      return getNode(ISD::SUB, VT, N2, N1.getOperand(1)); // (0-A)+B -> B-A
1166    if (N2.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N2.getOperand(0)) &&
1167        cast<ConstantSDNode>(N2.getOperand(0))->getValue() == 0)
1168      return getNode(ISD::SUB, VT, N1, N2.getOperand(1)); // A+(0-B) -> A-B
1169    break;
1170  case ISD::SUB:
1171    if (N1.getOpcode() == ISD::ADD) {
1172      if (N1.Val->getOperand(0) == N2)
1173        return N1.Val->getOperand(1);         // (A+B)-A == B
1174      if (N1.Val->getOperand(1) == N2)
1175        return N1.Val->getOperand(0);         // (A+B)-B == A
1176    }
1177    if (N2.getOpcode() == ISD::FNEG)          // (A- (-B) -> A+B
1178      return getNode(ISD::ADD, VT, N1, N2.getOperand(0));
1179    break;
1180  // FIXME: figure out how to safely handle things like
1181  // int foo(int x) { return 1 << (x & 255); }
1182  // int bar() { return foo(256); }
1183#if 0
1184  case ISD::SHL:
1185  case ISD::SRL:
1186  case ISD::SRA:
1187    if (N2.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1188        cast<MVTSDNode>(N2)->getExtraValueType() != MVT::i1)
1189      return getNode(Opcode, VT, N1, N2.getOperand(0));
1190    else if (N2.getOpcode() == ISD::AND)
1191      if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N2.getOperand(1))) {
1192        // If the and is only masking out bits that cannot effect the shift,
1193        // eliminate the and.
1194        unsigned NumBits = MVT::getSizeInBits(VT);
1195        if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
1196          return getNode(Opcode, VT, N1, N2.getOperand(0));
1197      }
1198    break;
1199#endif
1200  }
1201
1202  // Memoize this node if possible.
1203  SDNode *N;
1204  if (Opcode != ISD::CALLSEQ_START && Opcode != ISD::CALLSEQ_END) {
1205    SDNode *&BON = BinaryOps[std::make_pair(Opcode, std::make_pair(N1, N2))];
1206    if (BON) return SDOperand(BON, 0);
1207
1208    BON = N = new SDNode(Opcode, N1, N2);
1209  } else {
1210    N = new SDNode(Opcode, N1, N2);
1211  }
1212
1213
1214  if (Opcode != ISD::READPORT && Opcode != ISD::READIO)
1215    N->setValueTypes(VT);
1216  else
1217    N->setValueTypes(VT, MVT::Other);
1218
1219  AllNodes.push_back(N);
1220  return SDOperand(N, 0);
1221}
1222
1223// setAdjCallChain - This method changes the token chain of an
1224// CALLSEQ_START/END node to be the specified operand.
1225void SDNode::setAdjCallChain(SDOperand N) {
1226  assert(N.getValueType() == MVT::Other);
1227  assert((getOpcode() == ISD::CALLSEQ_START ||
1228          getOpcode() == ISD::CALLSEQ_END) && "Cannot adjust this node!");
1229
1230  Operands[0].Val->removeUser(this);
1231  Operands[0] = N;
1232  N.Val->Uses.push_back(this);
1233}
1234
1235
1236
1237SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
1238                                SDOperand Chain, SDOperand Ptr,
1239                                SDOperand SV) {
1240  SDNode *&N = Loads[std::make_pair(Ptr, std::make_pair(Chain, VT))];
1241  if (N) return SDOperand(N, 0);
1242  N = new SDNode(ISD::LOAD, Chain, Ptr, SV);
1243
1244  // Loads have a token chain.
1245  N->setValueTypes(VT, MVT::Other);
1246  AllNodes.push_back(N);
1247  return SDOperand(N, 0);
1248}
1249
1250SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1251                                SDOperand N1, SDOperand N2, SDOperand N3) {
1252  assert(Opcode != ISD::STORE && "Store shouldn't use this anymore");
1253  // Perform various simplifications.
1254  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1255  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1256  ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
1257  switch (Opcode) {
1258  case ISD::SELECT:
1259    if (N1C)
1260      if (N1C->getValue())
1261        return N2;             // select true, X, Y -> X
1262      else
1263        return N3;             // select false, X, Y -> Y
1264
1265    if (N2 == N3) return N2;   // select C, X, X -> X
1266
1267    if (VT == MVT::i1) {  // Boolean SELECT
1268      if (N2C) {
1269        if (N2C->getValue())   // select C, 1, X -> C | X
1270          return getNode(ISD::OR, VT, N1, N3);
1271        else                   // select C, 0, X -> ~C & X
1272          return getNode(ISD::AND, VT,
1273                         getNode(ISD::XOR, N1.getValueType(), N1,
1274                                 getConstant(1, N1.getValueType())), N3);
1275      } else if (N3C) {
1276        if (N3C->getValue())   // select C, X, 1 -> ~C | X
1277          return getNode(ISD::OR, VT,
1278                         getNode(ISD::XOR, N1.getValueType(), N1,
1279                                 getConstant(1, N1.getValueType())), N2);
1280        else                   // select C, X, 0 -> C & X
1281          return getNode(ISD::AND, VT, N1, N2);
1282      }
1283
1284      if (N1 == N2)   // X ? X : Y --> X ? 1 : Y --> X | Y
1285        return getNode(ISD::OR, VT, N1, N3);
1286      if (N1 == N3)   // X ? Y : X --> X ? Y : 0 --> X & Y
1287        return getNode(ISD::AND, VT, N1, N2);
1288    }
1289
1290    // If this is a selectcc, check to see if we can simplify the result.
1291    if (SetCCSDNode *SetCC = dyn_cast<SetCCSDNode>(N1)) {
1292      if (ConstantFPSDNode *CFP =
1293          dyn_cast<ConstantFPSDNode>(SetCC->getOperand(1)))
1294        if (CFP->getValue() == 0.0) {   // Allow either -0.0 or 0.0
1295          // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
1296          if ((SetCC->getCondition() == ISD::SETGE ||
1297               SetCC->getCondition() == ISD::SETGT) &&
1298              N2 == SetCC->getOperand(0) && N3.getOpcode() == ISD::FNEG &&
1299              N3.getOperand(0) == N2)
1300            return getNode(ISD::FABS, VT, N2);
1301
1302          // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
1303          if ((SetCC->getCondition() == ISD::SETLT ||
1304               SetCC->getCondition() == ISD::SETLE) &&
1305              N3 == SetCC->getOperand(0) && N2.getOpcode() == ISD::FNEG &&
1306              N2.getOperand(0) == N3)
1307            return getNode(ISD::FABS, VT, N3);
1308        }
1309      // select (setlt X, 0), A, 0 -> and (sra X, size(X)-1), A
1310      if (ConstantSDNode *CN =
1311          dyn_cast<ConstantSDNode>(SetCC->getOperand(1)))
1312        if (CN->getValue() == 0 && N3C && N3C->getValue() == 0)
1313          if (SetCC->getCondition() == ISD::SETLT) {
1314            MVT::ValueType XType = SetCC->getOperand(0).getValueType();
1315            MVT::ValueType AType = N2.getValueType();
1316            if (XType >= AType) {
1317              // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
1318              // single-bit constant.  FIXME: remove once the dag combiner
1319              // exists.
1320              if (ConstantSDNode *AC = dyn_cast<ConstantSDNode>(N2))
1321                if ((AC->getValue() & (AC->getValue()-1)) == 0) {
1322                  unsigned ShCtV = ExactLog2(AC->getValue());
1323                  ShCtV = MVT::getSizeInBits(XType)-ShCtV-1;
1324                  SDOperand ShCt = getConstant(ShCtV, TLI.getShiftAmountTy());
1325                  SDOperand Shift = getNode(ISD::SRL, XType,
1326                                            SetCC->getOperand(0), ShCt);
1327                  if (XType > AType)
1328                    Shift = getNode(ISD::TRUNCATE, AType, Shift);
1329                  return getNode(ISD::AND, AType, Shift, N2);
1330                }
1331
1332
1333              SDOperand Shift = getNode(ISD::SRA, XType, SetCC->getOperand(0),
1334                getConstant(MVT::getSizeInBits(XType)-1,
1335                            TLI.getShiftAmountTy()));
1336              if (XType > AType)
1337                Shift = getNode(ISD::TRUNCATE, AType, Shift);
1338              return getNode(ISD::AND, AType, Shift, N2);
1339            }
1340          }
1341    }
1342    break;
1343  case ISD::BRCOND:
1344    if (N2C)
1345      if (N2C->getValue()) // Unconditional branch
1346        return getNode(ISD::BR, MVT::Other, N1, N3);
1347      else
1348        return N1;         // Never-taken branch
1349    break;
1350  // FIXME: figure out how to safely handle things like
1351  // int foo(int x) { return 1 << (x & 255); }
1352  // int bar() { return foo(256); }
1353#if 0
1354  case ISD::SRA_PARTS:
1355  case ISD::SRL_PARTS:
1356  case ISD::SHL_PARTS:
1357    if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1358        cast<MVTSDNode>(N3)->getExtraValueType() != MVT::i1)
1359      return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
1360    else if (N3.getOpcode() == ISD::AND)
1361      if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
1362        // If the and is only masking out bits that cannot effect the shift,
1363        // eliminate the and.
1364        unsigned NumBits = MVT::getSizeInBits(VT)*2;
1365        if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
1366          return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
1367      }
1368    break;
1369#endif
1370  }
1371
1372  SDNode *N = new SDNode(Opcode, N1, N2, N3);
1373  switch (Opcode) {
1374  default:
1375    N->setValueTypes(VT);
1376    break;
1377  case ISD::DYNAMIC_STACKALLOC: // DYNAMIC_STACKALLOC produces pointer and chain
1378    N->setValueTypes(VT, MVT::Other);
1379    break;
1380
1381  case ISD::SRA_PARTS:
1382  case ISD::SRL_PARTS:
1383  case ISD::SHL_PARTS: {
1384    std::vector<MVT::ValueType> V(N->getNumOperands()-1, VT);
1385    N->setValueTypes(V);
1386    break;
1387  }
1388  }
1389
1390  // FIXME: memoize NODES
1391  AllNodes.push_back(N);
1392  return SDOperand(N, 0);
1393}
1394
1395SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1396                                SDOperand N1, SDOperand N2, SDOperand N3,
1397                                SDOperand N4) {
1398  assert(Opcode == ISD::STORE && "Only stores should use this");
1399
1400  SDNode *N = new SDNode(Opcode, N1, N2, N3, N4);
1401  N->setValueTypes(VT);
1402
1403  // FIXME: memoize NODES
1404  AllNodes.push_back(N);
1405  return SDOperand(N, 0);
1406}
1407
1408SDOperand SelectionDAG::getSrcValue(const Value *V, int Offset) {
1409  assert((!V || isa<PointerType>(V->getType())) &&
1410         "SrcValue is not a pointer?");
1411  SDNode *&N = ValueNodes[std::make_pair(V, Offset)];
1412  if (N) return SDOperand(N, 0);
1413
1414  N = new SrcValueSDNode(V, Offset);
1415  AllNodes.push_back(N);
1416  return SDOperand(N, 0);
1417}
1418
1419SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1420                                std::vector<SDOperand> &Ops) {
1421  switch (Ops.size()) {
1422  case 0: return getNode(Opcode, VT);
1423  case 1: return getNode(Opcode, VT, Ops[0]);
1424  case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
1425  case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
1426  default: break;
1427  }
1428
1429  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Ops[1].Val);
1430  switch (Opcode) {
1431  default: break;
1432  case ISD::BRCONDTWOWAY:
1433    if (N1C)
1434      if (N1C->getValue()) // Unconditional branch to true dest.
1435        return getNode(ISD::BR, MVT::Other, Ops[0], Ops[2]);
1436      else                 // Unconditional branch to false dest.
1437        return getNode(ISD::BR, MVT::Other, Ops[0], Ops[3]);
1438    break;
1439  }
1440
1441  // FIXME: MEMOIZE!!
1442  SDNode *N = new SDNode(Opcode, Ops);
1443  if (Opcode != ISD::ADD_PARTS && Opcode != ISD::SUB_PARTS) {
1444    N->setValueTypes(VT);
1445  } else {
1446    std::vector<MVT::ValueType> V(N->getNumOperands()/2, VT);
1447    N->setValueTypes(V);
1448  }
1449  AllNodes.push_back(N);
1450  return SDOperand(N, 0);
1451}
1452
1453SDOperand SelectionDAG::getNode(unsigned Opcode,
1454                                std::vector<MVT::ValueType> &ResultTys,
1455                                std::vector<SDOperand> &Ops) {
1456  if (ResultTys.size() == 1)
1457    return getNode(Opcode, ResultTys[0], Ops);
1458
1459
1460  // Memoize the node.
1461  SDNode *&N = ArbitraryNodes[std::make_pair(Opcode, std::make_pair(ResultTys,
1462                                                                    Ops))];
1463  if (N) return SDOperand(N, 0);
1464  N = new SDNode(Opcode, Ops);
1465  N->setValueTypes(ResultTys);
1466  AllNodes.push_back(N);
1467  return SDOperand(N, 0);
1468}
1469
1470
1471SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,SDOperand N1,
1472                                MVT::ValueType EVT) {
1473
1474  switch (Opcode) {
1475  default: assert(0 && "Bad opcode for this accessor!");
1476  case ISD::FP_ROUND_INREG:
1477    assert(VT == N1.getValueType() && "Not an inreg round!");
1478    assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
1479           "Cannot FP_ROUND_INREG integer types");
1480    if (EVT == VT) return N1;  // Not actually rounding
1481    assert(EVT < VT && "Not rounding down!");
1482
1483    if (isa<ConstantFPSDNode>(N1))
1484      return getNode(ISD::FP_EXTEND, VT, getNode(ISD::FP_ROUND, EVT, N1));
1485    break;
1486  case ISD::SIGN_EXTEND_INREG:
1487    assert(VT == N1.getValueType() && "Not an inreg extend!");
1488    assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
1489           "Cannot *_EXTEND_INREG FP types");
1490    if (EVT == VT) return N1;  // Not actually extending
1491    assert(EVT < VT && "Not extending!");
1492
1493    // Extending a constant?  Just return the extended constant.
1494    if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1495      SDOperand Tmp = getNode(ISD::TRUNCATE, EVT, N1);
1496      return getNode(ISD::SIGN_EXTEND, VT, Tmp);
1497    }
1498
1499    // If we are sign extending an extension, use the original source.
1500    if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG)
1501      if (cast<MVTSDNode>(N1)->getExtraValueType() <= EVT)
1502        return N1;
1503
1504    // If we are sign extending a sextload, return just the load.
1505    if (N1.getOpcode() == ISD::SEXTLOAD && Opcode == ISD::SIGN_EXTEND_INREG)
1506      if (cast<MVTSDNode>(N1)->getExtraValueType() <= EVT)
1507        return N1;
1508
1509    // If we are extending the result of a setcc, and we already know the
1510    // contents of the top bits, eliminate the extension.
1511    if (N1.getOpcode() == ISD::SETCC &&
1512        TLI.getSetCCResultContents() ==
1513                        TargetLowering::ZeroOrNegativeOneSetCCResult)
1514      return N1;
1515
1516    // If we are sign extending the result of an (and X, C) operation, and we
1517    // know the extended bits are zeros already, don't do the extend.
1518    if (N1.getOpcode() == ISD::AND)
1519      if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
1520        uint64_t Mask = N1C->getValue();
1521        unsigned NumBits = MVT::getSizeInBits(EVT);
1522        if ((Mask & (~0ULL << (NumBits-1))) == 0)
1523          return N1;
1524      }
1525    break;
1526  }
1527
1528  EVTStruct NN;
1529  NN.Opcode = Opcode;
1530  NN.VT = VT;
1531  NN.EVT = EVT;
1532  NN.Ops.push_back(N1);
1533
1534  SDNode *&N = MVTSDNodes[NN];
1535  if (N) return SDOperand(N, 0);
1536  N = new MVTSDNode(Opcode, VT, N1, EVT);
1537  AllNodes.push_back(N);
1538  return SDOperand(N, 0);
1539}
1540
1541SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,SDOperand N1,
1542                                SDOperand N2, SDOperand N3, MVT::ValueType EVT) {
1543  switch (Opcode) {
1544  default:  assert(0 && "Bad opcode for this accessor!");
1545  case ISD::EXTLOAD:
1546  case ISD::SEXTLOAD:
1547  case ISD::ZEXTLOAD:
1548    // If they are asking for an extending load from/to the same thing, return a
1549    // normal load.
1550    if (VT == EVT)
1551      return getLoad(VT, N1, N2, N3);
1552    assert(EVT < VT && "Should only be an extending load, not truncating!");
1553    assert((Opcode == ISD::EXTLOAD || MVT::isInteger(VT)) &&
1554           "Cannot sign/zero extend a FP load!");
1555    assert(MVT::isInteger(VT) == MVT::isInteger(EVT) &&
1556           "Cannot convert from FP to Int or Int -> FP!");
1557    break;
1558  }
1559
1560  EVTStruct NN;
1561  NN.Opcode = Opcode;
1562  NN.VT = VT;
1563  NN.EVT = EVT;
1564  NN.Ops.push_back(N1);
1565  NN.Ops.push_back(N2);
1566  NN.Ops.push_back(N3);
1567
1568  SDNode *&N = MVTSDNodes[NN];
1569  if (N) return SDOperand(N, 0);
1570  N = new MVTSDNode(Opcode, VT, MVT::Other, N1, N2, N3, EVT);
1571  AllNodes.push_back(N);
1572  return SDOperand(N, 0);
1573}
1574
1575SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,SDOperand N1,
1576                                SDOperand N2, SDOperand N3, SDOperand N4,
1577                                MVT::ValueType EVT) {
1578  switch (Opcode) {
1579  default:  assert(0 && "Bad opcode for this accessor!");
1580  case ISD::TRUNCSTORE:
1581#if 0 // FIXME: If the target supports EVT natively, convert to a truncate/store
1582    // If this is a truncating store of a constant, convert to the desired type
1583    // and store it instead.
1584    if (isa<Constant>(N1)) {
1585      SDOperand Op = getNode(ISD::TRUNCATE, EVT, N1);
1586      if (isa<Constant>(Op))
1587        N1 = Op;
1588    }
1589    // Also for ConstantFP?
1590#endif
1591    if (N1.getValueType() == EVT)       // Normal store?
1592      return getNode(ISD::STORE, VT, N1, N2, N3, N4);
1593    assert(N2.getValueType() > EVT && "Not a truncation?");
1594    assert(MVT::isInteger(N2.getValueType()) == MVT::isInteger(EVT) &&
1595           "Can't do FP-INT conversion!");
1596    break;
1597  }
1598
1599  EVTStruct NN;
1600  NN.Opcode = Opcode;
1601  NN.VT = VT;
1602  NN.EVT = EVT;
1603  NN.Ops.push_back(N1);
1604  NN.Ops.push_back(N2);
1605  NN.Ops.push_back(N3);
1606  NN.Ops.push_back(N4);
1607
1608  SDNode *&N = MVTSDNodes[NN];
1609  if (N) return SDOperand(N, 0);
1610  N = new MVTSDNode(Opcode, VT, N1, N2, N3, N4, EVT);
1611  AllNodes.push_back(N);
1612  return SDOperand(N, 0);
1613}
1614
1615
1616/// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
1617/// indicated value.  This method ignores uses of other values defined by this
1618/// operation.
1619bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) {
1620  assert(Value < getNumValues() && "Bad value!");
1621
1622  // If there is only one value, this is easy.
1623  if (getNumValues() == 1)
1624    return use_size() == NUses;
1625  if (Uses.size() < NUses) return false;
1626
1627  SDOperand TheValue(this, Value);
1628
1629  std::set<SDNode*> UsersHandled;
1630
1631  for (std::vector<SDNode*>::iterator UI = Uses.begin(), E = Uses.end();
1632       UI != E; ++UI) {
1633    SDNode *User = *UI;
1634    if (User->getNumOperands() == 1 ||
1635        UsersHandled.insert(User).second)     // First time we've seen this?
1636      for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
1637        if (User->getOperand(i) == TheValue) {
1638          if (NUses == 0)
1639            return false;   // too many uses
1640          --NUses;
1641        }
1642  }
1643
1644  // Found exactly the right number of uses?
1645  return NUses == 0;
1646}
1647
1648
1649const char *SDNode::getOperationName() const {
1650  switch (getOpcode()) {
1651  default: return "<<Unknown>>";
1652  case ISD::PCMARKER:      return "PCMarker";
1653  case ISD::SRCVALUE:      return "SrcValue";
1654  case ISD::EntryToken:    return "EntryToken";
1655  case ISD::TokenFactor:   return "TokenFactor";
1656  case ISD::Constant:      return "Constant";
1657  case ISD::ConstantFP:    return "ConstantFP";
1658  case ISD::GlobalAddress: return "GlobalAddress";
1659  case ISD::FrameIndex:    return "FrameIndex";
1660  case ISD::BasicBlock:    return "BasicBlock";
1661  case ISD::ExternalSymbol: return "ExternalSymbol";
1662  case ISD::ConstantPool:  return "ConstantPoolIndex";
1663  case ISD::CopyToReg:     return "CopyToReg";
1664  case ISD::CopyFromReg:   return "CopyFromReg";
1665  case ISD::ImplicitDef:   return "ImplicitDef";
1666  case ISD::UNDEF:         return "undef";
1667
1668  // Unary operators
1669  case ISD::FABS:   return "fabs";
1670  case ISD::FNEG:   return "fneg";
1671  case ISD::FSQRT:  return "fsqrt";
1672  case ISD::FSIN:   return "fsin";
1673  case ISD::FCOS:   return "fcos";
1674
1675  // Binary operators
1676  case ISD::ADD:    return "add";
1677  case ISD::SUB:    return "sub";
1678  case ISD::MUL:    return "mul";
1679  case ISD::MULHU:  return "mulhu";
1680  case ISD::MULHS:  return "mulhs";
1681  case ISD::SDIV:   return "sdiv";
1682  case ISD::UDIV:   return "udiv";
1683  case ISD::SREM:   return "srem";
1684  case ISD::UREM:   return "urem";
1685  case ISD::AND:    return "and";
1686  case ISD::OR:     return "or";
1687  case ISD::XOR:    return "xor";
1688  case ISD::SHL:    return "shl";
1689  case ISD::SRA:    return "sra";
1690  case ISD::SRL:    return "srl";
1691
1692  case ISD::SELECT: return "select";
1693  case ISD::ADD_PARTS:   return "add_parts";
1694  case ISD::SUB_PARTS:   return "sub_parts";
1695  case ISD::SHL_PARTS:   return "shl_parts";
1696  case ISD::SRA_PARTS:   return "sra_parts";
1697  case ISD::SRL_PARTS:   return "srl_parts";
1698
1699  // Conversion operators.
1700  case ISD::SIGN_EXTEND: return "sign_extend";
1701  case ISD::ZERO_EXTEND: return "zero_extend";
1702  case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
1703  case ISD::TRUNCATE:    return "truncate";
1704  case ISD::FP_ROUND:    return "fp_round";
1705  case ISD::FP_ROUND_INREG: return "fp_round_inreg";
1706  case ISD::FP_EXTEND:   return "fp_extend";
1707
1708  case ISD::SINT_TO_FP:  return "sint_to_fp";
1709  case ISD::UINT_TO_FP:  return "uint_to_fp";
1710  case ISD::FP_TO_SINT:  return "fp_to_sint";
1711  case ISD::FP_TO_UINT:  return "fp_to_uint";
1712
1713    // Control flow instructions
1714  case ISD::BR:      return "br";
1715  case ISD::BRCOND:  return "brcond";
1716  case ISD::BRCONDTWOWAY:  return "brcondtwoway";
1717  case ISD::RET:     return "ret";
1718  case ISD::CALL:    return "call";
1719  case ISD::TAILCALL:return "tailcall";
1720  case ISD::CALLSEQ_START:  return "callseq_start";
1721  case ISD::CALLSEQ_END:    return "callseq_end";
1722
1723    // Other operators
1724  case ISD::LOAD:    return "load";
1725  case ISD::STORE:   return "store";
1726  case ISD::EXTLOAD:    return "extload";
1727  case ISD::SEXTLOAD:   return "sextload";
1728  case ISD::ZEXTLOAD:   return "zextload";
1729  case ISD::TRUNCSTORE: return "truncstore";
1730
1731  case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
1732  case ISD::EXTRACT_ELEMENT: return "extract_element";
1733  case ISD::BUILD_PAIR: return "build_pair";
1734  case ISD::MEMSET:  return "memset";
1735  case ISD::MEMCPY:  return "memcpy";
1736  case ISD::MEMMOVE: return "memmove";
1737
1738  // Bit counting
1739  case ISD::CTPOP:   return "ctpop";
1740  case ISD::CTTZ:    return "cttz";
1741  case ISD::CTLZ:    return "ctlz";
1742
1743  // IO Intrinsics
1744  case ISD::READPORT: return "readport";
1745  case ISD::WRITEPORT: return "writeport";
1746  case ISD::READIO: return "readio";
1747  case ISD::WRITEIO: return "writeio";
1748
1749  case ISD::SETCC:
1750    const SetCCSDNode *SetCC = cast<SetCCSDNode>(this);
1751    switch (SetCC->getCondition()) {
1752    default: assert(0 && "Unknown setcc condition!");
1753    case ISD::SETOEQ:  return "setcc:setoeq";
1754    case ISD::SETOGT:  return "setcc:setogt";
1755    case ISD::SETOGE:  return "setcc:setoge";
1756    case ISD::SETOLT:  return "setcc:setolt";
1757    case ISD::SETOLE:  return "setcc:setole";
1758    case ISD::SETONE:  return "setcc:setone";
1759
1760    case ISD::SETO:    return "setcc:seto";
1761    case ISD::SETUO:   return "setcc:setuo";
1762    case ISD::SETUEQ:  return "setcc:setue";
1763    case ISD::SETUGT:  return "setcc:setugt";
1764    case ISD::SETUGE:  return "setcc:setuge";
1765    case ISD::SETULT:  return "setcc:setult";
1766    case ISD::SETULE:  return "setcc:setule";
1767    case ISD::SETUNE:  return "setcc:setune";
1768
1769    case ISD::SETEQ:   return "setcc:seteq";
1770    case ISD::SETGT:   return "setcc:setgt";
1771    case ISD::SETGE:   return "setcc:setge";
1772    case ISD::SETLT:   return "setcc:setlt";
1773    case ISD::SETLE:   return "setcc:setle";
1774    case ISD::SETNE:   return "setcc:setne";
1775    }
1776  }
1777}
1778
1779void SDNode::dump() const {
1780  std::cerr << (void*)this << ": ";
1781
1782  for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
1783    if (i) std::cerr << ",";
1784    if (getValueType(i) == MVT::Other)
1785      std::cerr << "ch";
1786    else
1787      std::cerr << MVT::getValueTypeString(getValueType(i));
1788  }
1789  std::cerr << " = " << getOperationName();
1790
1791  std::cerr << " ";
1792  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1793    if (i) std::cerr << ", ";
1794    std::cerr << (void*)getOperand(i).Val;
1795    if (unsigned RN = getOperand(i).ResNo)
1796      std::cerr << ":" << RN;
1797  }
1798
1799  if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
1800    std::cerr << "<" << CSDN->getValue() << ">";
1801  } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
1802    std::cerr << "<" << CSDN->getValue() << ">";
1803  } else if (const GlobalAddressSDNode *GADN =
1804             dyn_cast<GlobalAddressSDNode>(this)) {
1805    std::cerr << "<";
1806    WriteAsOperand(std::cerr, GADN->getGlobal()) << ">";
1807  } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
1808    std::cerr << "<" << FIDN->getIndex() << ">";
1809  } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
1810    std::cerr << "<" << CP->getIndex() << ">";
1811  } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
1812    std::cerr << "<";
1813    const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
1814    if (LBB)
1815      std::cerr << LBB->getName() << " ";
1816    std::cerr << (const void*)BBDN->getBasicBlock() << ">";
1817  } else if (const RegSDNode *C2V = dyn_cast<RegSDNode>(this)) {
1818    std::cerr << "<reg #" << C2V->getReg() << ">";
1819  } else if (const ExternalSymbolSDNode *ES =
1820             dyn_cast<ExternalSymbolSDNode>(this)) {
1821    std::cerr << "'" << ES->getSymbol() << "'";
1822  } else if (const MVTSDNode *M = dyn_cast<MVTSDNode>(this)) {
1823    std::cerr << " - Ty = " << MVT::getValueTypeString(M->getExtraValueType());
1824  } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
1825    if (M->getValue())
1826      std::cerr << "<" << M->getValue() << ":" << M->getOffset() << ">";
1827    else
1828      std::cerr << "<null:" << M->getOffset() << ">";
1829  }
1830}
1831
1832static void DumpNodes(SDNode *N, unsigned indent) {
1833  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1834    if (N->getOperand(i).Val->hasOneUse())
1835      DumpNodes(N->getOperand(i).Val, indent+2);
1836    else
1837      std::cerr << "\n" << std::string(indent+2, ' ')
1838                << (void*)N->getOperand(i).Val << ": <multiple use>";
1839
1840
1841  std::cerr << "\n" << std::string(indent, ' ');
1842  N->dump();
1843}
1844
1845void SelectionDAG::dump() const {
1846  std::cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
1847  std::vector<SDNode*> Nodes(AllNodes);
1848  std::sort(Nodes.begin(), Nodes.end());
1849
1850  for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1851    if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
1852      DumpNodes(Nodes[i], 2);
1853  }
1854
1855  DumpNodes(getRoot().Val, 2);
1856
1857  std::cerr << "\n\n";
1858}
1859
1860