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