SelectionDAG.cpp revision eaf089430e7681fcddc3465c3b33b9645273ab02
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/GlobalVariable.h"
17#include "llvm/Intrinsics.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Assembly/Writer.h"
20#include "llvm/CodeGen/MachineBasicBlock.h"
21#include "llvm/CodeGen/MachineConstantPool.h"
22#include "llvm/Support/MathExtras.h"
23#include "llvm/Target/MRegisterInfo.h"
24#include "llvm/Target/TargetData.h"
25#include "llvm/Target/TargetLowering.h"
26#include "llvm/Target/TargetInstrInfo.h"
27#include "llvm/Target/TargetMachine.h"
28#include "llvm/ADT/SetVector.h"
29#include "llvm/ADT/SmallPtrSet.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringExtras.h"
32#include <algorithm>
33#include <cmath>
34using namespace llvm;
35
36/// makeVTList - Return an instance of the SDVTList struct initialized with the
37/// specified members.
38static SDVTList makeVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
39  SDVTList Res = {VTs, NumVTs};
40  return Res;
41}
42
43//===----------------------------------------------------------------------===//
44//                              ConstantFPSDNode Class
45//===----------------------------------------------------------------------===//
46
47/// isExactlyValue - We don't rely on operator== working on double values, as
48/// it returns true for things that are clearly not equal, like -0.0 and 0.0.
49/// As such, this method can be used to do an exact bit-for-bit comparison of
50/// two floating point values.
51bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
52  return Value.bitwiseIsEqual(V);
53}
54
55bool ConstantFPSDNode::isValueValidForType(MVT::ValueType VT,
56                                           const APFloat& Val) {
57  // convert modifies in place, so make a copy.
58  APFloat Val2 = APFloat(Val);
59  switch (VT) {
60  default:
61    return false;         // These can't be represented as floating point!
62
63  // FIXME rounding mode needs to be more flexible
64  case MVT::f32:
65    return &Val2.getSemantics() == &APFloat::IEEEsingle ||
66           Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) ==
67              APFloat::opOK;
68  case MVT::f64:
69    return &Val2.getSemantics() == &APFloat::IEEEsingle ||
70           &Val2.getSemantics() == &APFloat::IEEEdouble ||
71           Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) ==
72             APFloat::opOK;
73  // TODO: Figure out how to test if we can use a shorter type instead!
74  case MVT::f80:
75  case MVT::f128:
76  case MVT::ppcf128:
77    return true;
78  }
79}
80
81//===----------------------------------------------------------------------===//
82//                              ISD Namespace
83//===----------------------------------------------------------------------===//
84
85/// isBuildVectorAllOnes - Return true if the specified node is a
86/// BUILD_VECTOR where all of the elements are ~0 or undef.
87bool ISD::isBuildVectorAllOnes(const SDNode *N) {
88  // Look through a bit convert.
89  if (N->getOpcode() == ISD::BIT_CONVERT)
90    N = N->getOperand(0).Val;
91
92  if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
93
94  unsigned i = 0, e = N->getNumOperands();
95
96  // Skip over all of the undef values.
97  while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
98    ++i;
99
100  // Do not accept an all-undef vector.
101  if (i == e) return false;
102
103  // Do not accept build_vectors that aren't all constants or which have non-~0
104  // elements.
105  SDOperand NotZero = N->getOperand(i);
106  if (isa<ConstantSDNode>(NotZero)) {
107    if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
108      return false;
109  } else if (isa<ConstantFPSDNode>(NotZero)) {
110    MVT::ValueType VT = NotZero.getValueType();
111    if (VT== MVT::f64) {
112      if (DoubleToBits(cast<ConstantFPSDNode>(NotZero)->
113                       getValueAPF().convertToDouble()) !=
114          (uint64_t)-1)
115        return false;
116    } else {
117      if (FloatToBits(cast<ConstantFPSDNode>(NotZero)->
118                      getValueAPF().convertToFloat()) !=
119          (uint32_t)-1)
120        return false;
121    }
122  } else
123    return false;
124
125  // Okay, we have at least one ~0 value, check to see if the rest match or are
126  // undefs.
127  for (++i; i != e; ++i)
128    if (N->getOperand(i) != NotZero &&
129        N->getOperand(i).getOpcode() != ISD::UNDEF)
130      return false;
131  return true;
132}
133
134
135/// isBuildVectorAllZeros - Return true if the specified node is a
136/// BUILD_VECTOR where all of the elements are 0 or undef.
137bool ISD::isBuildVectorAllZeros(const SDNode *N) {
138  // Look through a bit convert.
139  if (N->getOpcode() == ISD::BIT_CONVERT)
140    N = N->getOperand(0).Val;
141
142  if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
143
144  unsigned i = 0, e = N->getNumOperands();
145
146  // Skip over all of the undef values.
147  while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
148    ++i;
149
150  // Do not accept an all-undef vector.
151  if (i == e) return false;
152
153  // Do not accept build_vectors that aren't all constants or which have non-~0
154  // elements.
155  SDOperand Zero = N->getOperand(i);
156  if (isa<ConstantSDNode>(Zero)) {
157    if (!cast<ConstantSDNode>(Zero)->isNullValue())
158      return false;
159  } else if (isa<ConstantFPSDNode>(Zero)) {
160    if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
161      return false;
162  } else
163    return false;
164
165  // Okay, we have at least one ~0 value, check to see if the rest match or are
166  // undefs.
167  for (++i; i != e; ++i)
168    if (N->getOperand(i) != Zero &&
169        N->getOperand(i).getOpcode() != ISD::UNDEF)
170      return false;
171  return true;
172}
173
174/// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
175/// when given the operation for (X op Y).
176ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
177  // To perform this operation, we just need to swap the L and G bits of the
178  // operation.
179  unsigned OldL = (Operation >> 2) & 1;
180  unsigned OldG = (Operation >> 1) & 1;
181  return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
182                       (OldL << 1) |       // New G bit
183                       (OldG << 2));        // New L bit.
184}
185
186/// getSetCCInverse - Return the operation corresponding to !(X op Y), where
187/// 'op' is a valid SetCC operation.
188ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
189  unsigned Operation = Op;
190  if (isInteger)
191    Operation ^= 7;   // Flip L, G, E bits, but not U.
192  else
193    Operation ^= 15;  // Flip all of the condition bits.
194  if (Operation > ISD::SETTRUE2)
195    Operation &= ~8;     // Don't let N and U bits get set.
196  return ISD::CondCode(Operation);
197}
198
199
200/// isSignedOp - For an integer comparison, return 1 if the comparison is a
201/// signed operation and 2 if the result is an unsigned comparison.  Return zero
202/// if the operation does not depend on the sign of the input (setne and seteq).
203static int isSignedOp(ISD::CondCode Opcode) {
204  switch (Opcode) {
205  default: assert(0 && "Illegal integer setcc operation!");
206  case ISD::SETEQ:
207  case ISD::SETNE: return 0;
208  case ISD::SETLT:
209  case ISD::SETLE:
210  case ISD::SETGT:
211  case ISD::SETGE: return 1;
212  case ISD::SETULT:
213  case ISD::SETULE:
214  case ISD::SETUGT:
215  case ISD::SETUGE: return 2;
216  }
217}
218
219/// getSetCCOrOperation - Return the result of a logical OR between different
220/// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This function
221/// returns SETCC_INVALID if it is not possible to represent the resultant
222/// comparison.
223ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
224                                       bool isInteger) {
225  if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
226    // Cannot fold a signed integer setcc with an unsigned integer setcc.
227    return ISD::SETCC_INVALID;
228
229  unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
230
231  // If the N and U bits get set then the resultant comparison DOES suddenly
232  // care about orderedness, and is true when ordered.
233  if (Op > ISD::SETTRUE2)
234    Op &= ~16;     // Clear the U bit if the N bit is set.
235
236  // Canonicalize illegal integer setcc's.
237  if (isInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
238    Op = ISD::SETNE;
239
240  return ISD::CondCode(Op);
241}
242
243/// getSetCCAndOperation - Return the result of a logical AND between different
244/// comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
245/// function returns zero if it is not possible to represent the resultant
246/// comparison.
247ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
248                                        bool isInteger) {
249  if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
250    // Cannot fold a signed setcc with an unsigned setcc.
251    return ISD::SETCC_INVALID;
252
253  // Combine all of the condition bits.
254  ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
255
256  // Canonicalize illegal integer setcc's.
257  if (isInteger) {
258    switch (Result) {
259    default: break;
260    case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
261    case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
262    case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
263    case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
264    }
265  }
266
267  return Result;
268}
269
270const TargetMachine &SelectionDAG::getTarget() const {
271  return TLI.getTargetMachine();
272}
273
274//===----------------------------------------------------------------------===//
275//                           SDNode Profile Support
276//===----------------------------------------------------------------------===//
277
278/// AddNodeIDOpcode - Add the node opcode to the NodeID data.
279///
280static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
281  ID.AddInteger(OpC);
282}
283
284/// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
285/// solely with their pointer.
286void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
287  ID.AddPointer(VTList.VTs);
288}
289
290/// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
291///
292static void AddNodeIDOperands(FoldingSetNodeID &ID,
293                              const SDOperand *Ops, unsigned NumOps) {
294  for (; NumOps; --NumOps, ++Ops) {
295    ID.AddPointer(Ops->Val);
296    ID.AddInteger(Ops->ResNo);
297  }
298}
299
300static void AddNodeIDNode(FoldingSetNodeID &ID,
301                          unsigned short OpC, SDVTList VTList,
302                          const SDOperand *OpList, unsigned N) {
303  AddNodeIDOpcode(ID, OpC);
304  AddNodeIDValueTypes(ID, VTList);
305  AddNodeIDOperands(ID, OpList, N);
306}
307
308/// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
309/// data.
310static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
311  AddNodeIDOpcode(ID, N->getOpcode());
312  // Add the return value info.
313  AddNodeIDValueTypes(ID, N->getVTList());
314  // Add the operand info.
315  AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
316
317  // Handle SDNode leafs with special info.
318  switch (N->getOpcode()) {
319  default: break;  // Normal nodes don't need extra info.
320  case ISD::TargetConstant:
321  case ISD::Constant:
322    ID.AddInteger(cast<ConstantSDNode>(N)->getValue());
323    break;
324  case ISD::TargetConstantFP:
325  case ISD::ConstantFP: {
326    APFloat V = cast<ConstantFPSDNode>(N)->getValueAPF();
327    if (&V.getSemantics() == &APFloat::IEEEdouble)
328      ID.AddDouble(V.convertToDouble());
329    else if (&V.getSemantics() == &APFloat::IEEEsingle)
330      ID.AddDouble((double)V.convertToFloat());
331    else
332      assert(0);
333    break;
334  }
335  case ISD::TargetGlobalAddress:
336  case ISD::GlobalAddress:
337  case ISD::TargetGlobalTLSAddress:
338  case ISD::GlobalTLSAddress: {
339    GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
340    ID.AddPointer(GA->getGlobal());
341    ID.AddInteger(GA->getOffset());
342    break;
343  }
344  case ISD::BasicBlock:
345    ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
346    break;
347  case ISD::Register:
348    ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
349    break;
350  case ISD::SRCVALUE: {
351    SrcValueSDNode *SV = cast<SrcValueSDNode>(N);
352    ID.AddPointer(SV->getValue());
353    ID.AddInteger(SV->getOffset());
354    break;
355  }
356  case ISD::FrameIndex:
357  case ISD::TargetFrameIndex:
358    ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
359    break;
360  case ISD::JumpTable:
361  case ISD::TargetJumpTable:
362    ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
363    break;
364  case ISD::ConstantPool:
365  case ISD::TargetConstantPool: {
366    ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
367    ID.AddInteger(CP->getAlignment());
368    ID.AddInteger(CP->getOffset());
369    if (CP->isMachineConstantPoolEntry())
370      CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
371    else
372      ID.AddPointer(CP->getConstVal());
373    break;
374  }
375  case ISD::LOAD: {
376    LoadSDNode *LD = cast<LoadSDNode>(N);
377    ID.AddInteger(LD->getAddressingMode());
378    ID.AddInteger(LD->getExtensionType());
379    ID.AddInteger(LD->getLoadedVT());
380    ID.AddPointer(LD->getSrcValue());
381    ID.AddInteger(LD->getSrcValueOffset());
382    ID.AddInteger(LD->getAlignment());
383    ID.AddInteger(LD->isVolatile());
384    break;
385  }
386  case ISD::STORE: {
387    StoreSDNode *ST = cast<StoreSDNode>(N);
388    ID.AddInteger(ST->getAddressingMode());
389    ID.AddInteger(ST->isTruncatingStore());
390    ID.AddInteger(ST->getStoredVT());
391    ID.AddPointer(ST->getSrcValue());
392    ID.AddInteger(ST->getSrcValueOffset());
393    ID.AddInteger(ST->getAlignment());
394    ID.AddInteger(ST->isVolatile());
395    break;
396  }
397  }
398}
399
400//===----------------------------------------------------------------------===//
401//                              SelectionDAG Class
402//===----------------------------------------------------------------------===//
403
404/// RemoveDeadNodes - This method deletes all unreachable nodes in the
405/// SelectionDAG.
406void SelectionDAG::RemoveDeadNodes() {
407  // Create a dummy node (which is not added to allnodes), that adds a reference
408  // to the root node, preventing it from being deleted.
409  HandleSDNode Dummy(getRoot());
410
411  SmallVector<SDNode*, 128> DeadNodes;
412
413  // Add all obviously-dead nodes to the DeadNodes worklist.
414  for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
415    if (I->use_empty())
416      DeadNodes.push_back(I);
417
418  // Process the worklist, deleting the nodes and adding their uses to the
419  // worklist.
420  while (!DeadNodes.empty()) {
421    SDNode *N = DeadNodes.back();
422    DeadNodes.pop_back();
423
424    // Take the node out of the appropriate CSE map.
425    RemoveNodeFromCSEMaps(N);
426
427    // Next, brutally remove the operand list.  This is safe to do, as there are
428    // no cycles in the graph.
429    for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
430      SDNode *Operand = I->Val;
431      Operand->removeUser(N);
432
433      // Now that we removed this operand, see if there are no uses of it left.
434      if (Operand->use_empty())
435        DeadNodes.push_back(Operand);
436    }
437    if (N->OperandsNeedDelete)
438      delete[] N->OperandList;
439    N->OperandList = 0;
440    N->NumOperands = 0;
441
442    // Finally, remove N itself.
443    AllNodes.erase(N);
444  }
445
446  // If the root changed (e.g. it was a dead load, update the root).
447  setRoot(Dummy.getValue());
448}
449
450void SelectionDAG::RemoveDeadNode(SDNode *N, std::vector<SDNode*> &Deleted) {
451  SmallVector<SDNode*, 16> DeadNodes;
452  DeadNodes.push_back(N);
453
454  // Process the worklist, deleting the nodes and adding their uses to the
455  // worklist.
456  while (!DeadNodes.empty()) {
457    SDNode *N = DeadNodes.back();
458    DeadNodes.pop_back();
459
460    // Take the node out of the appropriate CSE map.
461    RemoveNodeFromCSEMaps(N);
462
463    // Next, brutally remove the operand list.  This is safe to do, as there are
464    // no cycles in the graph.
465    for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
466      SDNode *Operand = I->Val;
467      Operand->removeUser(N);
468
469      // Now that we removed this operand, see if there are no uses of it left.
470      if (Operand->use_empty())
471        DeadNodes.push_back(Operand);
472    }
473    if (N->OperandsNeedDelete)
474      delete[] N->OperandList;
475    N->OperandList = 0;
476    N->NumOperands = 0;
477
478    // Finally, remove N itself.
479    Deleted.push_back(N);
480    AllNodes.erase(N);
481  }
482}
483
484void SelectionDAG::DeleteNode(SDNode *N) {
485  assert(N->use_empty() && "Cannot delete a node that is not dead!");
486
487  // First take this out of the appropriate CSE map.
488  RemoveNodeFromCSEMaps(N);
489
490  // Finally, remove uses due to operands of this node, remove from the
491  // AllNodes list, and delete the node.
492  DeleteNodeNotInCSEMaps(N);
493}
494
495void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
496
497  // Remove it from the AllNodes list.
498  AllNodes.remove(N);
499
500  // Drop all of the operands and decrement used nodes use counts.
501  for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
502    I->Val->removeUser(N);
503  if (N->OperandsNeedDelete)
504    delete[] N->OperandList;
505  N->OperandList = 0;
506  N->NumOperands = 0;
507
508  delete N;
509}
510
511/// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
512/// correspond to it.  This is useful when we're about to delete or repurpose
513/// the node.  We don't want future request for structurally identical nodes
514/// to return N anymore.
515void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
516  bool Erased = false;
517  switch (N->getOpcode()) {
518  case ISD::HANDLENODE: return;  // noop.
519  case ISD::STRING:
520    Erased = StringNodes.erase(cast<StringSDNode>(N)->getValue());
521    break;
522  case ISD::CONDCODE:
523    assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
524           "Cond code doesn't exist!");
525    Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
526    CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
527    break;
528  case ISD::ExternalSymbol:
529    Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
530    break;
531  case ISD::TargetExternalSymbol:
532    Erased =
533      TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
534    break;
535  case ISD::VALUETYPE:
536    Erased = ValueTypeNodes[cast<VTSDNode>(N)->getVT()] != 0;
537    ValueTypeNodes[cast<VTSDNode>(N)->getVT()] = 0;
538    break;
539  default:
540    // Remove it from the CSE Map.
541    Erased = CSEMap.RemoveNode(N);
542    break;
543  }
544#ifndef NDEBUG
545  // Verify that the node was actually in one of the CSE maps, unless it has a
546  // flag result (which cannot be CSE'd) or is one of the special cases that are
547  // not subject to CSE.
548  if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
549      !N->isTargetOpcode()) {
550    N->dump(this);
551    cerr << "\n";
552    assert(0 && "Node is not in map!");
553  }
554#endif
555}
556
557/// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps.  It
558/// has been taken out and modified in some way.  If the specified node already
559/// exists in the CSE maps, do not modify the maps, but return the existing node
560/// instead.  If it doesn't exist, add it and return null.
561///
562SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
563  assert(N->getNumOperands() && "This is a leaf node!");
564  if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
565    return 0;    // Never add these nodes.
566
567  // Check that remaining values produced are not flags.
568  for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
569    if (N->getValueType(i) == MVT::Flag)
570      return 0;   // Never CSE anything that produces a flag.
571
572  SDNode *New = CSEMap.GetOrInsertNode(N);
573  if (New != N) return New;  // Node already existed.
574  return 0;
575}
576
577/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
578/// were replaced with those specified.  If this node is never memoized,
579/// return null, otherwise return a pointer to the slot it would take.  If a
580/// node already exists with these operands, the slot will be non-null.
581SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
582                                           void *&InsertPos) {
583  if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
584    return 0;    // Never add these nodes.
585
586  // Check that remaining values produced are not flags.
587  for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
588    if (N->getValueType(i) == MVT::Flag)
589      return 0;   // Never CSE anything that produces a flag.
590
591  SDOperand Ops[] = { Op };
592  FoldingSetNodeID ID;
593  AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
594  return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
595}
596
597/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
598/// were replaced with those specified.  If this node is never memoized,
599/// return null, otherwise return a pointer to the slot it would take.  If a
600/// node already exists with these operands, the slot will be non-null.
601SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
602                                           SDOperand Op1, SDOperand Op2,
603                                           void *&InsertPos) {
604  if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
605    return 0;    // Never add these nodes.
606
607  // Check that remaining values produced are not flags.
608  for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
609    if (N->getValueType(i) == MVT::Flag)
610      return 0;   // Never CSE anything that produces a flag.
611
612  SDOperand Ops[] = { Op1, Op2 };
613  FoldingSetNodeID ID;
614  AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
615  return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
616}
617
618
619/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
620/// were replaced with those specified.  If this node is never memoized,
621/// return null, otherwise return a pointer to the slot it would take.  If a
622/// node already exists with these operands, the slot will be non-null.
623SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
624                                           const SDOperand *Ops,unsigned NumOps,
625                                           void *&InsertPos) {
626  if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
627    return 0;    // Never add these nodes.
628
629  // Check that remaining values produced are not flags.
630  for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
631    if (N->getValueType(i) == MVT::Flag)
632      return 0;   // Never CSE anything that produces a flag.
633
634  FoldingSetNodeID ID;
635  AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
636
637  if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
638    ID.AddInteger(LD->getAddressingMode());
639    ID.AddInteger(LD->getExtensionType());
640    ID.AddInteger(LD->getLoadedVT());
641    ID.AddPointer(LD->getSrcValue());
642    ID.AddInteger(LD->getSrcValueOffset());
643    ID.AddInteger(LD->getAlignment());
644    ID.AddInteger(LD->isVolatile());
645  } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
646    ID.AddInteger(ST->getAddressingMode());
647    ID.AddInteger(ST->isTruncatingStore());
648    ID.AddInteger(ST->getStoredVT());
649    ID.AddPointer(ST->getSrcValue());
650    ID.AddInteger(ST->getSrcValueOffset());
651    ID.AddInteger(ST->getAlignment());
652    ID.AddInteger(ST->isVolatile());
653  }
654
655  return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
656}
657
658
659SelectionDAG::~SelectionDAG() {
660  while (!AllNodes.empty()) {
661    SDNode *N = AllNodes.begin();
662    N->SetNextInBucket(0);
663    if (N->OperandsNeedDelete)
664      delete [] N->OperandList;
665    N->OperandList = 0;
666    N->NumOperands = 0;
667    AllNodes.pop_front();
668  }
669}
670
671SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT::ValueType VT) {
672  if (Op.getValueType() == VT) return Op;
673  int64_t Imm = ~0ULL >> (64-MVT::getSizeInBits(VT));
674  return getNode(ISD::AND, Op.getValueType(), Op,
675                 getConstant(Imm, Op.getValueType()));
676}
677
678SDOperand SelectionDAG::getString(const std::string &Val) {
679  StringSDNode *&N = StringNodes[Val];
680  if (!N) {
681    N = new StringSDNode(Val);
682    AllNodes.push_back(N);
683  }
684  return SDOperand(N, 0);
685}
686
687SDOperand SelectionDAG::getConstant(uint64_t Val, MVT::ValueType VT, bool isT) {
688  assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
689  assert(!MVT::isVector(VT) && "Cannot create Vector ConstantSDNodes!");
690
691  // Mask out any bits that are not valid for this constant.
692  Val &= MVT::getIntVTBitMask(VT);
693
694  unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
695  FoldingSetNodeID ID;
696  AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
697  ID.AddInteger(Val);
698  void *IP = 0;
699  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
700    return SDOperand(E, 0);
701  SDNode *N = new ConstantSDNode(isT, Val, VT);
702  CSEMap.InsertNode(N, IP);
703  AllNodes.push_back(N);
704  return SDOperand(N, 0);
705}
706
707SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT::ValueType VT,
708                                      bool isTarget) {
709  assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
710
711  MVT::ValueType EltVT =
712    MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
713  bool isDouble = (EltVT == MVT::f64);
714  double Val = isDouble ? V.convertToDouble() : (double)V.convertToFloat();
715
716  // Do the map lookup using the actual bit pattern for the floating point
717  // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
718  // we don't have issues with SNANs.
719  unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
720  // ?? Should we store float/double/longdouble separately in ID?
721  FoldingSetNodeID ID;
722  AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
723  ID.AddDouble(Val);
724  void *IP = 0;
725  SDNode *N = NULL;
726  if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
727    if (!MVT::isVector(VT))
728      return SDOperand(N, 0);
729  if (!N) {
730    N = new ConstantFPSDNode(isTarget, Val, EltVT);
731    CSEMap.InsertNode(N, IP);
732    AllNodes.push_back(N);
733  }
734
735  SDOperand Result(N, 0);
736  if (MVT::isVector(VT)) {
737    SmallVector<SDOperand, 8> Ops;
738    Ops.assign(MVT::getVectorNumElements(VT), Result);
739    Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
740  }
741  return Result;
742}
743
744SDOperand SelectionDAG::getConstantFP(double Val, MVT::ValueType VT,
745                                      bool isTarget) {
746  MVT::ValueType EltVT =
747    MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
748  if (EltVT==MVT::f32)
749    return getConstantFP(APFloat((float)Val), VT, isTarget);
750  else
751    return getConstantFP(APFloat(Val), VT, isTarget);
752}
753
754SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
755                                         MVT::ValueType VT, int Offset,
756                                         bool isTargetGA) {
757  const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
758  unsigned Opc;
759  if (GVar && GVar->isThreadLocal())
760    Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
761  else
762    Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
763  FoldingSetNodeID ID;
764  AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
765  ID.AddPointer(GV);
766  ID.AddInteger(Offset);
767  void *IP = 0;
768  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
769   return SDOperand(E, 0);
770  SDNode *N = new GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
771  CSEMap.InsertNode(N, IP);
772  AllNodes.push_back(N);
773  return SDOperand(N, 0);
774}
775
776SDOperand SelectionDAG::getFrameIndex(int FI, MVT::ValueType VT,
777                                      bool isTarget) {
778  unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
779  FoldingSetNodeID ID;
780  AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
781  ID.AddInteger(FI);
782  void *IP = 0;
783  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
784    return SDOperand(E, 0);
785  SDNode *N = new FrameIndexSDNode(FI, VT, isTarget);
786  CSEMap.InsertNode(N, IP);
787  AllNodes.push_back(N);
788  return SDOperand(N, 0);
789}
790
791SDOperand SelectionDAG::getJumpTable(int JTI, MVT::ValueType VT, bool isTarget){
792  unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
793  FoldingSetNodeID ID;
794  AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
795  ID.AddInteger(JTI);
796  void *IP = 0;
797  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
798    return SDOperand(E, 0);
799  SDNode *N = new JumpTableSDNode(JTI, VT, isTarget);
800  CSEMap.InsertNode(N, IP);
801  AllNodes.push_back(N);
802  return SDOperand(N, 0);
803}
804
805SDOperand SelectionDAG::getConstantPool(Constant *C, MVT::ValueType VT,
806                                        unsigned Alignment, int Offset,
807                                        bool isTarget) {
808  unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
809  FoldingSetNodeID ID;
810  AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
811  ID.AddInteger(Alignment);
812  ID.AddInteger(Offset);
813  ID.AddPointer(C);
814  void *IP = 0;
815  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
816    return SDOperand(E, 0);
817  SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
818  CSEMap.InsertNode(N, IP);
819  AllNodes.push_back(N);
820  return SDOperand(N, 0);
821}
822
823
824SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C,
825                                        MVT::ValueType VT,
826                                        unsigned Alignment, int Offset,
827                                        bool isTarget) {
828  unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
829  FoldingSetNodeID ID;
830  AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
831  ID.AddInteger(Alignment);
832  ID.AddInteger(Offset);
833  C->AddSelectionDAGCSEId(ID);
834  void *IP = 0;
835  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
836    return SDOperand(E, 0);
837  SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
838  CSEMap.InsertNode(N, IP);
839  AllNodes.push_back(N);
840  return SDOperand(N, 0);
841}
842
843
844SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
845  FoldingSetNodeID ID;
846  AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
847  ID.AddPointer(MBB);
848  void *IP = 0;
849  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
850    return SDOperand(E, 0);
851  SDNode *N = new BasicBlockSDNode(MBB);
852  CSEMap.InsertNode(N, IP);
853  AllNodes.push_back(N);
854  return SDOperand(N, 0);
855}
856
857SDOperand SelectionDAG::getValueType(MVT::ValueType VT) {
858  if ((unsigned)VT >= ValueTypeNodes.size())
859    ValueTypeNodes.resize(VT+1);
860  if (ValueTypeNodes[VT] == 0) {
861    ValueTypeNodes[VT] = new VTSDNode(VT);
862    AllNodes.push_back(ValueTypeNodes[VT]);
863  }
864
865  return SDOperand(ValueTypeNodes[VT], 0);
866}
867
868SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT::ValueType VT) {
869  SDNode *&N = ExternalSymbols[Sym];
870  if (N) return SDOperand(N, 0);
871  N = new ExternalSymbolSDNode(false, Sym, VT);
872  AllNodes.push_back(N);
873  return SDOperand(N, 0);
874}
875
876SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym,
877                                                MVT::ValueType VT) {
878  SDNode *&N = TargetExternalSymbols[Sym];
879  if (N) return SDOperand(N, 0);
880  N = new ExternalSymbolSDNode(true, Sym, VT);
881  AllNodes.push_back(N);
882  return SDOperand(N, 0);
883}
884
885SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
886  if ((unsigned)Cond >= CondCodeNodes.size())
887    CondCodeNodes.resize(Cond+1);
888
889  if (CondCodeNodes[Cond] == 0) {
890    CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
891    AllNodes.push_back(CondCodeNodes[Cond]);
892  }
893  return SDOperand(CondCodeNodes[Cond], 0);
894}
895
896SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT::ValueType VT) {
897  FoldingSetNodeID ID;
898  AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
899  ID.AddInteger(RegNo);
900  void *IP = 0;
901  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
902    return SDOperand(E, 0);
903  SDNode *N = new RegisterSDNode(RegNo, VT);
904  CSEMap.InsertNode(N, IP);
905  AllNodes.push_back(N);
906  return SDOperand(N, 0);
907}
908
909SDOperand SelectionDAG::getSrcValue(const Value *V, int Offset) {
910  assert((!V || isa<PointerType>(V->getType())) &&
911         "SrcValue is not a pointer?");
912
913  FoldingSetNodeID ID;
914  AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
915  ID.AddPointer(V);
916  ID.AddInteger(Offset);
917  void *IP = 0;
918  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
919    return SDOperand(E, 0);
920  SDNode *N = new SrcValueSDNode(V, Offset);
921  CSEMap.InsertNode(N, IP);
922  AllNodes.push_back(N);
923  return SDOperand(N, 0);
924}
925
926SDOperand SelectionDAG::FoldSetCC(MVT::ValueType VT, SDOperand N1,
927                                  SDOperand N2, ISD::CondCode Cond) {
928  // These setcc operations always fold.
929  switch (Cond) {
930  default: break;
931  case ISD::SETFALSE:
932  case ISD::SETFALSE2: return getConstant(0, VT);
933  case ISD::SETTRUE:
934  case ISD::SETTRUE2:  return getConstant(1, VT);
935
936  case ISD::SETOEQ:
937  case ISD::SETOGT:
938  case ISD::SETOGE:
939  case ISD::SETOLT:
940  case ISD::SETOLE:
941  case ISD::SETONE:
942  case ISD::SETO:
943  case ISD::SETUO:
944  case ISD::SETUEQ:
945  case ISD::SETUNE:
946    assert(!MVT::isInteger(N1.getValueType()) && "Illegal setcc for integer!");
947    break;
948  }
949
950  if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
951    uint64_t C2 = N2C->getValue();
952    if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
953      uint64_t C1 = N1C->getValue();
954
955      // Sign extend the operands if required
956      if (ISD::isSignedIntSetCC(Cond)) {
957        C1 = N1C->getSignExtended();
958        C2 = N2C->getSignExtended();
959      }
960
961      switch (Cond) {
962      default: assert(0 && "Unknown integer setcc!");
963      case ISD::SETEQ:  return getConstant(C1 == C2, VT);
964      case ISD::SETNE:  return getConstant(C1 != C2, VT);
965      case ISD::SETULT: return getConstant(C1 <  C2, VT);
966      case ISD::SETUGT: return getConstant(C1 >  C2, VT);
967      case ISD::SETULE: return getConstant(C1 <= C2, VT);
968      case ISD::SETUGE: return getConstant(C1 >= C2, VT);
969      case ISD::SETLT:  return getConstant((int64_t)C1 <  (int64_t)C2, VT);
970      case ISD::SETGT:  return getConstant((int64_t)C1 >  (int64_t)C2, VT);
971      case ISD::SETLE:  return getConstant((int64_t)C1 <= (int64_t)C2, VT);
972      case ISD::SETGE:  return getConstant((int64_t)C1 >= (int64_t)C2, VT);
973      }
974    }
975  }
976  if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val))
977    if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
978
979      APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
980      switch (Cond) {
981      default: break;
982      case ISD::SETOEQ:
983      case ISD::SETEQ:  return getConstant(R==APFloat::cmpEqual, VT);
984      case ISD::SETONE:
985      case ISD::SETNE:  return getConstant(R==APFloat::cmpGreaterThan ||
986                                           R==APFloat::cmpLessThan, VT);
987      case ISD::SETOLT:
988      case ISD::SETLT:  return getConstant(R==APFloat::cmpLessThan, VT);
989      case ISD::SETOGT:
990      case ISD::SETGT:  return getConstant(R==APFloat::cmpGreaterThan, VT);
991      case ISD::SETOLE:
992      case ISD::SETLE:  return getConstant(R==APFloat::cmpLessThan ||
993                                           R==APFloat::cmpEqual, VT);
994      case ISD::SETOGE:
995      case ISD::SETGE:  return getConstant(R==APFloat::cmpGreaterThan ||
996                                           R==APFloat::cmpEqual, VT);
997      case ISD::SETO:   return getConstant(R!=APFloat::cmpUnordered, VT);
998      case ISD::SETUO:  return getConstant(R==APFloat::cmpUnordered, VT);
999      case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1000                                           R==APFloat::cmpEqual, VT);
1001      case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1002      case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1003                                           R==APFloat::cmpLessThan, VT);
1004      case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1005                                           R==APFloat::cmpUnordered, VT);
1006      case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1007      case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1008      }
1009    } else {
1010      // Ensure that the constant occurs on the RHS.
1011      return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1012    }
1013
1014  // Could not fold it.
1015  return SDOperand();
1016}
1017
1018/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
1019/// this predicate to simplify operations downstream.  Mask is known to be zero
1020/// for bits that V cannot have.
1021bool SelectionDAG::MaskedValueIsZero(SDOperand Op, uint64_t Mask,
1022                                     unsigned Depth) const {
1023  // The masks are not wide enough to represent this type!  Should use APInt.
1024  if (Op.getValueType() == MVT::i128)
1025    return false;
1026
1027  uint64_t KnownZero, KnownOne;
1028  ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1029  assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1030  return (KnownZero & Mask) == Mask;
1031}
1032
1033/// ComputeMaskedBits - Determine which of the bits specified in Mask are
1034/// known to be either zero or one and return them in the KnownZero/KnownOne
1035/// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
1036/// processing.
1037void SelectionDAG::ComputeMaskedBits(SDOperand Op, uint64_t Mask,
1038                                     uint64_t &KnownZero, uint64_t &KnownOne,
1039                                     unsigned Depth) const {
1040  KnownZero = KnownOne = 0;   // Don't know anything.
1041  if (Depth == 6 || Mask == 0)
1042    return;  // Limit search depth.
1043
1044  // The masks are not wide enough to represent this type!  Should use APInt.
1045  if (Op.getValueType() == MVT::i128)
1046    return;
1047
1048  uint64_t KnownZero2, KnownOne2;
1049
1050  switch (Op.getOpcode()) {
1051  case ISD::Constant:
1052    // We know all of the bits for a constant!
1053    KnownOne = cast<ConstantSDNode>(Op)->getValue() & Mask;
1054    KnownZero = ~KnownOne & Mask;
1055    return;
1056  case ISD::AND:
1057    // If either the LHS or the RHS are Zero, the result is zero.
1058    ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1059    Mask &= ~KnownZero;
1060    ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1061    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1062    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1063
1064    // Output known-1 bits are only known if set in both the LHS & RHS.
1065    KnownOne &= KnownOne2;
1066    // Output known-0 are known to be clear if zero in either the LHS | RHS.
1067    KnownZero |= KnownZero2;
1068    return;
1069  case ISD::OR:
1070    ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1071    Mask &= ~KnownOne;
1072    ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1073    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1074    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1075
1076    // Output known-0 bits are only known if clear in both the LHS & RHS.
1077    KnownZero &= KnownZero2;
1078    // Output known-1 are known to be set if set in either the LHS | RHS.
1079    KnownOne |= KnownOne2;
1080    return;
1081  case ISD::XOR: {
1082    ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1083    ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1084    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1085    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1086
1087    // Output known-0 bits are known if clear or set in both the LHS & RHS.
1088    uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1089    // Output known-1 are known to be set if set in only one of the LHS, RHS.
1090    KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1091    KnownZero = KnownZeroOut;
1092    return;
1093  }
1094  case ISD::SELECT:
1095    ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1096    ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1097    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1098    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1099
1100    // Only known if known in both the LHS and RHS.
1101    KnownOne &= KnownOne2;
1102    KnownZero &= KnownZero2;
1103    return;
1104  case ISD::SELECT_CC:
1105    ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1106    ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1107    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1108    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1109
1110    // Only known if known in both the LHS and RHS.
1111    KnownOne &= KnownOne2;
1112    KnownZero &= KnownZero2;
1113    return;
1114  case ISD::SETCC:
1115    // If we know the result of a setcc has the top bits zero, use this info.
1116    if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult)
1117      KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
1118    return;
1119  case ISD::SHL:
1120    // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
1121    if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1122      ComputeMaskedBits(Op.getOperand(0), Mask >> SA->getValue(),
1123                        KnownZero, KnownOne, Depth+1);
1124      assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1125      KnownZero <<= SA->getValue();
1126      KnownOne  <<= SA->getValue();
1127      KnownZero |= (1ULL << SA->getValue())-1;  // low bits known zero.
1128    }
1129    return;
1130  case ISD::SRL:
1131    // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
1132    if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1133      MVT::ValueType VT = Op.getValueType();
1134      unsigned ShAmt = SA->getValue();
1135
1136      uint64_t TypeMask = MVT::getIntVTBitMask(VT);
1137      ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt) & TypeMask,
1138                        KnownZero, KnownOne, Depth+1);
1139      assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1140      KnownZero &= TypeMask;
1141      KnownOne  &= TypeMask;
1142      KnownZero >>= ShAmt;
1143      KnownOne  >>= ShAmt;
1144
1145      uint64_t HighBits = (1ULL << ShAmt)-1;
1146      HighBits <<= MVT::getSizeInBits(VT)-ShAmt;
1147      KnownZero |= HighBits;  // High bits known zero.
1148    }
1149    return;
1150  case ISD::SRA:
1151    if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1152      MVT::ValueType VT = Op.getValueType();
1153      unsigned ShAmt = SA->getValue();
1154
1155      // Compute the new bits that are at the top now.
1156      uint64_t TypeMask = MVT::getIntVTBitMask(VT);
1157
1158      uint64_t InDemandedMask = (Mask << ShAmt) & TypeMask;
1159      // If any of the demanded bits are produced by the sign extension, we also
1160      // demand the input sign bit.
1161      uint64_t HighBits = (1ULL << ShAmt)-1;
1162      HighBits <<= MVT::getSizeInBits(VT) - ShAmt;
1163      if (HighBits & Mask)
1164        InDemandedMask |= MVT::getIntVTSignBit(VT);
1165
1166      ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1167                        Depth+1);
1168      assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1169      KnownZero &= TypeMask;
1170      KnownOne  &= TypeMask;
1171      KnownZero >>= ShAmt;
1172      KnownOne  >>= ShAmt;
1173
1174      // Handle the sign bits.
1175      uint64_t SignBit = MVT::getIntVTSignBit(VT);
1176      SignBit >>= ShAmt;  // Adjust to where it is now in the mask.
1177
1178      if (KnownZero & SignBit) {
1179        KnownZero |= HighBits;  // New bits are known zero.
1180      } else if (KnownOne & SignBit) {
1181        KnownOne  |= HighBits;  // New bits are known one.
1182      }
1183    }
1184    return;
1185  case ISD::SIGN_EXTEND_INREG: {
1186    MVT::ValueType EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1187
1188    // Sign extension.  Compute the demanded bits in the result that are not
1189    // present in the input.
1190    uint64_t NewBits = ~MVT::getIntVTBitMask(EVT) & Mask;
1191
1192    uint64_t InSignBit = MVT::getIntVTSignBit(EVT);
1193    int64_t InputDemandedBits = Mask & MVT::getIntVTBitMask(EVT);
1194
1195    // If the sign extended bits are demanded, we know that the sign
1196    // bit is demanded.
1197    if (NewBits)
1198      InputDemandedBits |= InSignBit;
1199
1200    ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1201                      KnownZero, KnownOne, Depth+1);
1202    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1203
1204    // If the sign bit of the input is known set or clear, then we know the
1205    // top bits of the result.
1206    if (KnownZero & InSignBit) {          // Input sign bit known clear
1207      KnownZero |= NewBits;
1208      KnownOne  &= ~NewBits;
1209    } else if (KnownOne & InSignBit) {    // Input sign bit known set
1210      KnownOne  |= NewBits;
1211      KnownZero &= ~NewBits;
1212    } else {                              // Input sign bit unknown
1213      KnownZero &= ~NewBits;
1214      KnownOne  &= ~NewBits;
1215    }
1216    return;
1217  }
1218  case ISD::CTTZ:
1219  case ISD::CTLZ:
1220  case ISD::CTPOP: {
1221    MVT::ValueType VT = Op.getValueType();
1222    unsigned LowBits = Log2_32(MVT::getSizeInBits(VT))+1;
1223    KnownZero = ~((1ULL << LowBits)-1) & MVT::getIntVTBitMask(VT);
1224    KnownOne  = 0;
1225    return;
1226  }
1227  case ISD::LOAD: {
1228    if (ISD::isZEXTLoad(Op.Val)) {
1229      LoadSDNode *LD = cast<LoadSDNode>(Op);
1230      MVT::ValueType VT = LD->getLoadedVT();
1231      KnownZero |= ~MVT::getIntVTBitMask(VT) & Mask;
1232    }
1233    return;
1234  }
1235  case ISD::ZERO_EXTEND: {
1236    uint64_t InMask  = MVT::getIntVTBitMask(Op.getOperand(0).getValueType());
1237    uint64_t NewBits = (~InMask) & Mask;
1238    ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1239                      KnownOne, Depth+1);
1240    KnownZero |= NewBits & Mask;
1241    KnownOne  &= ~NewBits;
1242    return;
1243  }
1244  case ISD::SIGN_EXTEND: {
1245    MVT::ValueType InVT = Op.getOperand(0).getValueType();
1246    unsigned InBits    = MVT::getSizeInBits(InVT);
1247    uint64_t InMask    = MVT::getIntVTBitMask(InVT);
1248    uint64_t InSignBit = 1ULL << (InBits-1);
1249    uint64_t NewBits   = (~InMask) & Mask;
1250    uint64_t InDemandedBits = Mask & InMask;
1251
1252    // If any of the sign extended bits are demanded, we know that the sign
1253    // bit is demanded.
1254    if (NewBits & Mask)
1255      InDemandedBits |= InSignBit;
1256
1257    ComputeMaskedBits(Op.getOperand(0), InDemandedBits, KnownZero,
1258                      KnownOne, Depth+1);
1259    // If the sign bit is known zero or one, the  top bits match.
1260    if (KnownZero & InSignBit) {
1261      KnownZero |= NewBits;
1262      KnownOne  &= ~NewBits;
1263    } else if (KnownOne & InSignBit) {
1264      KnownOne  |= NewBits;
1265      KnownZero &= ~NewBits;
1266    } else {   // Otherwise, top bits aren't known.
1267      KnownOne  &= ~NewBits;
1268      KnownZero &= ~NewBits;
1269    }
1270    return;
1271  }
1272  case ISD::ANY_EXTEND: {
1273    MVT::ValueType VT = Op.getOperand(0).getValueType();
1274    ComputeMaskedBits(Op.getOperand(0), Mask & MVT::getIntVTBitMask(VT),
1275                      KnownZero, KnownOne, Depth+1);
1276    return;
1277  }
1278  case ISD::TRUNCATE: {
1279    ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1280    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1281    uint64_t OutMask = MVT::getIntVTBitMask(Op.getValueType());
1282    KnownZero &= OutMask;
1283    KnownOne &= OutMask;
1284    break;
1285  }
1286  case ISD::AssertZext: {
1287    MVT::ValueType VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1288    uint64_t InMask = MVT::getIntVTBitMask(VT);
1289    ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1290                      KnownOne, Depth+1);
1291    KnownZero |= (~InMask) & Mask;
1292    return;
1293  }
1294  case ISD::ADD: {
1295    // If either the LHS or the RHS are Zero, the result is zero.
1296    ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1297    ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1298    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1299    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1300
1301    // Output known-0 bits are known if clear or set in both the low clear bits
1302    // common to both LHS & RHS.  For example, 8+(X<<3) is known to have the
1303    // low 3 bits clear.
1304    uint64_t KnownZeroOut = std::min(CountTrailingZeros_64(~KnownZero),
1305                                     CountTrailingZeros_64(~KnownZero2));
1306
1307    KnownZero = (1ULL << KnownZeroOut) - 1;
1308    KnownOne = 0;
1309    return;
1310  }
1311  case ISD::SUB: {
1312    ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0));
1313    if (!CLHS) return;
1314
1315    // We know that the top bits of C-X are clear if X contains less bits
1316    // than C (i.e. no wrap-around can happen).  For example, 20-X is
1317    // positive if we can prove that X is >= 0 and < 16.
1318    MVT::ValueType VT = CLHS->getValueType(0);
1319    if ((CLHS->getValue() & MVT::getIntVTSignBit(VT)) == 0) {  // sign bit clear
1320      unsigned NLZ = CountLeadingZeros_64(CLHS->getValue()+1);
1321      uint64_t MaskV = (1ULL << (63-NLZ))-1; // NLZ can't be 64 with no sign bit
1322      MaskV = ~MaskV & MVT::getIntVTBitMask(VT);
1323      ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero, KnownOne, Depth+1);
1324
1325      // If all of the MaskV bits are known to be zero, then we know the output
1326      // top bits are zero, because we now know that the output is from [0-C].
1327      if ((KnownZero & MaskV) == MaskV) {
1328        unsigned NLZ2 = CountLeadingZeros_64(CLHS->getValue());
1329        KnownZero = ~((1ULL << (64-NLZ2))-1) & Mask;  // Top bits known zero.
1330        KnownOne = 0;   // No one bits known.
1331      } else {
1332        KnownZero = KnownOne = 0;  // Otherwise, nothing known.
1333      }
1334    }
1335    return;
1336  }
1337  default:
1338    // Allow the target to implement this method for its nodes.
1339    if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1340  case ISD::INTRINSIC_WO_CHAIN:
1341  case ISD::INTRINSIC_W_CHAIN:
1342  case ISD::INTRINSIC_VOID:
1343      TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1344    }
1345    return;
1346  }
1347}
1348
1349/// ComputeNumSignBits - Return the number of times the sign bit of the
1350/// register is replicated into the other bits.  We know that at least 1 bit
1351/// is always equal to the sign bit (itself), but other cases can give us
1352/// information.  For example, immediately after an "SRA X, 2", we know that
1353/// the top 3 bits are all equal to each other, so we return 3.
1354unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
1355  MVT::ValueType VT = Op.getValueType();
1356  assert(MVT::isInteger(VT) && "Invalid VT!");
1357  unsigned VTBits = MVT::getSizeInBits(VT);
1358  unsigned Tmp, Tmp2;
1359
1360  if (Depth == 6)
1361    return 1;  // Limit search depth.
1362
1363  switch (Op.getOpcode()) {
1364  default: break;
1365  case ISD::AssertSext:
1366    Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1367    return VTBits-Tmp+1;
1368  case ISD::AssertZext:
1369    Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1370    return VTBits-Tmp;
1371
1372  case ISD::Constant: {
1373    uint64_t Val = cast<ConstantSDNode>(Op)->getValue();
1374    // If negative, invert the bits, then look at it.
1375    if (Val & MVT::getIntVTSignBit(VT))
1376      Val = ~Val;
1377
1378    // Shift the bits so they are the leading bits in the int64_t.
1379    Val <<= 64-VTBits;
1380
1381    // Return # leading zeros.  We use 'min' here in case Val was zero before
1382    // shifting.  We don't want to return '64' as for an i32 "0".
1383    return std::min(VTBits, CountLeadingZeros_64(Val));
1384  }
1385
1386  case ISD::SIGN_EXTEND:
1387    Tmp = VTBits-MVT::getSizeInBits(Op.getOperand(0).getValueType());
1388    return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1389
1390  case ISD::SIGN_EXTEND_INREG:
1391    // Max of the input and what this extends.
1392    Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1393    Tmp = VTBits-Tmp+1;
1394
1395    Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1396    return std::max(Tmp, Tmp2);
1397
1398  case ISD::SRA:
1399    Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1400    // SRA X, C   -> adds C sign bits.
1401    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1402      Tmp += C->getValue();
1403      if (Tmp > VTBits) Tmp = VTBits;
1404    }
1405    return Tmp;
1406  case ISD::SHL:
1407    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1408      // shl destroys sign bits.
1409      Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1410      if (C->getValue() >= VTBits ||      // Bad shift.
1411          C->getValue() >= Tmp) break;    // Shifted all sign bits out.
1412      return Tmp - C->getValue();
1413    }
1414    break;
1415  case ISD::AND:
1416  case ISD::OR:
1417  case ISD::XOR:    // NOT is handled here.
1418    // Logical binary ops preserve the number of sign bits.
1419    Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1420    if (Tmp == 1) return 1;  // Early out.
1421    Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1422    return std::min(Tmp, Tmp2);
1423
1424  case ISD::SELECT:
1425    Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1426    if (Tmp == 1) return 1;  // Early out.
1427    Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1428    return std::min(Tmp, Tmp2);
1429
1430  case ISD::SETCC:
1431    // If setcc returns 0/-1, all bits are sign bits.
1432    if (TLI.getSetCCResultContents() ==
1433        TargetLowering::ZeroOrNegativeOneSetCCResult)
1434      return VTBits;
1435    break;
1436  case ISD::ROTL:
1437  case ISD::ROTR:
1438    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1439      unsigned RotAmt = C->getValue() & (VTBits-1);
1440
1441      // Handle rotate right by N like a rotate left by 32-N.
1442      if (Op.getOpcode() == ISD::ROTR)
1443        RotAmt = (VTBits-RotAmt) & (VTBits-1);
1444
1445      // If we aren't rotating out all of the known-in sign bits, return the
1446      // number that are left.  This handles rotl(sext(x), 1) for example.
1447      Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1448      if (Tmp > RotAmt+1) return Tmp-RotAmt;
1449    }
1450    break;
1451  case ISD::ADD:
1452    // Add can have at most one carry bit.  Thus we know that the output
1453    // is, at worst, one more bit than the inputs.
1454    Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1455    if (Tmp == 1) return 1;  // Early out.
1456
1457    // Special case decrementing a value (ADD X, -1):
1458    if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1459      if (CRHS->isAllOnesValue()) {
1460        uint64_t KnownZero, KnownOne;
1461        uint64_t Mask = MVT::getIntVTBitMask(VT);
1462        ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1463
1464        // If the input is known to be 0 or 1, the output is 0/-1, which is all
1465        // sign bits set.
1466        if ((KnownZero|1) == Mask)
1467          return VTBits;
1468
1469        // If we are subtracting one from a positive number, there is no carry
1470        // out of the result.
1471        if (KnownZero & MVT::getIntVTSignBit(VT))
1472          return Tmp;
1473      }
1474
1475    Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1476    if (Tmp2 == 1) return 1;
1477      return std::min(Tmp, Tmp2)-1;
1478    break;
1479
1480  case ISD::SUB:
1481    Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1482    if (Tmp2 == 1) return 1;
1483
1484    // Handle NEG.
1485    if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1486      if (CLHS->getValue() == 0) {
1487        uint64_t KnownZero, KnownOne;
1488        uint64_t Mask = MVT::getIntVTBitMask(VT);
1489        ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1490        // If the input is known to be 0 or 1, the output is 0/-1, which is all
1491        // sign bits set.
1492        if ((KnownZero|1) == Mask)
1493          return VTBits;
1494
1495        // If the input is known to be positive (the sign bit is known clear),
1496        // the output of the NEG has the same number of sign bits as the input.
1497        if (KnownZero & MVT::getIntVTSignBit(VT))
1498          return Tmp2;
1499
1500        // Otherwise, we treat this like a SUB.
1501      }
1502
1503    // Sub can have at most one carry bit.  Thus we know that the output
1504    // is, at worst, one more bit than the inputs.
1505    Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1506    if (Tmp == 1) return 1;  // Early out.
1507      return std::min(Tmp, Tmp2)-1;
1508    break;
1509  case ISD::TRUNCATE:
1510    // FIXME: it's tricky to do anything useful for this, but it is an important
1511    // case for targets like X86.
1512    break;
1513  }
1514
1515  // Handle LOADX separately here. EXTLOAD case will fallthrough.
1516  if (Op.getOpcode() == ISD::LOAD) {
1517    LoadSDNode *LD = cast<LoadSDNode>(Op);
1518    unsigned ExtType = LD->getExtensionType();
1519    switch (ExtType) {
1520    default: break;
1521    case ISD::SEXTLOAD:    // '17' bits known
1522      Tmp = MVT::getSizeInBits(LD->getLoadedVT());
1523      return VTBits-Tmp+1;
1524    case ISD::ZEXTLOAD:    // '16' bits known
1525      Tmp = MVT::getSizeInBits(LD->getLoadedVT());
1526      return VTBits-Tmp;
1527    }
1528  }
1529
1530  // Allow the target to implement this method for its nodes.
1531  if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1532      Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1533      Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1534      Op.getOpcode() == ISD::INTRINSIC_VOID) {
1535    unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1536    if (NumBits > 1) return NumBits;
1537  }
1538
1539  // Finally, if we can prove that the top bits of the result are 0's or 1's,
1540  // use this information.
1541  uint64_t KnownZero, KnownOne;
1542  uint64_t Mask = MVT::getIntVTBitMask(VT);
1543  ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1544
1545  uint64_t SignBit = MVT::getIntVTSignBit(VT);
1546  if (KnownZero & SignBit) {        // SignBit is 0
1547    Mask = KnownZero;
1548  } else if (KnownOne & SignBit) {  // SignBit is 1;
1549    Mask = KnownOne;
1550  } else {
1551    // Nothing known.
1552    return 1;
1553  }
1554
1555  // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
1556  // the number of identical bits in the top of the input value.
1557  Mask ^= ~0ULL;
1558  Mask <<= 64-VTBits;
1559  // Return # leading zeros.  We use 'min' here in case Val was zero before
1560  // shifting.  We don't want to return '64' as for an i32 "0".
1561  return std::min(VTBits, CountLeadingZeros_64(Mask));
1562}
1563
1564
1565/// getNode - Gets or creates the specified node.
1566///
1567SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
1568  FoldingSetNodeID ID;
1569  AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
1570  void *IP = 0;
1571  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1572    return SDOperand(E, 0);
1573  SDNode *N = new SDNode(Opcode, SDNode::getSDVTList(VT));
1574  CSEMap.InsertNode(N, IP);
1575
1576  AllNodes.push_back(N);
1577  return SDOperand(N, 0);
1578}
1579
1580SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1581                                SDOperand Operand) {
1582  unsigned Tmp1;
1583  // Constant fold unary operations with an integer constant operand.
1584  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1585    uint64_t Val = C->getValue();
1586    switch (Opcode) {
1587    default: break;
1588    case ISD::SIGN_EXTEND: return getConstant(C->getSignExtended(), VT);
1589    case ISD::ANY_EXTEND:
1590    case ISD::ZERO_EXTEND: return getConstant(Val, VT);
1591    case ISD::TRUNCATE:    return getConstant(Val, VT);
1592    case ISD::SINT_TO_FP:  return getConstantFP(C->getSignExtended(), VT);
1593    case ISD::UINT_TO_FP:  return getConstantFP(C->getValue(), VT);
1594    case ISD::BIT_CONVERT:
1595      if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
1596        return getConstantFP(BitsToFloat(Val), VT);
1597      else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
1598        return getConstantFP(BitsToDouble(Val), VT);
1599      break;
1600    case ISD::BSWAP:
1601      switch(VT) {
1602      default: assert(0 && "Invalid bswap!"); break;
1603      case MVT::i16: return getConstant(ByteSwap_16((unsigned short)Val), VT);
1604      case MVT::i32: return getConstant(ByteSwap_32((unsigned)Val), VT);
1605      case MVT::i64: return getConstant(ByteSwap_64(Val), VT);
1606      }
1607      break;
1608    case ISD::CTPOP:
1609      switch(VT) {
1610      default: assert(0 && "Invalid ctpop!"); break;
1611      case MVT::i1: return getConstant(Val != 0, VT);
1612      case MVT::i8:
1613        Tmp1 = (unsigned)Val & 0xFF;
1614        return getConstant(CountPopulation_32(Tmp1), VT);
1615      case MVT::i16:
1616        Tmp1 = (unsigned)Val & 0xFFFF;
1617        return getConstant(CountPopulation_32(Tmp1), VT);
1618      case MVT::i32:
1619        return getConstant(CountPopulation_32((unsigned)Val), VT);
1620      case MVT::i64:
1621        return getConstant(CountPopulation_64(Val), VT);
1622      }
1623    case ISD::CTLZ:
1624      switch(VT) {
1625      default: assert(0 && "Invalid ctlz!"); break;
1626      case MVT::i1: return getConstant(Val == 0, VT);
1627      case MVT::i8:
1628        Tmp1 = (unsigned)Val & 0xFF;
1629        return getConstant(CountLeadingZeros_32(Tmp1)-24, VT);
1630      case MVT::i16:
1631        Tmp1 = (unsigned)Val & 0xFFFF;
1632        return getConstant(CountLeadingZeros_32(Tmp1)-16, VT);
1633      case MVT::i32:
1634        return getConstant(CountLeadingZeros_32((unsigned)Val), VT);
1635      case MVT::i64:
1636        return getConstant(CountLeadingZeros_64(Val), VT);
1637      }
1638    case ISD::CTTZ:
1639      switch(VT) {
1640      default: assert(0 && "Invalid cttz!"); break;
1641      case MVT::i1: return getConstant(Val == 0, VT);
1642      case MVT::i8:
1643        Tmp1 = (unsigned)Val | 0x100;
1644        return getConstant(CountTrailingZeros_32(Tmp1), VT);
1645      case MVT::i16:
1646        Tmp1 = (unsigned)Val | 0x10000;
1647        return getConstant(CountTrailingZeros_32(Tmp1), VT);
1648      case MVT::i32:
1649        return getConstant(CountTrailingZeros_32((unsigned)Val), VT);
1650      case MVT::i64:
1651        return getConstant(CountTrailingZeros_64(Val), VT);
1652      }
1653    }
1654  }
1655
1656  // Constant fold unary operations with an floating point constant operand.
1657  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val))
1658    switch (Opcode) {
1659    case ISD::FNEG:
1660      return getConstantFP(-C->getValue(), VT);
1661    case ISD::FABS:
1662      return getConstantFP(fabs(C->getValue()), VT);
1663    case ISD::FP_ROUND:
1664    case ISD::FP_EXTEND:
1665      return getConstantFP(C->getValue(), VT);
1666    case ISD::FP_TO_SINT:
1667      return getConstant((int64_t)C->getValue(), VT);
1668    case ISD::FP_TO_UINT:
1669      return getConstant((uint64_t)C->getValue(), VT);
1670    case ISD::BIT_CONVERT:
1671      if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
1672        return getConstant(FloatToBits(C->getValue()), VT);
1673      else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
1674        return getConstant(DoubleToBits(C->getValue()), VT);
1675      break;
1676    }
1677
1678  unsigned OpOpcode = Operand.Val->getOpcode();
1679  switch (Opcode) {
1680  case ISD::TokenFactor:
1681    return Operand;         // Factor of one node?  No factor.
1682  case ISD::FP_ROUND:
1683  case ISD::FP_EXTEND:
1684    assert(MVT::isFloatingPoint(VT) &&
1685           MVT::isFloatingPoint(Operand.getValueType()) && "Invalid FP cast!");
1686    break;
1687  case ISD::SIGN_EXTEND:
1688    assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1689           "Invalid SIGN_EXTEND!");
1690    if (Operand.getValueType() == VT) return Operand;   // noop extension
1691    assert(Operand.getValueType() < VT && "Invalid sext node, dst < src!");
1692    if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
1693      return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1694    break;
1695  case ISD::ZERO_EXTEND:
1696    assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1697           "Invalid ZERO_EXTEND!");
1698    if (Operand.getValueType() == VT) return Operand;   // noop extension
1699    assert(Operand.getValueType() < VT && "Invalid zext node, dst < src!");
1700    if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
1701      return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
1702    break;
1703  case ISD::ANY_EXTEND:
1704    assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1705           "Invalid ANY_EXTEND!");
1706    if (Operand.getValueType() == VT) return Operand;   // noop extension
1707    assert(Operand.getValueType() < VT && "Invalid anyext node, dst < src!");
1708    if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
1709      // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
1710      return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1711    break;
1712  case ISD::TRUNCATE:
1713    assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1714           "Invalid TRUNCATE!");
1715    if (Operand.getValueType() == VT) return Operand;   // noop truncate
1716    assert(Operand.getValueType() > VT && "Invalid truncate node, src < dst!");
1717    if (OpOpcode == ISD::TRUNCATE)
1718      return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1719    else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
1720             OpOpcode == ISD::ANY_EXTEND) {
1721      // If the source is smaller than the dest, we still need an extend.
1722      if (Operand.Val->getOperand(0).getValueType() < VT)
1723        return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1724      else if (Operand.Val->getOperand(0).getValueType() > VT)
1725        return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1726      else
1727        return Operand.Val->getOperand(0);
1728    }
1729    break;
1730  case ISD::BIT_CONVERT:
1731    // Basic sanity checking.
1732    assert(MVT::getSizeInBits(VT) == MVT::getSizeInBits(Operand.getValueType())
1733           && "Cannot BIT_CONVERT between types of different sizes!");
1734    if (VT == Operand.getValueType()) return Operand;  // noop conversion.
1735    if (OpOpcode == ISD::BIT_CONVERT)  // bitconv(bitconv(x)) -> bitconv(x)
1736      return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
1737    if (OpOpcode == ISD::UNDEF)
1738      return getNode(ISD::UNDEF, VT);
1739    break;
1740  case ISD::SCALAR_TO_VECTOR:
1741    assert(MVT::isVector(VT) && !MVT::isVector(Operand.getValueType()) &&
1742           MVT::getVectorElementType(VT) == Operand.getValueType() &&
1743           "Illegal SCALAR_TO_VECTOR node!");
1744    break;
1745  case ISD::FNEG:
1746    if (OpOpcode == ISD::FSUB)   // -(X-Y) -> (Y-X)
1747      return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
1748                     Operand.Val->getOperand(0));
1749    if (OpOpcode == ISD::FNEG)  // --X -> X
1750      return Operand.Val->getOperand(0);
1751    break;
1752  case ISD::FABS:
1753    if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
1754      return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
1755    break;
1756  }
1757
1758  SDNode *N;
1759  SDVTList VTs = getVTList(VT);
1760  if (VT != MVT::Flag) { // Don't CSE flag producing nodes
1761    FoldingSetNodeID ID;
1762    SDOperand Ops[1] = { Operand };
1763    AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
1764    void *IP = 0;
1765    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1766      return SDOperand(E, 0);
1767    N = new UnarySDNode(Opcode, VTs, Operand);
1768    CSEMap.InsertNode(N, IP);
1769  } else {
1770    N = new UnarySDNode(Opcode, VTs, Operand);
1771  }
1772  AllNodes.push_back(N);
1773  return SDOperand(N, 0);
1774}
1775
1776
1777
1778SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1779                                SDOperand N1, SDOperand N2) {
1780#ifndef NDEBUG
1781  switch (Opcode) {
1782  case ISD::TokenFactor:
1783    assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
1784           N2.getValueType() == MVT::Other && "Invalid token factor!");
1785    break;
1786  case ISD::AND:
1787  case ISD::OR:
1788  case ISD::XOR:
1789  case ISD::UDIV:
1790  case ISD::UREM:
1791  case ISD::MULHU:
1792  case ISD::MULHS:
1793    assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
1794    // fall through
1795  case ISD::ADD:
1796  case ISD::SUB:
1797  case ISD::MUL:
1798  case ISD::SDIV:
1799  case ISD::SREM:
1800    assert(MVT::isInteger(N1.getValueType()) && "Should use F* for FP ops");
1801    // fall through.
1802  case ISD::FADD:
1803  case ISD::FSUB:
1804  case ISD::FMUL:
1805  case ISD::FDIV:
1806  case ISD::FREM:
1807    assert(N1.getValueType() == N2.getValueType() &&
1808           N1.getValueType() == VT && "Binary operator types must match!");
1809    break;
1810  case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
1811    assert(N1.getValueType() == VT &&
1812           MVT::isFloatingPoint(N1.getValueType()) &&
1813           MVT::isFloatingPoint(N2.getValueType()) &&
1814           "Invalid FCOPYSIGN!");
1815    break;
1816  case ISD::SHL:
1817  case ISD::SRA:
1818  case ISD::SRL:
1819  case ISD::ROTL:
1820  case ISD::ROTR:
1821    assert(VT == N1.getValueType() &&
1822           "Shift operators return type must be the same as their first arg");
1823    assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
1824           VT != MVT::i1 && "Shifts only work on integers");
1825    break;
1826  case ISD::FP_ROUND_INREG: {
1827    MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1828    assert(VT == N1.getValueType() && "Not an inreg round!");
1829    assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
1830           "Cannot FP_ROUND_INREG integer types");
1831    assert(EVT <= VT && "Not rounding down!");
1832    break;
1833  }
1834  case ISD::AssertSext:
1835  case ISD::AssertZext:
1836  case ISD::SIGN_EXTEND_INREG: {
1837    MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1838    assert(VT == N1.getValueType() && "Not an inreg extend!");
1839    assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
1840           "Cannot *_EXTEND_INREG FP types");
1841    assert(EVT <= VT && "Not extending!");
1842  }
1843
1844  default: break;
1845  }
1846#endif
1847
1848  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1849  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1850  if (N1C) {
1851    if (Opcode == ISD::SIGN_EXTEND_INREG) {
1852      int64_t Val = N1C->getValue();
1853      unsigned FromBits = MVT::getSizeInBits(cast<VTSDNode>(N2)->getVT());
1854      Val <<= 64-FromBits;
1855      Val >>= 64-FromBits;
1856      return getConstant(Val, VT);
1857    }
1858
1859    if (N2C) {
1860      uint64_t C1 = N1C->getValue(), C2 = N2C->getValue();
1861      switch (Opcode) {
1862      case ISD::ADD: return getConstant(C1 + C2, VT);
1863      case ISD::SUB: return getConstant(C1 - C2, VT);
1864      case ISD::MUL: return getConstant(C1 * C2, VT);
1865      case ISD::UDIV:
1866        if (C2) return getConstant(C1 / C2, VT);
1867        break;
1868      case ISD::UREM :
1869        if (C2) return getConstant(C1 % C2, VT);
1870        break;
1871      case ISD::SDIV :
1872        if (C2) return getConstant(N1C->getSignExtended() /
1873                                   N2C->getSignExtended(), VT);
1874        break;
1875      case ISD::SREM :
1876        if (C2) return getConstant(N1C->getSignExtended() %
1877                                   N2C->getSignExtended(), VT);
1878        break;
1879      case ISD::AND  : return getConstant(C1 & C2, VT);
1880      case ISD::OR   : return getConstant(C1 | C2, VT);
1881      case ISD::XOR  : return getConstant(C1 ^ C2, VT);
1882      case ISD::SHL  : return getConstant(C1 << C2, VT);
1883      case ISD::SRL  : return getConstant(C1 >> C2, VT);
1884      case ISD::SRA  : return getConstant(N1C->getSignExtended() >>(int)C2, VT);
1885      case ISD::ROTL :
1886        return getConstant((C1 << C2) | (C1 >> (MVT::getSizeInBits(VT) - C2)),
1887                           VT);
1888      case ISD::ROTR :
1889        return getConstant((C1 >> C2) | (C1 << (MVT::getSizeInBits(VT) - C2)),
1890                           VT);
1891      default: break;
1892      }
1893    } else {      // Cannonicalize constant to RHS if commutative
1894      if (isCommutativeBinOp(Opcode)) {
1895        std::swap(N1C, N2C);
1896        std::swap(N1, N2);
1897      }
1898    }
1899  }
1900
1901  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
1902  ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
1903  if (N1CFP) {
1904    if (N2CFP) {
1905      double C1 = N1CFP->getValue(), C2 = N2CFP->getValue();
1906      switch (Opcode) {
1907      case ISD::FADD: return getConstantFP(C1 + C2, VT);
1908      case ISD::FSUB: return getConstantFP(C1 - C2, VT);
1909      case ISD::FMUL: return getConstantFP(C1 * C2, VT);
1910      case ISD::FDIV:
1911        if (C2) return getConstantFP(C1 / C2, VT);
1912        break;
1913      case ISD::FREM :
1914        if (C2) return getConstantFP(fmod(C1, C2), VT);
1915        break;
1916      case ISD::FCOPYSIGN: {
1917        union {
1918          double   F;
1919          uint64_t I;
1920        } u1;
1921        u1.F = C1;
1922        if (int64_t(DoubleToBits(C2)) < 0)  // Sign bit of RHS set?
1923          u1.I |= 1ULL << 63;      // Set the sign bit of the LHS.
1924        else
1925          u1.I &= (1ULL << 63)-1;  // Clear the sign bit of the LHS.
1926        return getConstantFP(u1.F, VT);
1927      }
1928      default: break;
1929      }
1930    } else {      // Cannonicalize constant to RHS if commutative
1931      if (isCommutativeBinOp(Opcode)) {
1932        std::swap(N1CFP, N2CFP);
1933        std::swap(N1, N2);
1934      }
1935    }
1936  }
1937
1938  // Canonicalize an UNDEF to the RHS, even over a constant.
1939  if (N1.getOpcode() == ISD::UNDEF) {
1940    if (isCommutativeBinOp(Opcode)) {
1941      std::swap(N1, N2);
1942    } else {
1943      switch (Opcode) {
1944      case ISD::FP_ROUND_INREG:
1945      case ISD::SIGN_EXTEND_INREG:
1946      case ISD::SUB:
1947      case ISD::FSUB:
1948      case ISD::FDIV:
1949      case ISD::FREM:
1950      case ISD::SRA:
1951        return N1;     // fold op(undef, arg2) -> undef
1952      case ISD::UDIV:
1953      case ISD::SDIV:
1954      case ISD::UREM:
1955      case ISD::SREM:
1956      case ISD::SRL:
1957      case ISD::SHL:
1958        if (!MVT::isVector(VT))
1959          return getConstant(0, VT);    // fold op(undef, arg2) -> 0
1960        // For vectors, we can't easily build an all zero vector, just return
1961        // the LHS.
1962        return N2;
1963      }
1964    }
1965  }
1966
1967  // Fold a bunch of operators when the RHS is undef.
1968  if (N2.getOpcode() == ISD::UNDEF) {
1969    switch (Opcode) {
1970    case ISD::ADD:
1971    case ISD::ADDC:
1972    case ISD::ADDE:
1973    case ISD::SUB:
1974    case ISD::FADD:
1975    case ISD::FSUB:
1976    case ISD::FMUL:
1977    case ISD::FDIV:
1978    case ISD::FREM:
1979    case ISD::UDIV:
1980    case ISD::SDIV:
1981    case ISD::UREM:
1982    case ISD::SREM:
1983    case ISD::XOR:
1984      return N2;       // fold op(arg1, undef) -> undef
1985    case ISD::MUL:
1986    case ISD::AND:
1987    case ISD::SRL:
1988    case ISD::SHL:
1989      if (!MVT::isVector(VT))
1990        return getConstant(0, VT);  // fold op(arg1, undef) -> 0
1991      // For vectors, we can't easily build an all zero vector, just return
1992      // the LHS.
1993      return N1;
1994    case ISD::OR:
1995      if (!MVT::isVector(VT))
1996        return getConstant(MVT::getIntVTBitMask(VT), VT);
1997      // For vectors, we can't easily build an all one vector, just return
1998      // the LHS.
1999      return N1;
2000    case ISD::SRA:
2001      return N1;
2002    }
2003  }
2004
2005  // Fold operations.
2006  switch (Opcode) {
2007  case ISD::TokenFactor:
2008    // Fold trivial token factors.
2009    if (N1.getOpcode() == ISD::EntryToken) return N2;
2010    if (N2.getOpcode() == ISD::EntryToken) return N1;
2011    break;
2012
2013  case ISD::AND:
2014    // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
2015    // worth handling here.
2016    if (N2C && N2C->getValue() == 0)
2017      return N2;
2018    break;
2019  case ISD::OR:
2020  case ISD::XOR:
2021    // (X ^| 0) -> X.  This commonly occurs when legalizing i64 values, so it's
2022    // worth handling here.
2023    if (N2C && N2C->getValue() == 0)
2024      return N1;
2025    break;
2026  case ISD::FP_ROUND_INREG:
2027    if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
2028    break;
2029  case ISD::SIGN_EXTEND_INREG: {
2030    MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
2031    if (EVT == VT) return N1;  // Not actually extending
2032    break;
2033  }
2034  case ISD::EXTRACT_VECTOR_ELT:
2035    assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
2036
2037    // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2038    // expanding copies of large vectors from registers.
2039    if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
2040        N1.getNumOperands() > 0) {
2041      unsigned Factor =
2042        MVT::getVectorNumElements(N1.getOperand(0).getValueType());
2043      return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2044                     N1.getOperand(N2C->getValue() / Factor),
2045                     getConstant(N2C->getValue() % Factor, N2.getValueType()));
2046    }
2047
2048    // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2049    // expanding large vector constants.
2050    if (N1.getOpcode() == ISD::BUILD_VECTOR)
2051      return N1.getOperand(N2C->getValue());
2052
2053    // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2054    // operations are lowered to scalars.
2055    if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
2056      if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
2057        if (IEC == N2C)
2058          return N1.getOperand(1);
2059        else
2060          return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2061      }
2062    break;
2063  case ISD::EXTRACT_ELEMENT:
2064    assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2065
2066    // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2067    // 64-bit integers into 32-bit parts.  Instead of building the extract of
2068    // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2069    if (N1.getOpcode() == ISD::BUILD_PAIR)
2070      return N1.getOperand(N2C->getValue());
2071
2072    // EXTRACT_ELEMENT of a constant int is also very common.
2073    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2074      unsigned Shift = MVT::getSizeInBits(VT) * N2C->getValue();
2075      return getConstant(C->getValue() >> Shift, VT);
2076    }
2077    break;
2078
2079  // FIXME: figure out how to safely handle things like
2080  // int foo(int x) { return 1 << (x & 255); }
2081  // int bar() { return foo(256); }
2082#if 0
2083  case ISD::SHL:
2084  case ISD::SRL:
2085  case ISD::SRA:
2086    if (N2.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2087        cast<VTSDNode>(N2.getOperand(1))->getVT() != MVT::i1)
2088      return getNode(Opcode, VT, N1, N2.getOperand(0));
2089    else if (N2.getOpcode() == ISD::AND)
2090      if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N2.getOperand(1))) {
2091        // If the and is only masking out bits that cannot effect the shift,
2092        // eliminate the and.
2093        unsigned NumBits = MVT::getSizeInBits(VT);
2094        if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
2095          return getNode(Opcode, VT, N1, N2.getOperand(0));
2096      }
2097    break;
2098#endif
2099  }
2100
2101  // Memoize this node if possible.
2102  SDNode *N;
2103  SDVTList VTs = getVTList(VT);
2104  if (VT != MVT::Flag) {
2105    SDOperand Ops[] = { N1, N2 };
2106    FoldingSetNodeID ID;
2107    AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2108    void *IP = 0;
2109    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2110      return SDOperand(E, 0);
2111    N = new BinarySDNode(Opcode, VTs, N1, N2);
2112    CSEMap.InsertNode(N, IP);
2113  } else {
2114    N = new BinarySDNode(Opcode, VTs, N1, N2);
2115  }
2116
2117  AllNodes.push_back(N);
2118  return SDOperand(N, 0);
2119}
2120
2121SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2122                                SDOperand N1, SDOperand N2, SDOperand N3) {
2123  // Perform various simplifications.
2124  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2125  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2126  switch (Opcode) {
2127  case ISD::SETCC: {
2128    // Use FoldSetCC to simplify SETCC's.
2129    SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2130    if (Simp.Val) return Simp;
2131    break;
2132  }
2133  case ISD::SELECT:
2134    if (N1C)
2135      if (N1C->getValue())
2136        return N2;             // select true, X, Y -> X
2137      else
2138        return N3;             // select false, X, Y -> Y
2139
2140    if (N2 == N3) return N2;   // select C, X, X -> X
2141    break;
2142  case ISD::BRCOND:
2143    if (N2C)
2144      if (N2C->getValue()) // Unconditional branch
2145        return getNode(ISD::BR, MVT::Other, N1, N3);
2146      else
2147        return N1;         // Never-taken branch
2148    break;
2149  case ISD::VECTOR_SHUFFLE:
2150    assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2151           MVT::isVector(VT) && MVT::isVector(N3.getValueType()) &&
2152           N3.getOpcode() == ISD::BUILD_VECTOR &&
2153           MVT::getVectorNumElements(VT) == N3.getNumOperands() &&
2154           "Illegal VECTOR_SHUFFLE node!");
2155    break;
2156  case ISD::BIT_CONVERT:
2157    // Fold bit_convert nodes from a type to themselves.
2158    if (N1.getValueType() == VT)
2159      return N1;
2160    break;
2161  }
2162
2163  // Memoize node if it doesn't produce a flag.
2164  SDNode *N;
2165  SDVTList VTs = getVTList(VT);
2166  if (VT != MVT::Flag) {
2167    SDOperand Ops[] = { N1, N2, N3 };
2168    FoldingSetNodeID ID;
2169    AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2170    void *IP = 0;
2171    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2172      return SDOperand(E, 0);
2173    N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2174    CSEMap.InsertNode(N, IP);
2175  } else {
2176    N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2177  }
2178  AllNodes.push_back(N);
2179  return SDOperand(N, 0);
2180}
2181
2182SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2183                                SDOperand N1, SDOperand N2, SDOperand N3,
2184                                SDOperand N4) {
2185  SDOperand Ops[] = { N1, N2, N3, N4 };
2186  return getNode(Opcode, VT, Ops, 4);
2187}
2188
2189SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2190                                SDOperand N1, SDOperand N2, SDOperand N3,
2191                                SDOperand N4, SDOperand N5) {
2192  SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2193  return getNode(Opcode, VT, Ops, 5);
2194}
2195
2196SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
2197                                SDOperand Chain, SDOperand Ptr,
2198                                const Value *SV, int SVOffset,
2199                                bool isVolatile, unsigned Alignment) {
2200  if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2201    const Type *Ty = 0;
2202    if (VT != MVT::iPTR) {
2203      Ty = MVT::getTypeForValueType(VT);
2204    } else if (SV) {
2205      const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2206      assert(PT && "Value for load must be a pointer");
2207      Ty = PT->getElementType();
2208    }
2209    assert(Ty && "Could not get type information for load");
2210    Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2211  }
2212  SDVTList VTs = getVTList(VT, MVT::Other);
2213  SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2214  SDOperand Ops[] = { Chain, Ptr, Undef };
2215  FoldingSetNodeID ID;
2216  AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2217  ID.AddInteger(ISD::UNINDEXED);
2218  ID.AddInteger(ISD::NON_EXTLOAD);
2219  ID.AddInteger(VT);
2220  ID.AddPointer(SV);
2221  ID.AddInteger(SVOffset);
2222  ID.AddInteger(Alignment);
2223  ID.AddInteger(isVolatile);
2224  void *IP = 0;
2225  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2226    return SDOperand(E, 0);
2227  SDNode *N = new LoadSDNode(Ops, VTs, ISD::UNINDEXED,
2228                             ISD::NON_EXTLOAD, VT, SV, SVOffset, Alignment,
2229                             isVolatile);
2230  CSEMap.InsertNode(N, IP);
2231  AllNodes.push_back(N);
2232  return SDOperand(N, 0);
2233}
2234
2235SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT::ValueType VT,
2236                                   SDOperand Chain, SDOperand Ptr,
2237                                   const Value *SV,
2238                                   int SVOffset, MVT::ValueType EVT,
2239                                   bool isVolatile, unsigned Alignment) {
2240  // If they are asking for an extending load from/to the same thing, return a
2241  // normal load.
2242  if (VT == EVT)
2243    ExtType = ISD::NON_EXTLOAD;
2244
2245  if (MVT::isVector(VT))
2246    assert(EVT == MVT::getVectorElementType(VT) && "Invalid vector extload!");
2247  else
2248    assert(EVT < VT && "Should only be an extending load, not truncating!");
2249  assert((ExtType == ISD::EXTLOAD || MVT::isInteger(VT)) &&
2250         "Cannot sign/zero extend a FP/Vector load!");
2251  assert(MVT::isInteger(VT) == MVT::isInteger(EVT) &&
2252         "Cannot convert from FP to Int or Int -> FP!");
2253
2254  if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2255    const Type *Ty = 0;
2256    if (VT != MVT::iPTR) {
2257      Ty = MVT::getTypeForValueType(VT);
2258    } else if (SV) {
2259      const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2260      assert(PT && "Value for load must be a pointer");
2261      Ty = PT->getElementType();
2262    }
2263    assert(Ty && "Could not get type information for load");
2264    Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2265  }
2266  SDVTList VTs = getVTList(VT, MVT::Other);
2267  SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2268  SDOperand Ops[] = { Chain, Ptr, Undef };
2269  FoldingSetNodeID ID;
2270  AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2271  ID.AddInteger(ISD::UNINDEXED);
2272  ID.AddInteger(ExtType);
2273  ID.AddInteger(EVT);
2274  ID.AddPointer(SV);
2275  ID.AddInteger(SVOffset);
2276  ID.AddInteger(Alignment);
2277  ID.AddInteger(isVolatile);
2278  void *IP = 0;
2279  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2280    return SDOperand(E, 0);
2281  SDNode *N = new LoadSDNode(Ops, VTs, ISD::UNINDEXED, ExtType, EVT,
2282                             SV, SVOffset, Alignment, isVolatile);
2283  CSEMap.InsertNode(N, IP);
2284  AllNodes.push_back(N);
2285  return SDOperand(N, 0);
2286}
2287
2288SDOperand
2289SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
2290                             SDOperand Offset, ISD::MemIndexedMode AM) {
2291  LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
2292  assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
2293         "Load is already a indexed load!");
2294  MVT::ValueType VT = OrigLoad.getValueType();
2295  SDVTList VTs = getVTList(VT, Base.getValueType(), MVT::Other);
2296  SDOperand Ops[] = { LD->getChain(), Base, Offset };
2297  FoldingSetNodeID ID;
2298  AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2299  ID.AddInteger(AM);
2300  ID.AddInteger(LD->getExtensionType());
2301  ID.AddInteger(LD->getLoadedVT());
2302  ID.AddPointer(LD->getSrcValue());
2303  ID.AddInteger(LD->getSrcValueOffset());
2304  ID.AddInteger(LD->getAlignment());
2305  ID.AddInteger(LD->isVolatile());
2306  void *IP = 0;
2307  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2308    return SDOperand(E, 0);
2309  SDNode *N = new LoadSDNode(Ops, VTs, AM,
2310                             LD->getExtensionType(), LD->getLoadedVT(),
2311                             LD->getSrcValue(), LD->getSrcValueOffset(),
2312                             LD->getAlignment(), LD->isVolatile());
2313  CSEMap.InsertNode(N, IP);
2314  AllNodes.push_back(N);
2315  return SDOperand(N, 0);
2316}
2317
2318SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
2319                                 SDOperand Ptr, const Value *SV, int SVOffset,
2320                                 bool isVolatile, unsigned Alignment) {
2321  MVT::ValueType VT = Val.getValueType();
2322
2323  if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2324    const Type *Ty = 0;
2325    if (VT != MVT::iPTR) {
2326      Ty = MVT::getTypeForValueType(VT);
2327    } else if (SV) {
2328      const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2329      assert(PT && "Value for store must be a pointer");
2330      Ty = PT->getElementType();
2331    }
2332    assert(Ty && "Could not get type information for store");
2333    Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2334  }
2335  SDVTList VTs = getVTList(MVT::Other);
2336  SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2337  SDOperand Ops[] = { Chain, Val, Ptr, Undef };
2338  FoldingSetNodeID ID;
2339  AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2340  ID.AddInteger(ISD::UNINDEXED);
2341  ID.AddInteger(false);
2342  ID.AddInteger(VT);
2343  ID.AddPointer(SV);
2344  ID.AddInteger(SVOffset);
2345  ID.AddInteger(Alignment);
2346  ID.AddInteger(isVolatile);
2347  void *IP = 0;
2348  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2349    return SDOperand(E, 0);
2350  SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
2351                              VT, SV, SVOffset, Alignment, isVolatile);
2352  CSEMap.InsertNode(N, IP);
2353  AllNodes.push_back(N);
2354  return SDOperand(N, 0);
2355}
2356
2357SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
2358                                      SDOperand Ptr, const Value *SV,
2359                                      int SVOffset, MVT::ValueType SVT,
2360                                      bool isVolatile, unsigned Alignment) {
2361  MVT::ValueType VT = Val.getValueType();
2362  bool isTrunc = VT != SVT;
2363
2364  assert(VT > SVT && "Not a truncation?");
2365  assert(MVT::isInteger(VT) == MVT::isInteger(SVT) &&
2366         "Can't do FP-INT conversion!");
2367
2368  if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2369    const Type *Ty = 0;
2370    if (VT != MVT::iPTR) {
2371      Ty = MVT::getTypeForValueType(VT);
2372    } else if (SV) {
2373      const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2374      assert(PT && "Value for store must be a pointer");
2375      Ty = PT->getElementType();
2376    }
2377    assert(Ty && "Could not get type information for store");
2378    Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2379  }
2380  SDVTList VTs = getVTList(MVT::Other);
2381  SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2382  SDOperand Ops[] = { Chain, Val, Ptr, Undef };
2383  FoldingSetNodeID ID;
2384  AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2385  ID.AddInteger(ISD::UNINDEXED);
2386  ID.AddInteger(isTrunc);
2387  ID.AddInteger(SVT);
2388  ID.AddPointer(SV);
2389  ID.AddInteger(SVOffset);
2390  ID.AddInteger(Alignment);
2391  ID.AddInteger(isVolatile);
2392  void *IP = 0;
2393  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2394    return SDOperand(E, 0);
2395  SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, isTrunc,
2396                              SVT, SV, SVOffset, Alignment, isVolatile);
2397  CSEMap.InsertNode(N, IP);
2398  AllNodes.push_back(N);
2399  return SDOperand(N, 0);
2400}
2401
2402SDOperand
2403SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
2404                              SDOperand Offset, ISD::MemIndexedMode AM) {
2405  StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
2406  assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
2407         "Store is already a indexed store!");
2408  SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
2409  SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
2410  FoldingSetNodeID ID;
2411  AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2412  ID.AddInteger(AM);
2413  ID.AddInteger(ST->isTruncatingStore());
2414  ID.AddInteger(ST->getStoredVT());
2415  ID.AddPointer(ST->getSrcValue());
2416  ID.AddInteger(ST->getSrcValueOffset());
2417  ID.AddInteger(ST->getAlignment());
2418  ID.AddInteger(ST->isVolatile());
2419  void *IP = 0;
2420  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2421    return SDOperand(E, 0);
2422  SDNode *N = new StoreSDNode(Ops, VTs, AM,
2423                              ST->isTruncatingStore(), ST->getStoredVT(),
2424                              ST->getSrcValue(), ST->getSrcValueOffset(),
2425                              ST->getAlignment(), ST->isVolatile());
2426  CSEMap.InsertNode(N, IP);
2427  AllNodes.push_back(N);
2428  return SDOperand(N, 0);
2429}
2430
2431SDOperand SelectionDAG::getVAArg(MVT::ValueType VT,
2432                                 SDOperand Chain, SDOperand Ptr,
2433                                 SDOperand SV) {
2434  SDOperand Ops[] = { Chain, Ptr, SV };
2435  return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
2436}
2437
2438SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2439                                const SDOperand *Ops, unsigned NumOps) {
2440  switch (NumOps) {
2441  case 0: return getNode(Opcode, VT);
2442  case 1: return getNode(Opcode, VT, Ops[0]);
2443  case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
2444  case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
2445  default: break;
2446  }
2447
2448  switch (Opcode) {
2449  default: break;
2450  case ISD::SELECT_CC: {
2451    assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
2452    assert(Ops[0].getValueType() == Ops[1].getValueType() &&
2453           "LHS and RHS of condition must have same type!");
2454    assert(Ops[2].getValueType() == Ops[3].getValueType() &&
2455           "True and False arms of SelectCC must have same type!");
2456    assert(Ops[2].getValueType() == VT &&
2457           "select_cc node must be of same type as true and false value!");
2458    break;
2459  }
2460  case ISD::BR_CC: {
2461    assert(NumOps == 5 && "BR_CC takes 5 operands!");
2462    assert(Ops[2].getValueType() == Ops[3].getValueType() &&
2463           "LHS/RHS of comparison should match types!");
2464    break;
2465  }
2466  }
2467
2468  // Memoize nodes.
2469  SDNode *N;
2470  SDVTList VTs = getVTList(VT);
2471  if (VT != MVT::Flag) {
2472    FoldingSetNodeID ID;
2473    AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
2474    void *IP = 0;
2475    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2476      return SDOperand(E, 0);
2477    N = new SDNode(Opcode, VTs, Ops, NumOps);
2478    CSEMap.InsertNode(N, IP);
2479  } else {
2480    N = new SDNode(Opcode, VTs, Ops, NumOps);
2481  }
2482  AllNodes.push_back(N);
2483  return SDOperand(N, 0);
2484}
2485
2486SDOperand SelectionDAG::getNode(unsigned Opcode,
2487                                std::vector<MVT::ValueType> &ResultTys,
2488                                const SDOperand *Ops, unsigned NumOps) {
2489  return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
2490                 Ops, NumOps);
2491}
2492
2493SDOperand SelectionDAG::getNode(unsigned Opcode,
2494                                const MVT::ValueType *VTs, unsigned NumVTs,
2495                                const SDOperand *Ops, unsigned NumOps) {
2496  if (NumVTs == 1)
2497    return getNode(Opcode, VTs[0], Ops, NumOps);
2498  return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
2499}
2500
2501SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2502                                const SDOperand *Ops, unsigned NumOps) {
2503  if (VTList.NumVTs == 1)
2504    return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
2505
2506  switch (Opcode) {
2507  // FIXME: figure out how to safely handle things like
2508  // int foo(int x) { return 1 << (x & 255); }
2509  // int bar() { return foo(256); }
2510#if 0
2511  case ISD::SRA_PARTS:
2512  case ISD::SRL_PARTS:
2513  case ISD::SHL_PARTS:
2514    if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2515        cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
2516      return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
2517    else if (N3.getOpcode() == ISD::AND)
2518      if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
2519        // If the and is only masking out bits that cannot effect the shift,
2520        // eliminate the and.
2521        unsigned NumBits = MVT::getSizeInBits(VT)*2;
2522        if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
2523          return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
2524      }
2525    break;
2526#endif
2527  }
2528
2529  // Memoize the node unless it returns a flag.
2530  SDNode *N;
2531  if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
2532    FoldingSetNodeID ID;
2533    AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
2534    void *IP = 0;
2535    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2536      return SDOperand(E, 0);
2537    if (NumOps == 1)
2538      N = new UnarySDNode(Opcode, VTList, Ops[0]);
2539    else if (NumOps == 2)
2540      N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
2541    else if (NumOps == 3)
2542      N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
2543    else
2544      N = new SDNode(Opcode, VTList, Ops, NumOps);
2545    CSEMap.InsertNode(N, IP);
2546  } else {
2547    if (NumOps == 1)
2548      N = new UnarySDNode(Opcode, VTList, Ops[0]);
2549    else if (NumOps == 2)
2550      N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
2551    else if (NumOps == 3)
2552      N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
2553    else
2554      N = new SDNode(Opcode, VTList, Ops, NumOps);
2555  }
2556  AllNodes.push_back(N);
2557  return SDOperand(N, 0);
2558}
2559
2560SDVTList SelectionDAG::getVTList(MVT::ValueType VT) {
2561  if (!MVT::isExtendedVT(VT))
2562    return makeVTList(SDNode::getValueTypeList(VT), 1);
2563
2564  for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2565       E = VTList.end(); I != E; ++I) {
2566    if (I->size() == 1 && (*I)[0] == VT)
2567      return makeVTList(&(*I)[0], 1);
2568  }
2569  std::vector<MVT::ValueType> V;
2570  V.push_back(VT);
2571  VTList.push_front(V);
2572  return makeVTList(&(*VTList.begin())[0], 1);
2573}
2574
2575SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2) {
2576  for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2577       E = VTList.end(); I != E; ++I) {
2578    if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2)
2579      return makeVTList(&(*I)[0], 2);
2580  }
2581  std::vector<MVT::ValueType> V;
2582  V.push_back(VT1);
2583  V.push_back(VT2);
2584  VTList.push_front(V);
2585  return makeVTList(&(*VTList.begin())[0], 2);
2586}
2587SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2,
2588                                 MVT::ValueType VT3) {
2589  for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2590       E = VTList.end(); I != E; ++I) {
2591    if (I->size() == 3 && (*I)[0] == VT1 && (*I)[1] == VT2 &&
2592        (*I)[2] == VT3)
2593      return makeVTList(&(*I)[0], 3);
2594  }
2595  std::vector<MVT::ValueType> V;
2596  V.push_back(VT1);
2597  V.push_back(VT2);
2598  V.push_back(VT3);
2599  VTList.push_front(V);
2600  return makeVTList(&(*VTList.begin())[0], 3);
2601}
2602
2603SDVTList SelectionDAG::getVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
2604  switch (NumVTs) {
2605    case 0: assert(0 && "Cannot have nodes without results!");
2606    case 1: return getVTList(VTs[0]);
2607    case 2: return getVTList(VTs[0], VTs[1]);
2608    case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
2609    default: break;
2610  }
2611
2612  for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2613       E = VTList.end(); I != E; ++I) {
2614    if (I->size() != NumVTs || VTs[0] != (*I)[0] || VTs[1] != (*I)[1]) continue;
2615
2616    bool NoMatch = false;
2617    for (unsigned i = 2; i != NumVTs; ++i)
2618      if (VTs[i] != (*I)[i]) {
2619        NoMatch = true;
2620        break;
2621      }
2622    if (!NoMatch)
2623      return makeVTList(&*I->begin(), NumVTs);
2624  }
2625
2626  VTList.push_front(std::vector<MVT::ValueType>(VTs, VTs+NumVTs));
2627  return makeVTList(&*VTList.begin()->begin(), NumVTs);
2628}
2629
2630
2631/// UpdateNodeOperands - *Mutate* the specified node in-place to have the
2632/// specified operands.  If the resultant node already exists in the DAG,
2633/// this does not modify the specified node, instead it returns the node that
2634/// already exists.  If the resultant node does not exist in the DAG, the
2635/// input node is returned.  As a degenerate case, if you specify the same
2636/// input operands as the node already has, the input node is returned.
2637SDOperand SelectionDAG::
2638UpdateNodeOperands(SDOperand InN, SDOperand Op) {
2639  SDNode *N = InN.Val;
2640  assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
2641
2642  // Check to see if there is no change.
2643  if (Op == N->getOperand(0)) return InN;
2644
2645  // See if the modified node already exists.
2646  void *InsertPos = 0;
2647  if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
2648    return SDOperand(Existing, InN.ResNo);
2649
2650  // Nope it doesn't.  Remove the node from it's current place in the maps.
2651  if (InsertPos)
2652    RemoveNodeFromCSEMaps(N);
2653
2654  // Now we update the operands.
2655  N->OperandList[0].Val->removeUser(N);
2656  Op.Val->addUser(N);
2657  N->OperandList[0] = Op;
2658
2659  // If this gets put into a CSE map, add it.
2660  if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2661  return InN;
2662}
2663
2664SDOperand SelectionDAG::
2665UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
2666  SDNode *N = InN.Val;
2667  assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
2668
2669  // Check to see if there is no change.
2670  if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
2671    return InN;   // No operands changed, just return the input node.
2672
2673  // See if the modified node already exists.
2674  void *InsertPos = 0;
2675  if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
2676    return SDOperand(Existing, InN.ResNo);
2677
2678  // Nope it doesn't.  Remove the node from it's current place in the maps.
2679  if (InsertPos)
2680    RemoveNodeFromCSEMaps(N);
2681
2682  // Now we update the operands.
2683  if (N->OperandList[0] != Op1) {
2684    N->OperandList[0].Val->removeUser(N);
2685    Op1.Val->addUser(N);
2686    N->OperandList[0] = Op1;
2687  }
2688  if (N->OperandList[1] != Op2) {
2689    N->OperandList[1].Val->removeUser(N);
2690    Op2.Val->addUser(N);
2691    N->OperandList[1] = Op2;
2692  }
2693
2694  // If this gets put into a CSE map, add it.
2695  if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2696  return InN;
2697}
2698
2699SDOperand SelectionDAG::
2700UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
2701  SDOperand Ops[] = { Op1, Op2, Op3 };
2702  return UpdateNodeOperands(N, Ops, 3);
2703}
2704
2705SDOperand SelectionDAG::
2706UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
2707                   SDOperand Op3, SDOperand Op4) {
2708  SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
2709  return UpdateNodeOperands(N, Ops, 4);
2710}
2711
2712SDOperand SelectionDAG::
2713UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
2714                   SDOperand Op3, SDOperand Op4, SDOperand Op5) {
2715  SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
2716  return UpdateNodeOperands(N, Ops, 5);
2717}
2718
2719
2720SDOperand SelectionDAG::
2721UpdateNodeOperands(SDOperand InN, SDOperand *Ops, unsigned NumOps) {
2722  SDNode *N = InN.Val;
2723  assert(N->getNumOperands() == NumOps &&
2724         "Update with wrong number of operands");
2725
2726  // Check to see if there is no change.
2727  bool AnyChange = false;
2728  for (unsigned i = 0; i != NumOps; ++i) {
2729    if (Ops[i] != N->getOperand(i)) {
2730      AnyChange = true;
2731      break;
2732    }
2733  }
2734
2735  // No operands changed, just return the input node.
2736  if (!AnyChange) return InN;
2737
2738  // See if the modified node already exists.
2739  void *InsertPos = 0;
2740  if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
2741    return SDOperand(Existing, InN.ResNo);
2742
2743  // Nope it doesn't.  Remove the node from it's current place in the maps.
2744  if (InsertPos)
2745    RemoveNodeFromCSEMaps(N);
2746
2747  // Now we update the operands.
2748  for (unsigned i = 0; i != NumOps; ++i) {
2749    if (N->OperandList[i] != Ops[i]) {
2750      N->OperandList[i].Val->removeUser(N);
2751      Ops[i].Val->addUser(N);
2752      N->OperandList[i] = Ops[i];
2753    }
2754  }
2755
2756  // If this gets put into a CSE map, add it.
2757  if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2758  return InN;
2759}
2760
2761
2762/// MorphNodeTo - This frees the operands of the current node, resets the
2763/// opcode, types, and operands to the specified value.  This should only be
2764/// used by the SelectionDAG class.
2765void SDNode::MorphNodeTo(unsigned Opc, SDVTList L,
2766                         const SDOperand *Ops, unsigned NumOps) {
2767  NodeType = Opc;
2768  ValueList = L.VTs;
2769  NumValues = L.NumVTs;
2770
2771  // Clear the operands list, updating used nodes to remove this from their
2772  // use list.
2773  for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
2774    I->Val->removeUser(this);
2775
2776  // If NumOps is larger than the # of operands we currently have, reallocate
2777  // the operand list.
2778  if (NumOps > NumOperands) {
2779    if (OperandsNeedDelete)
2780      delete [] OperandList;
2781    OperandList = new SDOperand[NumOps];
2782    OperandsNeedDelete = true;
2783  }
2784
2785  // Assign the new operands.
2786  NumOperands = NumOps;
2787
2788  for (unsigned i = 0, e = NumOps; i != e; ++i) {
2789    OperandList[i] = Ops[i];
2790    SDNode *N = OperandList[i].Val;
2791    N->Uses.push_back(this);
2792  }
2793}
2794
2795/// SelectNodeTo - These are used for target selectors to *mutate* the
2796/// specified node to have the specified return type, Target opcode, and
2797/// operands.  Note that target opcodes are stored as
2798/// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
2799///
2800/// Note that SelectNodeTo returns the resultant node.  If there is already a
2801/// node of the specified opcode and operands, it returns that node instead of
2802/// the current one.
2803SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2804                                   MVT::ValueType VT) {
2805  SDVTList VTs = getVTList(VT);
2806  FoldingSetNodeID ID;
2807  AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, 0, 0);
2808  void *IP = 0;
2809  if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2810    return ON;
2811
2812  RemoveNodeFromCSEMaps(N);
2813
2814  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, 0, 0);
2815
2816  CSEMap.InsertNode(N, IP);
2817  return N;
2818}
2819
2820SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2821                                   MVT::ValueType VT, SDOperand Op1) {
2822  // If an identical node already exists, use it.
2823  SDVTList VTs = getVTList(VT);
2824  SDOperand Ops[] = { Op1 };
2825
2826  FoldingSetNodeID ID;
2827  AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
2828  void *IP = 0;
2829  if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2830    return ON;
2831
2832  RemoveNodeFromCSEMaps(N);
2833  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
2834  CSEMap.InsertNode(N, IP);
2835  return N;
2836}
2837
2838SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2839                                   MVT::ValueType VT, SDOperand Op1,
2840                                   SDOperand Op2) {
2841  // If an identical node already exists, use it.
2842  SDVTList VTs = getVTList(VT);
2843  SDOperand Ops[] = { Op1, Op2 };
2844
2845  FoldingSetNodeID ID;
2846  AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
2847  void *IP = 0;
2848  if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2849    return ON;
2850
2851  RemoveNodeFromCSEMaps(N);
2852
2853  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
2854
2855  CSEMap.InsertNode(N, IP);   // Memoize the new node.
2856  return N;
2857}
2858
2859SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2860                                   MVT::ValueType VT, SDOperand Op1,
2861                                   SDOperand Op2, SDOperand Op3) {
2862  // If an identical node already exists, use it.
2863  SDVTList VTs = getVTList(VT);
2864  SDOperand Ops[] = { Op1, Op2, Op3 };
2865  FoldingSetNodeID ID;
2866  AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
2867  void *IP = 0;
2868  if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2869    return ON;
2870
2871  RemoveNodeFromCSEMaps(N);
2872
2873  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
2874
2875  CSEMap.InsertNode(N, IP);   // Memoize the new node.
2876  return N;
2877}
2878
2879SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2880                                   MVT::ValueType VT, const SDOperand *Ops,
2881                                   unsigned NumOps) {
2882  // If an identical node already exists, use it.
2883  SDVTList VTs = getVTList(VT);
2884  FoldingSetNodeID ID;
2885  AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
2886  void *IP = 0;
2887  if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2888    return ON;
2889
2890  RemoveNodeFromCSEMaps(N);
2891  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
2892
2893  CSEMap.InsertNode(N, IP);   // Memoize the new node.
2894  return N;
2895}
2896
2897SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2898                                   MVT::ValueType VT1, MVT::ValueType VT2,
2899                                   SDOperand Op1, SDOperand Op2) {
2900  SDVTList VTs = getVTList(VT1, VT2);
2901  FoldingSetNodeID ID;
2902  SDOperand Ops[] = { Op1, Op2 };
2903  AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
2904  void *IP = 0;
2905  if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2906    return ON;
2907
2908  RemoveNodeFromCSEMaps(N);
2909  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
2910  CSEMap.InsertNode(N, IP);   // Memoize the new node.
2911  return N;
2912}
2913
2914SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2915                                   MVT::ValueType VT1, MVT::ValueType VT2,
2916                                   SDOperand Op1, SDOperand Op2,
2917                                   SDOperand Op3) {
2918  // If an identical node already exists, use it.
2919  SDVTList VTs = getVTList(VT1, VT2);
2920  SDOperand Ops[] = { Op1, Op2, Op3 };
2921  FoldingSetNodeID ID;
2922  AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
2923  void *IP = 0;
2924  if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2925    return ON;
2926
2927  RemoveNodeFromCSEMaps(N);
2928
2929  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
2930  CSEMap.InsertNode(N, IP);   // Memoize the new node.
2931  return N;
2932}
2933
2934
2935/// getTargetNode - These are used for target selectors to create a new node
2936/// with specified return type(s), target opcode, and operands.
2937///
2938/// Note that getTargetNode returns the resultant node.  If there is already a
2939/// node of the specified opcode and operands, it returns that node instead of
2940/// the current one.
2941SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT) {
2942  return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
2943}
2944SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2945                                    SDOperand Op1) {
2946  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
2947}
2948SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2949                                    SDOperand Op1, SDOperand Op2) {
2950  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
2951}
2952SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2953                                    SDOperand Op1, SDOperand Op2,
2954                                    SDOperand Op3) {
2955  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
2956}
2957SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2958                                    const SDOperand *Ops, unsigned NumOps) {
2959  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val;
2960}
2961SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2962                                    MVT::ValueType VT2, SDOperand Op1) {
2963  const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
2964  return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op1, 1).Val;
2965}
2966SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2967                                    MVT::ValueType VT2, SDOperand Op1,
2968                                    SDOperand Op2) {
2969  const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
2970  SDOperand Ops[] = { Op1, Op2 };
2971  return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 2).Val;
2972}
2973SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2974                                    MVT::ValueType VT2, SDOperand Op1,
2975                                    SDOperand Op2, SDOperand Op3) {
2976  const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
2977  SDOperand Ops[] = { Op1, Op2, Op3 };
2978  return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 3).Val;
2979}
2980SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2981                                    MVT::ValueType VT2,
2982                                    const SDOperand *Ops, unsigned NumOps) {
2983  const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
2984  return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, NumOps).Val;
2985}
2986SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2987                                    MVT::ValueType VT2, MVT::ValueType VT3,
2988                                    SDOperand Op1, SDOperand Op2) {
2989  const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
2990  SDOperand Ops[] = { Op1, Op2 };
2991  return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 2).Val;
2992}
2993SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2994                                    MVT::ValueType VT2, MVT::ValueType VT3,
2995                                    SDOperand Op1, SDOperand Op2,
2996                                    SDOperand Op3) {
2997  const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
2998  SDOperand Ops[] = { Op1, Op2, Op3 };
2999  return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 3).Val;
3000}
3001SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3002                                    MVT::ValueType VT2, MVT::ValueType VT3,
3003                                    const SDOperand *Ops, unsigned NumOps) {
3004  const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3005  return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, NumOps).Val;
3006}
3007
3008/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3009/// This can cause recursive merging of nodes in the DAG.
3010///
3011/// This version assumes From/To have a single result value.
3012///
3013void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand ToN,
3014                                      std::vector<SDNode*> *Deleted) {
3015  SDNode *From = FromN.Val, *To = ToN.Val;
3016  assert(From->getNumValues() == 1 && To->getNumValues() == 1 &&
3017         "Cannot replace with this method!");
3018  assert(From != To && "Cannot replace uses of with self");
3019
3020  while (!From->use_empty()) {
3021    // Process users until they are all gone.
3022    SDNode *U = *From->use_begin();
3023
3024    // This node is about to morph, remove its old self from the CSE maps.
3025    RemoveNodeFromCSEMaps(U);
3026
3027    for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3028         I != E; ++I)
3029      if (I->Val == From) {
3030        From->removeUser(U);
3031        I->Val = To;
3032        To->addUser(U);
3033      }
3034
3035    // Now that we have modified U, add it back to the CSE maps.  If it already
3036    // exists there, recursively merge the results together.
3037    if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3038      ReplaceAllUsesWith(U, Existing, Deleted);
3039      // U is now dead.
3040      if (Deleted) Deleted->push_back(U);
3041      DeleteNodeNotInCSEMaps(U);
3042    }
3043  }
3044}
3045
3046/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3047/// This can cause recursive merging of nodes in the DAG.
3048///
3049/// This version assumes From/To have matching types and numbers of result
3050/// values.
3051///
3052void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
3053                                      std::vector<SDNode*> *Deleted) {
3054  assert(From != To && "Cannot replace uses of with self");
3055  assert(From->getNumValues() == To->getNumValues() &&
3056         "Cannot use this version of ReplaceAllUsesWith!");
3057  if (From->getNumValues() == 1) {  // If possible, use the faster version.
3058    ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0), Deleted);
3059    return;
3060  }
3061
3062  while (!From->use_empty()) {
3063    // Process users until they are all gone.
3064    SDNode *U = *From->use_begin();
3065
3066    // This node is about to morph, remove its old self from the CSE maps.
3067    RemoveNodeFromCSEMaps(U);
3068
3069    for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3070         I != E; ++I)
3071      if (I->Val == From) {
3072        From->removeUser(U);
3073        I->Val = To;
3074        To->addUser(U);
3075      }
3076
3077    // Now that we have modified U, add it back to the CSE maps.  If it already
3078    // exists there, recursively merge the results together.
3079    if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3080      ReplaceAllUsesWith(U, Existing, Deleted);
3081      // U is now dead.
3082      if (Deleted) Deleted->push_back(U);
3083      DeleteNodeNotInCSEMaps(U);
3084    }
3085  }
3086}
3087
3088/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3089/// This can cause recursive merging of nodes in the DAG.
3090///
3091/// This version can replace From with any result values.  To must match the
3092/// number and types of values returned by From.
3093void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
3094                                      const SDOperand *To,
3095                                      std::vector<SDNode*> *Deleted) {
3096  if (From->getNumValues() == 1 && To[0].Val->getNumValues() == 1) {
3097    // Degenerate case handled above.
3098    ReplaceAllUsesWith(SDOperand(From, 0), To[0], Deleted);
3099    return;
3100  }
3101
3102  while (!From->use_empty()) {
3103    // Process users until they are all gone.
3104    SDNode *U = *From->use_begin();
3105
3106    // This node is about to morph, remove its old self from the CSE maps.
3107    RemoveNodeFromCSEMaps(U);
3108
3109    for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3110         I != E; ++I)
3111      if (I->Val == From) {
3112        const SDOperand &ToOp = To[I->ResNo];
3113        From->removeUser(U);
3114        *I = ToOp;
3115        ToOp.Val->addUser(U);
3116      }
3117
3118    // Now that we have modified U, add it back to the CSE maps.  If it already
3119    // exists there, recursively merge the results together.
3120    if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3121      ReplaceAllUsesWith(U, Existing, Deleted);
3122      // U is now dead.
3123      if (Deleted) Deleted->push_back(U);
3124      DeleteNodeNotInCSEMaps(U);
3125    }
3126  }
3127}
3128
3129/// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
3130/// uses of other values produced by From.Val alone.  The Deleted vector is
3131/// handled the same was as for ReplaceAllUsesWith.
3132void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
3133                                             std::vector<SDNode*> &Deleted) {
3134  assert(From != To && "Cannot replace a value with itself");
3135  // Handle the simple, trivial, case efficiently.
3136  if (From.Val->getNumValues() == 1 && To.Val->getNumValues() == 1) {
3137    ReplaceAllUsesWith(From, To, &Deleted);
3138    return;
3139  }
3140
3141  // Get all of the users of From.Val.  We want these in a nice,
3142  // deterministically ordered and uniqued set, so we use a SmallSetVector.
3143  SmallSetVector<SDNode*, 16> Users(From.Val->use_begin(), From.Val->use_end());
3144
3145  while (!Users.empty()) {
3146    // We know that this user uses some value of From.  If it is the right
3147    // value, update it.
3148    SDNode *User = Users.back();
3149    Users.pop_back();
3150
3151    for (SDOperand *Op = User->OperandList,
3152         *E = User->OperandList+User->NumOperands; Op != E; ++Op) {
3153      if (*Op == From) {
3154        // Okay, we know this user needs to be updated.  Remove its old self
3155        // from the CSE maps.
3156        RemoveNodeFromCSEMaps(User);
3157
3158        // Update all operands that match "From".
3159        for (; Op != E; ++Op) {
3160          if (*Op == From) {
3161            From.Val->removeUser(User);
3162            *Op = To;
3163            To.Val->addUser(User);
3164          }
3165        }
3166
3167        // Now that we have modified User, add it back to the CSE maps.  If it
3168        // already exists there, recursively merge the results together.
3169        if (SDNode *Existing = AddNonLeafNodeToCSEMaps(User)) {
3170          unsigned NumDeleted = Deleted.size();
3171          ReplaceAllUsesWith(User, Existing, &Deleted);
3172
3173          // User is now dead.
3174          Deleted.push_back(User);
3175          DeleteNodeNotInCSEMaps(User);
3176
3177          // We have to be careful here, because ReplaceAllUsesWith could have
3178          // deleted a user of From, which means there may be dangling pointers
3179          // in the "Users" setvector.  Scan over the deleted node pointers and
3180          // remove them from the setvector.
3181          for (unsigned i = NumDeleted, e = Deleted.size(); i != e; ++i)
3182            Users.remove(Deleted[i]);
3183        }
3184        break;   // Exit the operand scanning loop.
3185      }
3186    }
3187  }
3188}
3189
3190
3191/// AssignNodeIds - Assign a unique node id for each node in the DAG based on
3192/// their allnodes order. It returns the maximum id.
3193unsigned SelectionDAG::AssignNodeIds() {
3194  unsigned Id = 0;
3195  for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I){
3196    SDNode *N = I;
3197    N->setNodeId(Id++);
3198  }
3199  return Id;
3200}
3201
3202/// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
3203/// based on their topological order. It returns the maximum id and a vector
3204/// of the SDNodes* in assigned order by reference.
3205unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
3206  unsigned DAGSize = AllNodes.size();
3207  std::vector<unsigned> InDegree(DAGSize);
3208  std::vector<SDNode*> Sources;
3209
3210  // Use a two pass approach to avoid using a std::map which is slow.
3211  unsigned Id = 0;
3212  for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
3213    SDNode *N = I;
3214    N->setNodeId(Id++);
3215    unsigned Degree = N->use_size();
3216    InDegree[N->getNodeId()] = Degree;
3217    if (Degree == 0)
3218      Sources.push_back(N);
3219  }
3220
3221  TopOrder.clear();
3222  while (!Sources.empty()) {
3223    SDNode *N = Sources.back();
3224    Sources.pop_back();
3225    TopOrder.push_back(N);
3226    for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
3227      SDNode *P = I->Val;
3228      unsigned Degree = --InDegree[P->getNodeId()];
3229      if (Degree == 0)
3230        Sources.push_back(P);
3231    }
3232  }
3233
3234  // Second pass, assign the actual topological order as node ids.
3235  Id = 0;
3236  for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
3237       TI != TE; ++TI)
3238    (*TI)->setNodeId(Id++);
3239
3240  return Id;
3241}
3242
3243
3244
3245//===----------------------------------------------------------------------===//
3246//                              SDNode Class
3247//===----------------------------------------------------------------------===//
3248
3249// Out-of-line virtual method to give class a home.
3250void SDNode::ANCHOR() {}
3251void UnarySDNode::ANCHOR() {}
3252void BinarySDNode::ANCHOR() {}
3253void TernarySDNode::ANCHOR() {}
3254void HandleSDNode::ANCHOR() {}
3255void StringSDNode::ANCHOR() {}
3256void ConstantSDNode::ANCHOR() {}
3257void ConstantFPSDNode::ANCHOR() {}
3258void GlobalAddressSDNode::ANCHOR() {}
3259void FrameIndexSDNode::ANCHOR() {}
3260void JumpTableSDNode::ANCHOR() {}
3261void ConstantPoolSDNode::ANCHOR() {}
3262void BasicBlockSDNode::ANCHOR() {}
3263void SrcValueSDNode::ANCHOR() {}
3264void RegisterSDNode::ANCHOR() {}
3265void ExternalSymbolSDNode::ANCHOR() {}
3266void CondCodeSDNode::ANCHOR() {}
3267void VTSDNode::ANCHOR() {}
3268void LoadSDNode::ANCHOR() {}
3269void StoreSDNode::ANCHOR() {}
3270
3271HandleSDNode::~HandleSDNode() {
3272  SDVTList VTs = { 0, 0 };
3273  MorphNodeTo(ISD::HANDLENODE, VTs, 0, 0);  // Drops operand uses.
3274}
3275
3276GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
3277                                         MVT::ValueType VT, int o)
3278  : SDNode(isa<GlobalVariable>(GA) &&
3279           cast<GlobalVariable>(GA)->isThreadLocal() ?
3280           // Thread Local
3281           (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
3282           // Non Thread Local
3283           (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
3284           getSDVTList(VT)), Offset(o) {
3285  TheGlobal = const_cast<GlobalValue*>(GA);
3286}
3287
3288/// Profile - Gather unique data for the node.
3289///
3290void SDNode::Profile(FoldingSetNodeID &ID) {
3291  AddNodeIDNode(ID, this);
3292}
3293
3294/// getValueTypeList - Return a pointer to the specified value type.
3295///
3296MVT::ValueType *SDNode::getValueTypeList(MVT::ValueType VT) {
3297  static MVT::ValueType VTs[MVT::LAST_VALUETYPE];
3298  VTs[VT] = VT;
3299  return &VTs[VT];
3300}
3301
3302/// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
3303/// indicated value.  This method ignores uses of other values defined by this
3304/// operation.
3305bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
3306  assert(Value < getNumValues() && "Bad value!");
3307
3308  // If there is only one value, this is easy.
3309  if (getNumValues() == 1)
3310    return use_size() == NUses;
3311  if (use_size() < NUses) return false;
3312
3313  SDOperand TheValue(const_cast<SDNode *>(this), Value);
3314
3315  SmallPtrSet<SDNode*, 32> UsersHandled;
3316
3317  for (SDNode::use_iterator UI = Uses.begin(), E = Uses.end(); UI != E; ++UI) {
3318    SDNode *User = *UI;
3319    if (User->getNumOperands() == 1 ||
3320        UsersHandled.insert(User))     // First time we've seen this?
3321      for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
3322        if (User->getOperand(i) == TheValue) {
3323          if (NUses == 0)
3324            return false;   // too many uses
3325          --NUses;
3326        }
3327  }
3328
3329  // Found exactly the right number of uses?
3330  return NUses == 0;
3331}
3332
3333
3334/// hasAnyUseOfValue - Return true if there are any use of the indicated
3335/// value. This method ignores uses of other values defined by this operation.
3336bool SDNode::hasAnyUseOfValue(unsigned Value) const {
3337  assert(Value < getNumValues() && "Bad value!");
3338
3339  if (use_size() == 0) return false;
3340
3341  SDOperand TheValue(const_cast<SDNode *>(this), Value);
3342
3343  SmallPtrSet<SDNode*, 32> UsersHandled;
3344
3345  for (SDNode::use_iterator UI = Uses.begin(), E = Uses.end(); UI != E; ++UI) {
3346    SDNode *User = *UI;
3347    if (User->getNumOperands() == 1 ||
3348        UsersHandled.insert(User))     // First time we've seen this?
3349      for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
3350        if (User->getOperand(i) == TheValue) {
3351          return true;
3352        }
3353  }
3354
3355  return false;
3356}
3357
3358
3359/// isOnlyUse - Return true if this node is the only use of N.
3360///
3361bool SDNode::isOnlyUse(SDNode *N) const {
3362  bool Seen = false;
3363  for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
3364    SDNode *User = *I;
3365    if (User == this)
3366      Seen = true;
3367    else
3368      return false;
3369  }
3370
3371  return Seen;
3372}
3373
3374/// isOperand - Return true if this node is an operand of N.
3375///
3376bool SDOperand::isOperand(SDNode *N) const {
3377  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
3378    if (*this == N->getOperand(i))
3379      return true;
3380  return false;
3381}
3382
3383bool SDNode::isOperand(SDNode *N) const {
3384  for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
3385    if (this == N->OperandList[i].Val)
3386      return true;
3387  return false;
3388}
3389
3390static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
3391                            SmallPtrSet<SDNode *, 32> &Visited) {
3392  if (found || !Visited.insert(N))
3393    return;
3394
3395  for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
3396    SDNode *Op = N->getOperand(i).Val;
3397    if (Op == P) {
3398      found = true;
3399      return;
3400    }
3401    findPredecessor(Op, P, found, Visited);
3402  }
3403}
3404
3405/// isPredecessor - Return true if this node is a predecessor of N. This node
3406/// is either an operand of N or it can be reached by recursively traversing
3407/// up the operands.
3408/// NOTE: this is an expensive method. Use it carefully.
3409bool SDNode::isPredecessor(SDNode *N) const {
3410  SmallPtrSet<SDNode *, 32> Visited;
3411  bool found = false;
3412  findPredecessor(N, this, found, Visited);
3413  return found;
3414}
3415
3416uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
3417  assert(Num < NumOperands && "Invalid child # of SDNode!");
3418  return cast<ConstantSDNode>(OperandList[Num])->getValue();
3419}
3420
3421std::string SDNode::getOperationName(const SelectionDAG *G) const {
3422  switch (getOpcode()) {
3423  default:
3424    if (getOpcode() < ISD::BUILTIN_OP_END)
3425      return "<<Unknown DAG Node>>";
3426    else {
3427      if (G) {
3428        if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
3429          if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
3430            return TII->getName(getOpcode()-ISD::BUILTIN_OP_END);
3431
3432        TargetLowering &TLI = G->getTargetLoweringInfo();
3433        const char *Name =
3434          TLI.getTargetNodeName(getOpcode());
3435        if (Name) return Name;
3436      }
3437
3438      return "<<Unknown Target Node>>";
3439    }
3440
3441  case ISD::PCMARKER:      return "PCMarker";
3442  case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
3443  case ISD::SRCVALUE:      return "SrcValue";
3444  case ISD::EntryToken:    return "EntryToken";
3445  case ISD::TokenFactor:   return "TokenFactor";
3446  case ISD::AssertSext:    return "AssertSext";
3447  case ISD::AssertZext:    return "AssertZext";
3448
3449  case ISD::STRING:        return "String";
3450  case ISD::BasicBlock:    return "BasicBlock";
3451  case ISD::VALUETYPE:     return "ValueType";
3452  case ISD::Register:      return "Register";
3453
3454  case ISD::Constant:      return "Constant";
3455  case ISD::ConstantFP:    return "ConstantFP";
3456  case ISD::GlobalAddress: return "GlobalAddress";
3457  case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
3458  case ISD::FrameIndex:    return "FrameIndex";
3459  case ISD::JumpTable:     return "JumpTable";
3460  case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
3461  case ISD::RETURNADDR: return "RETURNADDR";
3462  case ISD::FRAMEADDR: return "FRAMEADDR";
3463  case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
3464  case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
3465  case ISD::EHSELECTION: return "EHSELECTION";
3466  case ISD::EH_RETURN: return "EH_RETURN";
3467  case ISD::ConstantPool:  return "ConstantPool";
3468  case ISD::ExternalSymbol: return "ExternalSymbol";
3469  case ISD::INTRINSIC_WO_CHAIN: {
3470    unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
3471    return Intrinsic::getName((Intrinsic::ID)IID);
3472  }
3473  case ISD::INTRINSIC_VOID:
3474  case ISD::INTRINSIC_W_CHAIN: {
3475    unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
3476    return Intrinsic::getName((Intrinsic::ID)IID);
3477  }
3478
3479  case ISD::BUILD_VECTOR:   return "BUILD_VECTOR";
3480  case ISD::TargetConstant: return "TargetConstant";
3481  case ISD::TargetConstantFP:return "TargetConstantFP";
3482  case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
3483  case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
3484  case ISD::TargetFrameIndex: return "TargetFrameIndex";
3485  case ISD::TargetJumpTable:  return "TargetJumpTable";
3486  case ISD::TargetConstantPool:  return "TargetConstantPool";
3487  case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
3488
3489  case ISD::CopyToReg:     return "CopyToReg";
3490  case ISD::CopyFromReg:   return "CopyFromReg";
3491  case ISD::UNDEF:         return "undef";
3492  case ISD::MERGE_VALUES:  return "merge_values";
3493  case ISD::INLINEASM:     return "inlineasm";
3494  case ISD::LABEL:         return "label";
3495  case ISD::HANDLENODE:    return "handlenode";
3496  case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
3497  case ISD::CALL:          return "call";
3498
3499  // Unary operators
3500  case ISD::FABS:   return "fabs";
3501  case ISD::FNEG:   return "fneg";
3502  case ISD::FSQRT:  return "fsqrt";
3503  case ISD::FSIN:   return "fsin";
3504  case ISD::FCOS:   return "fcos";
3505  case ISD::FPOWI:  return "fpowi";
3506
3507  // Binary operators
3508  case ISD::ADD:    return "add";
3509  case ISD::SUB:    return "sub";
3510  case ISD::MUL:    return "mul";
3511  case ISD::MULHU:  return "mulhu";
3512  case ISD::MULHS:  return "mulhs";
3513  case ISD::SDIV:   return "sdiv";
3514  case ISD::UDIV:   return "udiv";
3515  case ISD::SREM:   return "srem";
3516  case ISD::UREM:   return "urem";
3517  case ISD::AND:    return "and";
3518  case ISD::OR:     return "or";
3519  case ISD::XOR:    return "xor";
3520  case ISD::SHL:    return "shl";
3521  case ISD::SRA:    return "sra";
3522  case ISD::SRL:    return "srl";
3523  case ISD::ROTL:   return "rotl";
3524  case ISD::ROTR:   return "rotr";
3525  case ISD::FADD:   return "fadd";
3526  case ISD::FSUB:   return "fsub";
3527  case ISD::FMUL:   return "fmul";
3528  case ISD::FDIV:   return "fdiv";
3529  case ISD::FREM:   return "frem";
3530  case ISD::FCOPYSIGN: return "fcopysign";
3531
3532  case ISD::SETCC:       return "setcc";
3533  case ISD::SELECT:      return "select";
3534  case ISD::SELECT_CC:   return "select_cc";
3535  case ISD::INSERT_VECTOR_ELT:   return "insert_vector_elt";
3536  case ISD::EXTRACT_VECTOR_ELT:  return "extract_vector_elt";
3537  case ISD::CONCAT_VECTORS:      return "concat_vectors";
3538  case ISD::EXTRACT_SUBVECTOR:   return "extract_subvector";
3539  case ISD::SCALAR_TO_VECTOR:    return "scalar_to_vector";
3540  case ISD::VECTOR_SHUFFLE:      return "vector_shuffle";
3541  case ISD::CARRY_FALSE:         return "carry_false";
3542  case ISD::ADDC:        return "addc";
3543  case ISD::ADDE:        return "adde";
3544  case ISD::SUBC:        return "subc";
3545  case ISD::SUBE:        return "sube";
3546  case ISD::SHL_PARTS:   return "shl_parts";
3547  case ISD::SRA_PARTS:   return "sra_parts";
3548  case ISD::SRL_PARTS:   return "srl_parts";
3549
3550  case ISD::EXTRACT_SUBREG:     return "extract_subreg";
3551  case ISD::INSERT_SUBREG:      return "insert_subreg";
3552
3553  // Conversion operators.
3554  case ISD::SIGN_EXTEND: return "sign_extend";
3555  case ISD::ZERO_EXTEND: return "zero_extend";
3556  case ISD::ANY_EXTEND:  return "any_extend";
3557  case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
3558  case ISD::TRUNCATE:    return "truncate";
3559  case ISD::FP_ROUND:    return "fp_round";
3560  case ISD::FP_ROUND_INREG: return "fp_round_inreg";
3561  case ISD::FP_EXTEND:   return "fp_extend";
3562
3563  case ISD::SINT_TO_FP:  return "sint_to_fp";
3564  case ISD::UINT_TO_FP:  return "uint_to_fp";
3565  case ISD::FP_TO_SINT:  return "fp_to_sint";
3566  case ISD::FP_TO_UINT:  return "fp_to_uint";
3567  case ISD::BIT_CONVERT: return "bit_convert";
3568
3569    // Control flow instructions
3570  case ISD::BR:      return "br";
3571  case ISD::BRIND:   return "brind";
3572  case ISD::BR_JT:   return "br_jt";
3573  case ISD::BRCOND:  return "brcond";
3574  case ISD::BR_CC:   return "br_cc";
3575  case ISD::RET:     return "ret";
3576  case ISD::CALLSEQ_START:  return "callseq_start";
3577  case ISD::CALLSEQ_END:    return "callseq_end";
3578
3579    // Other operators
3580  case ISD::LOAD:               return "load";
3581  case ISD::STORE:              return "store";
3582  case ISD::VAARG:              return "vaarg";
3583  case ISD::VACOPY:             return "vacopy";
3584  case ISD::VAEND:              return "vaend";
3585  case ISD::VASTART:            return "vastart";
3586  case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
3587  case ISD::EXTRACT_ELEMENT:    return "extract_element";
3588  case ISD::BUILD_PAIR:         return "build_pair";
3589  case ISD::STACKSAVE:          return "stacksave";
3590  case ISD::STACKRESTORE:       return "stackrestore";
3591
3592  // Block memory operations.
3593  case ISD::MEMSET:  return "memset";
3594  case ISD::MEMCPY:  return "memcpy";
3595  case ISD::MEMMOVE: return "memmove";
3596
3597  // Bit manipulation
3598  case ISD::BSWAP:   return "bswap";
3599  case ISD::CTPOP:   return "ctpop";
3600  case ISD::CTTZ:    return "cttz";
3601  case ISD::CTLZ:    return "ctlz";
3602
3603  // Debug info
3604  case ISD::LOCATION: return "location";
3605  case ISD::DEBUG_LOC: return "debug_loc";
3606
3607  // Trampolines
3608  case ISD::ADJUST_TRAMP: return "adjust_tramp";
3609  case ISD::TRAMPOLINE:   return "trampoline";
3610
3611  case ISD::CONDCODE:
3612    switch (cast<CondCodeSDNode>(this)->get()) {
3613    default: assert(0 && "Unknown setcc condition!");
3614    case ISD::SETOEQ:  return "setoeq";
3615    case ISD::SETOGT:  return "setogt";
3616    case ISD::SETOGE:  return "setoge";
3617    case ISD::SETOLT:  return "setolt";
3618    case ISD::SETOLE:  return "setole";
3619    case ISD::SETONE:  return "setone";
3620
3621    case ISD::SETO:    return "seto";
3622    case ISD::SETUO:   return "setuo";
3623    case ISD::SETUEQ:  return "setue";
3624    case ISD::SETUGT:  return "setugt";
3625    case ISD::SETUGE:  return "setuge";
3626    case ISD::SETULT:  return "setult";
3627    case ISD::SETULE:  return "setule";
3628    case ISD::SETUNE:  return "setune";
3629
3630    case ISD::SETEQ:   return "seteq";
3631    case ISD::SETGT:   return "setgt";
3632    case ISD::SETGE:   return "setge";
3633    case ISD::SETLT:   return "setlt";
3634    case ISD::SETLE:   return "setle";
3635    case ISD::SETNE:   return "setne";
3636    }
3637  }
3638}
3639
3640const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
3641  switch (AM) {
3642  default:
3643    return "";
3644  case ISD::PRE_INC:
3645    return "<pre-inc>";
3646  case ISD::PRE_DEC:
3647    return "<pre-dec>";
3648  case ISD::POST_INC:
3649    return "<post-inc>";
3650  case ISD::POST_DEC:
3651    return "<post-dec>";
3652  }
3653}
3654
3655void SDNode::dump() const { dump(0); }
3656void SDNode::dump(const SelectionDAG *G) const {
3657  cerr << (void*)this << ": ";
3658
3659  for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
3660    if (i) cerr << ",";
3661    if (getValueType(i) == MVT::Other)
3662      cerr << "ch";
3663    else
3664      cerr << MVT::getValueTypeString(getValueType(i));
3665  }
3666  cerr << " = " << getOperationName(G);
3667
3668  cerr << " ";
3669  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3670    if (i) cerr << ", ";
3671    cerr << (void*)getOperand(i).Val;
3672    if (unsigned RN = getOperand(i).ResNo)
3673      cerr << ":" << RN;
3674  }
3675
3676  if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
3677    cerr << "<" << CSDN->getValue() << ">";
3678  } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
3679    cerr << "<" << CSDN->getValue() << ">";
3680  } else if (const GlobalAddressSDNode *GADN =
3681             dyn_cast<GlobalAddressSDNode>(this)) {
3682    int offset = GADN->getOffset();
3683    cerr << "<";
3684    WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
3685    if (offset > 0)
3686      cerr << " + " << offset;
3687    else
3688      cerr << " " << offset;
3689  } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
3690    cerr << "<" << FIDN->getIndex() << ">";
3691  } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
3692    cerr << "<" << JTDN->getIndex() << ">";
3693  } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
3694    int offset = CP->getOffset();
3695    if (CP->isMachineConstantPoolEntry())
3696      cerr << "<" << *CP->getMachineCPVal() << ">";
3697    else
3698      cerr << "<" << *CP->getConstVal() << ">";
3699    if (offset > 0)
3700      cerr << " + " << offset;
3701    else
3702      cerr << " " << offset;
3703  } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
3704    cerr << "<";
3705    const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
3706    if (LBB)
3707      cerr << LBB->getName() << " ";
3708    cerr << (const void*)BBDN->getBasicBlock() << ">";
3709  } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
3710    if (G && R->getReg() && MRegisterInfo::isPhysicalRegister(R->getReg())) {
3711      cerr << " " <<G->getTarget().getRegisterInfo()->getName(R->getReg());
3712    } else {
3713      cerr << " #" << R->getReg();
3714    }
3715  } else if (const ExternalSymbolSDNode *ES =
3716             dyn_cast<ExternalSymbolSDNode>(this)) {
3717    cerr << "'" << ES->getSymbol() << "'";
3718  } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
3719    if (M->getValue())
3720      cerr << "<" << M->getValue() << ":" << M->getOffset() << ">";
3721    else
3722      cerr << "<null:" << M->getOffset() << ">";
3723  } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
3724    cerr << ":" << MVT::getValueTypeString(N->getVT());
3725  } else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
3726    bool doExt = true;
3727    switch (LD->getExtensionType()) {
3728    default: doExt = false; break;
3729    case ISD::EXTLOAD:
3730      cerr << " <anyext ";
3731      break;
3732    case ISD::SEXTLOAD:
3733      cerr << " <sext ";
3734      break;
3735    case ISD::ZEXTLOAD:
3736      cerr << " <zext ";
3737      break;
3738    }
3739    if (doExt)
3740      cerr << MVT::getValueTypeString(LD->getLoadedVT()) << ">";
3741
3742    const char *AM = getIndexedModeName(LD->getAddressingMode());
3743    if (*AM)
3744      cerr << " " << AM;
3745  } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
3746    if (ST->isTruncatingStore())
3747      cerr << " <trunc "
3748           << MVT::getValueTypeString(ST->getStoredVT()) << ">";
3749
3750    const char *AM = getIndexedModeName(ST->getAddressingMode());
3751    if (*AM)
3752      cerr << " " << AM;
3753  }
3754}
3755
3756static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
3757  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
3758    if (N->getOperand(i).Val->hasOneUse())
3759      DumpNodes(N->getOperand(i).Val, indent+2, G);
3760    else
3761      cerr << "\n" << std::string(indent+2, ' ')
3762           << (void*)N->getOperand(i).Val << ": <multiple use>";
3763
3764
3765  cerr << "\n" << std::string(indent, ' ');
3766  N->dump(G);
3767}
3768
3769void SelectionDAG::dump() const {
3770  cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
3771  std::vector<const SDNode*> Nodes;
3772  for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
3773       I != E; ++I)
3774    Nodes.push_back(I);
3775
3776  std::sort(Nodes.begin(), Nodes.end());
3777
3778  for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
3779    if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
3780      DumpNodes(Nodes[i], 2, this);
3781  }
3782
3783  if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
3784
3785  cerr << "\n\n";
3786}
3787
3788const Type *ConstantPoolSDNode::getType() const {
3789  if (isMachineConstantPoolEntry())
3790    return Val.MachineCPVal->getType();
3791  return Val.ConstVal->getType();
3792}
3793