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