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