Added support for machine specific constantpool values. These are useful for
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAG.cpp
1 //===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements the SelectionDAG class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "llvm/Constants.h"
16 #include "llvm/GlobalValue.h"
17 #include "llvm/Intrinsics.h"
18 #include "llvm/Assembly/Writer.h"
19 #include "llvm/CodeGen/MachineBasicBlock.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/Support/MathExtras.h"
22 #include "llvm/Target/MRegisterInfo.h"
23 #include "llvm/Target/TargetLowering.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/ADT/SetVector.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include <iostream>
30 #include <set>
31 #include <cmath>
32 #include <algorithm>
33 using namespace llvm;
34
35 /// makeVTList - Return an instance of the SDVTList struct initialized with the
36 /// specified members.
37 static SDVTList makeVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
38   SDVTList Res = {VTs, NumVTs};
39   return Res;
40 }
41
42 // isInvertibleForFree - Return true if there is no cost to emitting the logical
43 // inverse of this node.
44 static bool isInvertibleForFree(SDOperand N) {
45   if (isa<ConstantSDNode>(N.Val)) return true;
46   if (N.Val->getOpcode() == ISD::SETCC && N.Val->hasOneUse())
47     return true;
48   return false;
49 }
50
51 //===----------------------------------------------------------------------===//
52 //                              ConstantFPSDNode Class
53 //===----------------------------------------------------------------------===//
54
55 /// isExactlyValue - We don't rely on operator== working on double values, as
56 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
57 /// As such, this method can be used to do an exact bit-for-bit comparison of
58 /// two floating point values.
59 bool ConstantFPSDNode::isExactlyValue(double V) const {
60   return DoubleToBits(V) == DoubleToBits(Value);
61 }
62
63 //===----------------------------------------------------------------------===//
64 //                              ISD Namespace
65 //===----------------------------------------------------------------------===//
66
67 /// isBuildVectorAllOnes - Return true if the specified node is a
68 /// BUILD_VECTOR where all of the elements are ~0 or undef.
69 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
70   // Look through a bit convert.
71   if (N->getOpcode() == ISD::BIT_CONVERT)
72     N = N->getOperand(0).Val;
73   
74   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
75   
76   unsigned i = 0, e = N->getNumOperands();
77   
78   // Skip over all of the undef values.
79   while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
80     ++i;
81   
82   // Do not accept an all-undef vector.
83   if (i == e) return false;
84   
85   // Do not accept build_vectors that aren't all constants or which have non-~0
86   // elements.
87   SDOperand NotZero = N->getOperand(i);
88   if (isa<ConstantSDNode>(NotZero)) {
89     if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
90       return false;
91   } else if (isa<ConstantFPSDNode>(NotZero)) {
92     MVT::ValueType VT = NotZero.getValueType();
93     if (VT== MVT::f64) {
94       if (DoubleToBits(cast<ConstantFPSDNode>(NotZero)->getValue()) !=
95           (uint64_t)-1)
96         return false;
97     } else {
98       if (FloatToBits(cast<ConstantFPSDNode>(NotZero)->getValue()) !=
99           (uint32_t)-1)
100         return false;
101     }
102   } else
103     return false;
104   
105   // Okay, we have at least one ~0 value, check to see if the rest match or are
106   // undefs.
107   for (++i; i != e; ++i)
108     if (N->getOperand(i) != NotZero &&
109         N->getOperand(i).getOpcode() != ISD::UNDEF)
110       return false;
111   return true;
112 }
113
114
115 /// isBuildVectorAllZeros - Return true if the specified node is a
116 /// BUILD_VECTOR where all of the elements are 0 or undef.
117 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
118   // Look through a bit convert.
119   if (N->getOpcode() == ISD::BIT_CONVERT)
120     N = N->getOperand(0).Val;
121   
122   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
123   
124   unsigned i = 0, e = N->getNumOperands();
125   
126   // Skip over all of the undef values.
127   while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
128     ++i;
129   
130   // Do not accept an all-undef vector.
131   if (i == e) return false;
132   
133   // Do not accept build_vectors that aren't all constants or which have non-~0
134   // elements.
135   SDOperand Zero = N->getOperand(i);
136   if (isa<ConstantSDNode>(Zero)) {
137     if (!cast<ConstantSDNode>(Zero)->isNullValue())
138       return false;
139   } else if (isa<ConstantFPSDNode>(Zero)) {
140     if (!cast<ConstantFPSDNode>(Zero)->isExactlyValue(0.0))
141       return false;
142   } else
143     return false;
144   
145   // Okay, we have at least one ~0 value, check to see if the rest match or are
146   // undefs.
147   for (++i; i != e; ++i)
148     if (N->getOperand(i) != Zero &&
149         N->getOperand(i).getOpcode() != ISD::UNDEF)
150       return false;
151   return true;
152 }
153
154 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
155 /// when given the operation for (X op Y).
156 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
157   // To perform this operation, we just need to swap the L and G bits of the
158   // operation.
159   unsigned OldL = (Operation >> 2) & 1;
160   unsigned OldG = (Operation >> 1) & 1;
161   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
162                        (OldL << 1) |       // New G bit
163                        (OldG << 2));        // New L bit.
164 }
165
166 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
167 /// 'op' is a valid SetCC operation.
168 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
169   unsigned Operation = Op;
170   if (isInteger)
171     Operation ^= 7;   // Flip L, G, E bits, but not U.
172   else
173     Operation ^= 15;  // Flip all of the condition bits.
174   if (Operation > ISD::SETTRUE2)
175     Operation &= ~8;     // Don't let N and U bits get set.
176   return ISD::CondCode(Operation);
177 }
178
179
180 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
181 /// signed operation and 2 if the result is an unsigned comparison.  Return zero
182 /// if the operation does not depend on the sign of the input (setne and seteq).
183 static int isSignedOp(ISD::CondCode Opcode) {
184   switch (Opcode) {
185   default: assert(0 && "Illegal integer setcc operation!");
186   case ISD::SETEQ:
187   case ISD::SETNE: return 0;
188   case ISD::SETLT:
189   case ISD::SETLE:
190   case ISD::SETGT:
191   case ISD::SETGE: return 1;
192   case ISD::SETULT:
193   case ISD::SETULE:
194   case ISD::SETUGT:
195   case ISD::SETUGE: return 2;
196   }
197 }
198
199 /// getSetCCOrOperation - Return the result of a logical OR between different
200 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This function
201 /// returns SETCC_INVALID if it is not possible to represent the resultant
202 /// comparison.
203 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
204                                        bool isInteger) {
205   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
206     // Cannot fold a signed integer setcc with an unsigned integer setcc.
207     return ISD::SETCC_INVALID;
208
209   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
210
211   // If the N and U bits get set then the resultant comparison DOES suddenly
212   // care about orderedness, and is true when ordered.
213   if (Op > ISD::SETTRUE2)
214     Op &= ~16;     // Clear the U bit if the N bit is set.
215   
216   // Canonicalize illegal integer setcc's.
217   if (isInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
218     Op = ISD::SETNE;
219   
220   return ISD::CondCode(Op);
221 }
222
223 /// getSetCCAndOperation - Return the result of a logical AND between different
224 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
225 /// function returns zero if it is not possible to represent the resultant
226 /// comparison.
227 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
228                                         bool isInteger) {
229   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
230     // Cannot fold a signed setcc with an unsigned setcc.
231     return ISD::SETCC_INVALID;
232
233   // Combine all of the condition bits.
234   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
235   
236   // Canonicalize illegal integer setcc's.
237   if (isInteger) {
238     switch (Result) {
239     default: break;
240     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
241     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
242     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
243     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
244     }
245   }
246   
247   return Result;
248 }
249
250 const TargetMachine &SelectionDAG::getTarget() const {
251   return TLI.getTargetMachine();
252 }
253
254 //===----------------------------------------------------------------------===//
255 //                              SelectionDAG Class
256 //===----------------------------------------------------------------------===//
257
258 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
259 /// SelectionDAG.
260 void SelectionDAG::RemoveDeadNodes() {
261   // Create a dummy node (which is not added to allnodes), that adds a reference
262   // to the root node, preventing it from being deleted.
263   HandleSDNode Dummy(getRoot());
264
265   SmallVector<SDNode*, 128> DeadNodes;
266   
267   // Add all obviously-dead nodes to the DeadNodes worklist.
268   for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
269     if (I->use_empty())
270       DeadNodes.push_back(I);
271
272   // Process the worklist, deleting the nodes and adding their uses to the
273   // worklist.
274   while (!DeadNodes.empty()) {
275     SDNode *N = DeadNodes.back();
276     DeadNodes.pop_back();
277     
278     // Take the node out of the appropriate CSE map.
279     RemoveNodeFromCSEMaps(N);
280
281     // Next, brutally remove the operand list.  This is safe to do, as there are
282     // no cycles in the graph.
283     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
284       SDNode *Operand = I->Val;
285       Operand->removeUser(N);
286       
287       // Now that we removed this operand, see if there are no uses of it left.
288       if (Operand->use_empty())
289         DeadNodes.push_back(Operand);
290     }
291     delete[] N->OperandList;
292     N->OperandList = 0;
293     N->NumOperands = 0;
294     
295     // Finally, remove N itself.
296     AllNodes.erase(N);
297   }
298   
299   // If the root changed (e.g. it was a dead load, update the root).
300   setRoot(Dummy.getValue());
301 }
302
303 void SelectionDAG::DeleteNode(SDNode *N) {
304   assert(N->use_empty() && "Cannot delete a node that is not dead!");
305
306   // First take this out of the appropriate CSE map.
307   RemoveNodeFromCSEMaps(N);
308
309   // Finally, remove uses due to operands of this node, remove from the 
310   // AllNodes list, and delete the node.
311   DeleteNodeNotInCSEMaps(N);
312 }
313
314 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
315
316   // Remove it from the AllNodes list.
317   AllNodes.remove(N);
318     
319   // Drop all of the operands and decrement used nodes use counts.
320   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
321     I->Val->removeUser(N);
322   delete[] N->OperandList;
323   N->OperandList = 0;
324   N->NumOperands = 0;
325   
326   delete N;
327 }
328
329 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
330 /// correspond to it.  This is useful when we're about to delete or repurpose
331 /// the node.  We don't want future request for structurally identical nodes
332 /// to return N anymore.
333 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
334   bool Erased = false;
335   switch (N->getOpcode()) {
336   case ISD::HANDLENODE: return;  // noop.
337   case ISD::STRING:
338     Erased = StringNodes.erase(cast<StringSDNode>(N)->getValue());
339     break;
340   case ISD::CONDCODE:
341     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
342            "Cond code doesn't exist!");
343     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
344     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
345     break;
346   case ISD::ExternalSymbol:
347     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
348     break;
349   case ISD::TargetExternalSymbol:
350     Erased =
351       TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
352     break;
353   case ISD::VALUETYPE:
354     Erased = ValueTypeNodes[cast<VTSDNode>(N)->getVT()] != 0;
355     ValueTypeNodes[cast<VTSDNode>(N)->getVT()] = 0;
356     break;
357   default:
358     // Remove it from the CSE Map.
359     Erased = CSEMap.RemoveNode(N);
360     break;
361   }
362 #ifndef NDEBUG
363   // Verify that the node was actually in one of the CSE maps, unless it has a 
364   // flag result (which cannot be CSE'd) or is one of the special cases that are
365   // not subject to CSE.
366   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
367       !N->isTargetOpcode()) {
368     N->dump();
369     std::cerr << "\n";
370     assert(0 && "Node is not in map!");
371   }
372 #endif
373 }
374
375 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps.  It
376 /// has been taken out and modified in some way.  If the specified node already
377 /// exists in the CSE maps, do not modify the maps, but return the existing node
378 /// instead.  If it doesn't exist, add it and return null.
379 ///
380 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
381   assert(N->getNumOperands() && "This is a leaf node!");
382   if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
383     return 0;    // Never add these nodes.
384   
385   // Check that remaining values produced are not flags.
386   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
387     if (N->getValueType(i) == MVT::Flag)
388       return 0;   // Never CSE anything that produces a flag.
389   
390   SDNode *New = CSEMap.GetOrInsertNode(N);
391   if (New != N) return New;  // Node already existed.
392   return 0;
393 }
394
395 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
396 /// were replaced with those specified.  If this node is never memoized, 
397 /// return null, otherwise return a pointer to the slot it would take.  If a
398 /// node already exists with these operands, the slot will be non-null.
399 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
400                                            void *&InsertPos) {
401   if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
402     return 0;    // Never add these nodes.
403   
404   // Check that remaining values produced are not flags.
405   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
406     if (N->getValueType(i) == MVT::Flag)
407       return 0;   // Never CSE anything that produces a flag.
408   
409   SelectionDAGCSEMap::NodeID ID;
410   ID.SetOpcode(N->getOpcode());
411   ID.SetValueTypes(N->getVTList());
412   ID.SetOperands(Op);
413   return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
414 }
415
416 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
417 /// were replaced with those specified.  If this node is never memoized, 
418 /// return null, otherwise return a pointer to the slot it would take.  If a
419 /// node already exists with these operands, the slot will be non-null.
420 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 
421                                            SDOperand Op1, SDOperand Op2,
422                                            void *&InsertPos) {
423   if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
424     return 0;    // Never add these nodes.
425   
426   // Check that remaining values produced are not flags.
427   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
428     if (N->getValueType(i) == MVT::Flag)
429       return 0;   // Never CSE anything that produces a flag.
430                                               
431   SelectionDAGCSEMap::NodeID ID;
432   ID.SetOpcode(N->getOpcode());
433   ID.SetValueTypes(N->getVTList());
434   ID.SetOperands(Op1, Op2);
435   return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
436 }
437
438
439 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
440 /// were replaced with those specified.  If this node is never memoized, 
441 /// return null, otherwise return a pointer to the slot it would take.  If a
442 /// node already exists with these operands, the slot will be non-null.
443 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 
444                                            const SDOperand *Ops,unsigned NumOps,
445                                            void *&InsertPos) {
446   if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
447     return 0;    // Never add these nodes.
448   
449   // Check that remaining values produced are not flags.
450   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
451     if (N->getValueType(i) == MVT::Flag)
452       return 0;   // Never CSE anything that produces a flag.
453   
454   SelectionDAGCSEMap::NodeID ID;
455   ID.SetOpcode(N->getOpcode());
456   ID.SetValueTypes(N->getVTList());
457   ID.SetOperands(Ops, NumOps);
458   return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
459 }
460
461
462 SelectionDAG::~SelectionDAG() {
463   while (!AllNodes.empty()) {
464     SDNode *N = AllNodes.begin();
465     N->SetNextInBucket(0);
466     delete [] N->OperandList;
467     N->OperandList = 0;
468     N->NumOperands = 0;
469     AllNodes.pop_front();
470   }
471 }
472
473 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT::ValueType VT) {
474   if (Op.getValueType() == VT) return Op;
475   int64_t Imm = ~0ULL >> (64-MVT::getSizeInBits(VT));
476   return getNode(ISD::AND, Op.getValueType(), Op,
477                  getConstant(Imm, Op.getValueType()));
478 }
479
480 SDOperand SelectionDAG::getString(const std::string &Val) {
481   StringSDNode *&N = StringNodes[Val];
482   if (!N) {
483     N = new StringSDNode(Val);
484     AllNodes.push_back(N);
485   }
486   return SDOperand(N, 0);
487 }
488
489 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT::ValueType VT, bool isT) {
490   assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
491   assert(!MVT::isVector(VT) && "Cannot create Vector ConstantSDNodes!");
492   
493   // Mask out any bits that are not valid for this constant.
494   Val &= MVT::getIntVTBitMask(VT);
495
496   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
497   SelectionDAGCSEMap::NodeID ID(Opc, getVTList(VT));
498   ID.AddInteger(Val);
499   void *IP = 0;
500   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
501     return SDOperand(E, 0);
502   SDNode *N = new ConstantSDNode(isT, Val, VT);
503   CSEMap.InsertNode(N, IP);
504   AllNodes.push_back(N);
505   return SDOperand(N, 0);
506 }
507
508
509 SDOperand SelectionDAG::getConstantFP(double Val, MVT::ValueType VT,
510                                       bool isTarget) {
511   assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
512   if (VT == MVT::f32)
513     Val = (float)Val;  // Mask out extra precision.
514
515   // Do the map lookup using the actual bit pattern for the floating point
516   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
517   // we don't have issues with SNANs.
518   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
519   SelectionDAGCSEMap::NodeID ID(Opc, getVTList(VT));
520   ID.AddInteger(DoubleToBits(Val));
521   void *IP = 0;
522   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
523     return SDOperand(E, 0);
524   SDNode *N = new ConstantFPSDNode(isTarget, Val, VT);
525   CSEMap.InsertNode(N, IP);
526   AllNodes.push_back(N);
527   return SDOperand(N, 0);
528 }
529
530 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
531                                          MVT::ValueType VT, int Offset,
532                                          bool isTargetGA) {
533   unsigned Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
534   SelectionDAGCSEMap::NodeID ID(Opc, getVTList(VT));
535   ID.AddPointer(GV);
536   ID.AddInteger(Offset);
537   void *IP = 0;
538   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
539    return SDOperand(E, 0);
540   SDNode *N = new GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
541   CSEMap.InsertNode(N, IP);
542   AllNodes.push_back(N);
543   return SDOperand(N, 0);
544 }
545
546 SDOperand SelectionDAG::getFrameIndex(int FI, MVT::ValueType VT,
547                                       bool isTarget) {
548   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
549   SelectionDAGCSEMap::NodeID ID(Opc, getVTList(VT));
550   ID.AddInteger(FI);
551   void *IP = 0;
552   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
553     return SDOperand(E, 0);
554   SDNode *N = new FrameIndexSDNode(FI, VT, isTarget);
555   CSEMap.InsertNode(N, IP);
556   AllNodes.push_back(N);
557   return SDOperand(N, 0);
558 }
559
560 SDOperand SelectionDAG::getJumpTable(int JTI, MVT::ValueType VT, bool isTarget){
561   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
562   SelectionDAGCSEMap::NodeID ID(Opc, getVTList(VT));
563   ID.AddInteger(JTI);
564   void *IP = 0;
565   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
566     return SDOperand(E, 0);
567   SDNode *N = new JumpTableSDNode(JTI, VT, isTarget);
568   CSEMap.InsertNode(N, IP);
569   AllNodes.push_back(N);
570   return SDOperand(N, 0);
571 }
572
573 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT::ValueType VT,
574                                         unsigned Alignment, int Offset,
575                                         bool isTarget) {
576   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
577   SelectionDAGCSEMap::NodeID ID(Opc, getVTList(VT));
578   ID.AddInteger(Alignment);
579   ID.AddInteger(Offset);
580   ID.AddPointer(C);
581   void *IP = 0;
582   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
583     return SDOperand(E, 0);
584   SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
585   CSEMap.InsertNode(N, IP);
586   AllNodes.push_back(N);
587   return SDOperand(N, 0);
588 }
589
590
591 SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C,
592                                         MVT::ValueType VT,
593                                         unsigned Alignment, int Offset,
594                                         bool isTarget) {
595   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
596   SelectionDAGCSEMap::NodeID ID(Opc, getVTList(VT));
597   ID.AddInteger(Alignment);
598   ID.AddInteger(Offset);
599   C->AddSelectionDAGCSEId(&ID);
600   void *IP = 0;
601   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
602     return SDOperand(E, 0);
603   SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
604   CSEMap.InsertNode(N, IP);
605   AllNodes.push_back(N);
606   return SDOperand(N, 0);
607 }
608
609
610 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
611   SelectionDAGCSEMap::NodeID ID(ISD::BasicBlock, getVTList(MVT::Other));
612   ID.AddPointer(MBB);
613   void *IP = 0;
614   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
615     return SDOperand(E, 0);
616   SDNode *N = new BasicBlockSDNode(MBB);
617   CSEMap.InsertNode(N, IP);
618   AllNodes.push_back(N);
619   return SDOperand(N, 0);
620 }
621
622 SDOperand SelectionDAG::getValueType(MVT::ValueType VT) {
623   if ((unsigned)VT >= ValueTypeNodes.size())
624     ValueTypeNodes.resize(VT+1);
625   if (ValueTypeNodes[VT] == 0) {
626     ValueTypeNodes[VT] = new VTSDNode(VT);
627     AllNodes.push_back(ValueTypeNodes[VT]);
628   }
629
630   return SDOperand(ValueTypeNodes[VT], 0);
631 }
632
633 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT::ValueType VT) {
634   SDNode *&N = ExternalSymbols[Sym];
635   if (N) return SDOperand(N, 0);
636   N = new ExternalSymbolSDNode(false, Sym, VT);
637   AllNodes.push_back(N);
638   return SDOperand(N, 0);
639 }
640
641 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym,
642                                                 MVT::ValueType VT) {
643   SDNode *&N = TargetExternalSymbols[Sym];
644   if (N) return SDOperand(N, 0);
645   N = new ExternalSymbolSDNode(true, Sym, VT);
646   AllNodes.push_back(N);
647   return SDOperand(N, 0);
648 }
649
650 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
651   if ((unsigned)Cond >= CondCodeNodes.size())
652     CondCodeNodes.resize(Cond+1);
653   
654   if (CondCodeNodes[Cond] == 0) {
655     CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
656     AllNodes.push_back(CondCodeNodes[Cond]);
657   }
658   return SDOperand(CondCodeNodes[Cond], 0);
659 }
660
661 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT::ValueType VT) {
662   SelectionDAGCSEMap::NodeID ID(ISD::Register, getVTList(VT));
663   ID.AddInteger(RegNo);
664   void *IP = 0;
665   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
666     return SDOperand(E, 0);
667   SDNode *N = new RegisterSDNode(RegNo, VT);
668   CSEMap.InsertNode(N, IP);
669   AllNodes.push_back(N);
670   return SDOperand(N, 0);
671 }
672
673 SDOperand SelectionDAG::getSrcValue(const Value *V, int Offset) {
674   assert((!V || isa<PointerType>(V->getType())) &&
675          "SrcValue is not a pointer?");
676
677   SelectionDAGCSEMap::NodeID ID(ISD::SRCVALUE, getVTList(MVT::Other));
678   ID.AddPointer(V);
679   ID.AddInteger(Offset);
680   void *IP = 0;
681   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
682     return SDOperand(E, 0);
683   SDNode *N = new SrcValueSDNode(V, Offset);
684   CSEMap.InsertNode(N, IP);
685   AllNodes.push_back(N);
686   return SDOperand(N, 0);
687 }
688
689 SDOperand SelectionDAG::SimplifySetCC(MVT::ValueType VT, SDOperand N1,
690                                       SDOperand N2, ISD::CondCode Cond) {
691   // These setcc operations always fold.
692   switch (Cond) {
693   default: break;
694   case ISD::SETFALSE:
695   case ISD::SETFALSE2: return getConstant(0, VT);
696   case ISD::SETTRUE:
697   case ISD::SETTRUE2:  return getConstant(1, VT);
698     
699   case ISD::SETOEQ:
700   case ISD::SETOGT:
701   case ISD::SETOGE:
702   case ISD::SETOLT:
703   case ISD::SETOLE:
704   case ISD::SETONE:
705   case ISD::SETO:
706   case ISD::SETUO:
707   case ISD::SETUEQ:
708   case ISD::SETUNE:
709     assert(!MVT::isInteger(N1.getValueType()) && "Illegal setcc for integer!");
710     break;
711   }
712
713   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
714     uint64_t C2 = N2C->getValue();
715     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
716       uint64_t C1 = N1C->getValue();
717
718       // Sign extend the operands if required
719       if (ISD::isSignedIntSetCC(Cond)) {
720         C1 = N1C->getSignExtended();
721         C2 = N2C->getSignExtended();
722       }
723
724       switch (Cond) {
725       default: assert(0 && "Unknown integer setcc!");
726       case ISD::SETEQ:  return getConstant(C1 == C2, VT);
727       case ISD::SETNE:  return getConstant(C1 != C2, VT);
728       case ISD::SETULT: return getConstant(C1 <  C2, VT);
729       case ISD::SETUGT: return getConstant(C1 >  C2, VT);
730       case ISD::SETULE: return getConstant(C1 <= C2, VT);
731       case ISD::SETUGE: return getConstant(C1 >= C2, VT);
732       case ISD::SETLT:  return getConstant((int64_t)C1 <  (int64_t)C2, VT);
733       case ISD::SETGT:  return getConstant((int64_t)C1 >  (int64_t)C2, VT);
734       case ISD::SETLE:  return getConstant((int64_t)C1 <= (int64_t)C2, VT);
735       case ISD::SETGE:  return getConstant((int64_t)C1 >= (int64_t)C2, VT);
736       }
737     } else {
738       // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
739       if (N1.getOpcode() == ISD::ZERO_EXTEND) {
740         unsigned InSize = MVT::getSizeInBits(N1.getOperand(0).getValueType());
741
742         // If the comparison constant has bits in the upper part, the
743         // zero-extended value could never match.
744         if (C2 & (~0ULL << InSize)) {
745           unsigned VSize = MVT::getSizeInBits(N1.getValueType());
746           switch (Cond) {
747           case ISD::SETUGT:
748           case ISD::SETUGE:
749           case ISD::SETEQ: return getConstant(0, VT);
750           case ISD::SETULT:
751           case ISD::SETULE:
752           case ISD::SETNE: return getConstant(1, VT);
753           case ISD::SETGT:
754           case ISD::SETGE:
755             // True if the sign bit of C2 is set.
756             return getConstant((C2 & (1ULL << VSize)) != 0, VT);
757           case ISD::SETLT:
758           case ISD::SETLE:
759             // True if the sign bit of C2 isn't set.
760             return getConstant((C2 & (1ULL << VSize)) == 0, VT);
761           default:
762             break;
763           }
764         }
765
766         // Otherwise, we can perform the comparison with the low bits.
767         switch (Cond) {
768         case ISD::SETEQ:
769         case ISD::SETNE:
770         case ISD::SETUGT:
771         case ISD::SETUGE:
772         case ISD::SETULT:
773         case ISD::SETULE:
774           return getSetCC(VT, N1.getOperand(0),
775                           getConstant(C2, N1.getOperand(0).getValueType()),
776                           Cond);
777         default:
778           break;   // todo, be more careful with signed comparisons
779         }
780       } else if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG &&
781                  (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
782         MVT::ValueType ExtSrcTy = cast<VTSDNode>(N1.getOperand(1))->getVT();
783         unsigned ExtSrcTyBits = MVT::getSizeInBits(ExtSrcTy);
784         MVT::ValueType ExtDstTy = N1.getValueType();
785         unsigned ExtDstTyBits = MVT::getSizeInBits(ExtDstTy);
786
787         // If the extended part has any inconsistent bits, it cannot ever
788         // compare equal.  In other words, they have to be all ones or all
789         // zeros.
790         uint64_t ExtBits =
791           (~0ULL >> (64-ExtSrcTyBits)) & (~0ULL << (ExtDstTyBits-1));
792         if ((C2 & ExtBits) != 0 && (C2 & ExtBits) != ExtBits)
793           return getConstant(Cond == ISD::SETNE, VT);
794         
795         // Otherwise, make this a use of a zext.
796         return getSetCC(VT, getZeroExtendInReg(N1.getOperand(0), ExtSrcTy),
797                         getConstant(C2 & (~0ULL>>(64-ExtSrcTyBits)), ExtDstTy),
798                         Cond);
799       }
800
801       uint64_t MinVal, MaxVal;
802       unsigned OperandBitSize = MVT::getSizeInBits(N2C->getValueType(0));
803       if (ISD::isSignedIntSetCC(Cond)) {
804         MinVal = 1ULL << (OperandBitSize-1);
805         if (OperandBitSize != 1)   // Avoid X >> 64, which is undefined.
806           MaxVal = ~0ULL >> (65-OperandBitSize);
807         else
808           MaxVal = 0;
809       } else {
810         MinVal = 0;
811         MaxVal = ~0ULL >> (64-OperandBitSize);
812       }
813
814       // Canonicalize GE/LE comparisons to use GT/LT comparisons.
815       if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
816         if (C2 == MinVal) return getConstant(1, VT);   // X >= MIN --> true
817         --C2;                                          // X >= C1 --> X > (C1-1)
818         return getSetCC(VT, N1, getConstant(C2, N2.getValueType()),
819                         (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
820       }
821
822       if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
823         if (C2 == MaxVal) return getConstant(1, VT);   // X <= MAX --> true
824         ++C2;                                          // X <= C1 --> X < (C1+1)
825         return getSetCC(VT, N1, getConstant(C2, N2.getValueType()),
826                         (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
827       }
828
829       if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C2 == MinVal)
830         return getConstant(0, VT);      // X < MIN --> false
831
832       // Canonicalize setgt X, Min --> setne X, Min
833       if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C2 == MinVal)
834         return getSetCC(VT, N1, N2, ISD::SETNE);
835
836       // If we have setult X, 1, turn it into seteq X, 0
837       if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C2 == MinVal+1)
838         return getSetCC(VT, N1, getConstant(MinVal, N1.getValueType()),
839                         ISD::SETEQ);
840       // If we have setugt X, Max-1, turn it into seteq X, Max
841       else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C2 == MaxVal-1)
842         return getSetCC(VT, N1, getConstant(MaxVal, N1.getValueType()),
843                         ISD::SETEQ);
844
845       // If we have "setcc X, C1", check to see if we can shrink the immediate
846       // by changing cc.
847
848       // SETUGT X, SINTMAX  -> SETLT X, 0
849       if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
850           C2 == (~0ULL >> (65-OperandBitSize)))
851         return getSetCC(VT, N1, getConstant(0, N2.getValueType()), ISD::SETLT);
852
853       // FIXME: Implement the rest of these.
854
855
856       // Fold bit comparisons when we can.
857       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
858           VT == N1.getValueType() && N1.getOpcode() == ISD::AND)
859         if (ConstantSDNode *AndRHS =
860                     dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
861           if (Cond == ISD::SETNE && C2 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
862             // Perform the xform if the AND RHS is a single bit.
863             if ((AndRHS->getValue() & (AndRHS->getValue()-1)) == 0) {
864               return getNode(ISD::SRL, VT, N1,
865                              getConstant(Log2_64(AndRHS->getValue()),
866                                                    TLI.getShiftAmountTy()));
867             }
868           } else if (Cond == ISD::SETEQ && C2 == AndRHS->getValue()) {
869             // (X & 8) == 8  -->  (X & 8) >> 3
870             // Perform the xform if C2 is a single bit.
871             if ((C2 & (C2-1)) == 0) {
872               return getNode(ISD::SRL, VT, N1,
873                              getConstant(Log2_64(C2),TLI.getShiftAmountTy()));
874             }
875           }
876         }
877     }
878   } else if (isa<ConstantSDNode>(N1.Val)) {
879       // Ensure that the constant occurs on the RHS.
880     return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
881   }
882
883   if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val))
884     if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
885       double C1 = N1C->getValue(), C2 = N2C->getValue();
886
887       switch (Cond) {
888       default: break; // FIXME: Implement the rest of these!
889       case ISD::SETEQ:  return getConstant(C1 == C2, VT);
890       case ISD::SETNE:  return getConstant(C1 != C2, VT);
891       case ISD::SETLT:  return getConstant(C1 < C2, VT);
892       case ISD::SETGT:  return getConstant(C1 > C2, VT);
893       case ISD::SETLE:  return getConstant(C1 <= C2, VT);
894       case ISD::SETGE:  return getConstant(C1 >= C2, VT);
895       }
896     } else {
897       // Ensure that the constant occurs on the RHS.
898       return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
899     }
900
901   // Could not fold it.
902   return SDOperand();
903 }
904
905 /// getNode - Gets or creates the specified node.
906 ///
907 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
908   SelectionDAGCSEMap::NodeID ID(Opcode, getVTList(VT));
909   void *IP = 0;
910   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
911     return SDOperand(E, 0);
912   SDNode *N = new SDNode(Opcode, VT);
913   CSEMap.InsertNode(N, IP);
914   
915   AllNodes.push_back(N);
916   return SDOperand(N, 0);
917 }
918
919 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
920                                 SDOperand Operand) {
921   unsigned Tmp1;
922   // Constant fold unary operations with an integer constant operand.
923   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
924     uint64_t Val = C->getValue();
925     switch (Opcode) {
926     default: break;
927     case ISD::SIGN_EXTEND: return getConstant(C->getSignExtended(), VT);
928     case ISD::ANY_EXTEND:
929     case ISD::ZERO_EXTEND: return getConstant(Val, VT);
930     case ISD::TRUNCATE:    return getConstant(Val, VT);
931     case ISD::SINT_TO_FP:  return getConstantFP(C->getSignExtended(), VT);
932     case ISD::UINT_TO_FP:  return getConstantFP(C->getValue(), VT);
933     case ISD::BIT_CONVERT:
934       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
935         return getConstantFP(BitsToFloat(Val), VT);
936       else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
937         return getConstantFP(BitsToDouble(Val), VT);
938       break;
939     case ISD::BSWAP:
940       switch(VT) {
941       default: assert(0 && "Invalid bswap!"); break;
942       case MVT::i16: return getConstant(ByteSwap_16((unsigned short)Val), VT);
943       case MVT::i32: return getConstant(ByteSwap_32((unsigned)Val), VT);
944       case MVT::i64: return getConstant(ByteSwap_64(Val), VT);
945       }
946       break;
947     case ISD::CTPOP:
948       switch(VT) {
949       default: assert(0 && "Invalid ctpop!"); break;
950       case MVT::i1: return getConstant(Val != 0, VT);
951       case MVT::i8: 
952         Tmp1 = (unsigned)Val & 0xFF;
953         return getConstant(CountPopulation_32(Tmp1), VT);
954       case MVT::i16:
955         Tmp1 = (unsigned)Val & 0xFFFF;
956         return getConstant(CountPopulation_32(Tmp1), VT);
957       case MVT::i32:
958         return getConstant(CountPopulation_32((unsigned)Val), VT);
959       case MVT::i64:
960         return getConstant(CountPopulation_64(Val), VT);
961       }
962     case ISD::CTLZ:
963       switch(VT) {
964       default: assert(0 && "Invalid ctlz!"); break;
965       case MVT::i1: return getConstant(Val == 0, VT);
966       case MVT::i8: 
967         Tmp1 = (unsigned)Val & 0xFF;
968         return getConstant(CountLeadingZeros_32(Tmp1)-24, VT);
969       case MVT::i16:
970         Tmp1 = (unsigned)Val & 0xFFFF;
971         return getConstant(CountLeadingZeros_32(Tmp1)-16, VT);
972       case MVT::i32:
973         return getConstant(CountLeadingZeros_32((unsigned)Val), VT);
974       case MVT::i64:
975         return getConstant(CountLeadingZeros_64(Val), VT);
976       }
977     case ISD::CTTZ:
978       switch(VT) {
979       default: assert(0 && "Invalid cttz!"); break;
980       case MVT::i1: return getConstant(Val == 0, VT);
981       case MVT::i8: 
982         Tmp1 = (unsigned)Val | 0x100;
983         return getConstant(CountTrailingZeros_32(Tmp1), VT);
984       case MVT::i16:
985         Tmp1 = (unsigned)Val | 0x10000;
986         return getConstant(CountTrailingZeros_32(Tmp1), VT);
987       case MVT::i32:
988         return getConstant(CountTrailingZeros_32((unsigned)Val), VT);
989       case MVT::i64:
990         return getConstant(CountTrailingZeros_64(Val), VT);
991       }
992     }
993   }
994
995   // Constant fold unary operations with an floating point constant operand.
996   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val))
997     switch (Opcode) {
998     case ISD::FNEG:
999       return getConstantFP(-C->getValue(), VT);
1000     case ISD::FABS:
1001       return getConstantFP(fabs(C->getValue()), VT);
1002     case ISD::FP_ROUND:
1003     case ISD::FP_EXTEND:
1004       return getConstantFP(C->getValue(), VT);
1005     case ISD::FP_TO_SINT:
1006       return getConstant((int64_t)C->getValue(), VT);
1007     case ISD::FP_TO_UINT:
1008       return getConstant((uint64_t)C->getValue(), VT);
1009     case ISD::BIT_CONVERT:
1010       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
1011         return getConstant(FloatToBits(C->getValue()), VT);
1012       else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
1013         return getConstant(DoubleToBits(C->getValue()), VT);
1014       break;
1015     }
1016
1017   unsigned OpOpcode = Operand.Val->getOpcode();
1018   switch (Opcode) {
1019   case ISD::TokenFactor:
1020     return Operand;         // Factor of one node?  No factor.
1021   case ISD::SIGN_EXTEND:
1022     if (Operand.getValueType() == VT) return Operand;   // noop extension
1023     assert(Operand.getValueType() < VT && "Invalid sext node, dst < src!");
1024     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
1025       return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1026     break;
1027   case ISD::ZERO_EXTEND:
1028     if (Operand.getValueType() == VT) return Operand;   // noop extension
1029     assert(Operand.getValueType() < VT && "Invalid zext node, dst < src!");
1030     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
1031       return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
1032     break;
1033   case ISD::ANY_EXTEND:
1034     if (Operand.getValueType() == VT) return Operand;   // noop extension
1035     assert(Operand.getValueType() < VT && "Invalid anyext node, dst < src!");
1036     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
1037       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
1038       return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1039     break;
1040   case ISD::TRUNCATE:
1041     if (Operand.getValueType() == VT) return Operand;   // noop truncate
1042     assert(Operand.getValueType() > VT && "Invalid truncate node, src < dst!");
1043     if (OpOpcode == ISD::TRUNCATE)
1044       return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1045     else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
1046              OpOpcode == ISD::ANY_EXTEND) {
1047       // If the source is smaller than the dest, we still need an extend.
1048       if (Operand.Val->getOperand(0).getValueType() < VT)
1049         return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1050       else if (Operand.Val->getOperand(0).getValueType() > VT)
1051         return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1052       else
1053         return Operand.Val->getOperand(0);
1054     }
1055     break;
1056   case ISD::BIT_CONVERT:
1057     // Basic sanity checking.
1058     assert(MVT::getSizeInBits(VT) == MVT::getSizeInBits(Operand.getValueType())
1059            && "Cannot BIT_CONVERT between two different types!");
1060     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
1061     if (OpOpcode == ISD::BIT_CONVERT)  // bitconv(bitconv(x)) -> bitconv(x)
1062       return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
1063     if (OpOpcode == ISD::UNDEF)
1064       return getNode(ISD::UNDEF, VT);
1065     break;
1066   case ISD::SCALAR_TO_VECTOR:
1067     assert(MVT::isVector(VT) && !MVT::isVector(Operand.getValueType()) &&
1068            MVT::getVectorBaseType(VT) == Operand.getValueType() &&
1069            "Illegal SCALAR_TO_VECTOR node!");
1070     break;
1071   case ISD::FNEG:
1072     if (OpOpcode == ISD::FSUB)   // -(X-Y) -> (Y-X)
1073       return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
1074                      Operand.Val->getOperand(0));
1075     if (OpOpcode == ISD::FNEG)  // --X -> X
1076       return Operand.Val->getOperand(0);
1077     break;
1078   case ISD::FABS:
1079     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
1080       return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
1081     break;
1082   }
1083
1084   SDNode *N;
1085   SDVTList VTs = getVTList(VT);
1086   if (VT != MVT::Flag) { // Don't CSE flag producing nodes
1087     SelectionDAGCSEMap::NodeID ID(Opcode, VTs, Operand);
1088     void *IP = 0;
1089     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1090       return SDOperand(E, 0);
1091     N = new SDNode(Opcode, Operand);
1092     N->setValueTypes(VTs);
1093     CSEMap.InsertNode(N, IP);
1094   } else {
1095     N = new SDNode(Opcode, Operand);
1096     N->setValueTypes(VTs);
1097   }
1098   AllNodes.push_back(N);
1099   return SDOperand(N, 0);
1100 }
1101
1102
1103
1104 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1105                                 SDOperand N1, SDOperand N2) {
1106 #ifndef NDEBUG
1107   switch (Opcode) {
1108   case ISD::TokenFactor:
1109     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
1110            N2.getValueType() == MVT::Other && "Invalid token factor!");
1111     break;
1112   case ISD::AND:
1113   case ISD::OR:
1114   case ISD::XOR:
1115   case ISD::UDIV:
1116   case ISD::UREM:
1117   case ISD::MULHU:
1118   case ISD::MULHS:
1119     assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
1120     // fall through
1121   case ISD::ADD:
1122   case ISD::SUB:
1123   case ISD::MUL:
1124   case ISD::SDIV:
1125   case ISD::SREM:
1126     assert(MVT::isInteger(N1.getValueType()) && "Should use F* for FP ops");
1127     // fall through.
1128   case ISD::FADD:
1129   case ISD::FSUB:
1130   case ISD::FMUL:
1131   case ISD::FDIV:
1132   case ISD::FREM:
1133     assert(N1.getValueType() == N2.getValueType() &&
1134            N1.getValueType() == VT && "Binary operator types must match!");
1135     break;
1136   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
1137     assert(N1.getValueType() == VT &&
1138            MVT::isFloatingPoint(N1.getValueType()) && 
1139            MVT::isFloatingPoint(N2.getValueType()) &&
1140            "Invalid FCOPYSIGN!");
1141     break;
1142   case ISD::SHL:
1143   case ISD::SRA:
1144   case ISD::SRL:
1145   case ISD::ROTL:
1146   case ISD::ROTR:
1147     assert(VT == N1.getValueType() &&
1148            "Shift operators return type must be the same as their first arg");
1149     assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
1150            VT != MVT::i1 && "Shifts only work on integers");
1151     break;
1152   case ISD::FP_ROUND_INREG: {
1153     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1154     assert(VT == N1.getValueType() && "Not an inreg round!");
1155     assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
1156            "Cannot FP_ROUND_INREG integer types");
1157     assert(EVT <= VT && "Not rounding down!");
1158     break;
1159   }
1160   case ISD::AssertSext:
1161   case ISD::AssertZext:
1162   case ISD::SIGN_EXTEND_INREG: {
1163     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1164     assert(VT == N1.getValueType() && "Not an inreg extend!");
1165     assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
1166            "Cannot *_EXTEND_INREG FP types");
1167     assert(EVT <= VT && "Not extending!");
1168   }
1169
1170   default: break;
1171   }
1172 #endif
1173
1174   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1175   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1176   if (N1C) {
1177     if (Opcode == ISD::SIGN_EXTEND_INREG) {
1178       int64_t Val = N1C->getValue();
1179       unsigned FromBits = MVT::getSizeInBits(cast<VTSDNode>(N2)->getVT());
1180       Val <<= 64-FromBits;
1181       Val >>= 64-FromBits;
1182       return getConstant(Val, VT);
1183     }
1184     
1185     if (N2C) {
1186       uint64_t C1 = N1C->getValue(), C2 = N2C->getValue();
1187       switch (Opcode) {
1188       case ISD::ADD: return getConstant(C1 + C2, VT);
1189       case ISD::SUB: return getConstant(C1 - C2, VT);
1190       case ISD::MUL: return getConstant(C1 * C2, VT);
1191       case ISD::UDIV:
1192         if (C2) return getConstant(C1 / C2, VT);
1193         break;
1194       case ISD::UREM :
1195         if (C2) return getConstant(C1 % C2, VT);
1196         break;
1197       case ISD::SDIV :
1198         if (C2) return getConstant(N1C->getSignExtended() /
1199                                    N2C->getSignExtended(), VT);
1200         break;
1201       case ISD::SREM :
1202         if (C2) return getConstant(N1C->getSignExtended() %
1203                                    N2C->getSignExtended(), VT);
1204         break;
1205       case ISD::AND  : return getConstant(C1 & C2, VT);
1206       case ISD::OR   : return getConstant(C1 | C2, VT);
1207       case ISD::XOR  : return getConstant(C1 ^ C2, VT);
1208       case ISD::SHL  : return getConstant(C1 << C2, VT);
1209       case ISD::SRL  : return getConstant(C1 >> C2, VT);
1210       case ISD::SRA  : return getConstant(N1C->getSignExtended() >>(int)C2, VT);
1211       case ISD::ROTL : 
1212         return getConstant((C1 << C2) | (C1 >> (MVT::getSizeInBits(VT) - C2)),
1213                            VT);
1214       case ISD::ROTR : 
1215         return getConstant((C1 >> C2) | (C1 << (MVT::getSizeInBits(VT) - C2)), 
1216                            VT);
1217       default: break;
1218       }
1219     } else {      // Cannonicalize constant to RHS if commutative
1220       if (isCommutativeBinOp(Opcode)) {
1221         std::swap(N1C, N2C);
1222         std::swap(N1, N2);
1223       }
1224     }
1225   }
1226
1227   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
1228   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
1229   if (N1CFP) {
1230     if (N2CFP) {
1231       double C1 = N1CFP->getValue(), C2 = N2CFP->getValue();
1232       switch (Opcode) {
1233       case ISD::FADD: return getConstantFP(C1 + C2, VT);
1234       case ISD::FSUB: return getConstantFP(C1 - C2, VT);
1235       case ISD::FMUL: return getConstantFP(C1 * C2, VT);
1236       case ISD::FDIV:
1237         if (C2) return getConstantFP(C1 / C2, VT);
1238         break;
1239       case ISD::FREM :
1240         if (C2) return getConstantFP(fmod(C1, C2), VT);
1241         break;
1242       case ISD::FCOPYSIGN: {
1243         union {
1244           double   F;
1245           uint64_t I;
1246         } u1;
1247         union {
1248           double  F;
1249           int64_t I;
1250         } u2;
1251         u1.F = C1;
1252         u2.F = C2;
1253         if (u2.I < 0)  // Sign bit of RHS set?
1254           u1.I |= 1ULL << 63;      // Set the sign bit of the LHS.
1255         else 
1256           u1.I &= (1ULL << 63)-1;  // Clear the sign bit of the LHS.
1257         return getConstantFP(u1.F, VT);
1258       }
1259       default: break;
1260       }
1261     } else {      // Cannonicalize constant to RHS if commutative
1262       if (isCommutativeBinOp(Opcode)) {
1263         std::swap(N1CFP, N2CFP);
1264         std::swap(N1, N2);
1265       }
1266     }
1267   }
1268   
1269   // Canonicalize an UNDEF to the RHS, even over a constant.
1270   if (N1.getOpcode() == ISD::UNDEF) {
1271     if (isCommutativeBinOp(Opcode)) {
1272       std::swap(N1, N2);
1273     } else {
1274       switch (Opcode) {
1275       case ISD::FP_ROUND_INREG:
1276       case ISD::SIGN_EXTEND_INREG:
1277       case ISD::SUB:
1278       case ISD::FSUB:
1279       case ISD::FDIV:
1280       case ISD::FREM:
1281       case ISD::SRA:
1282         return N1;     // fold op(undef, arg2) -> undef
1283       case ISD::UDIV:
1284       case ISD::SDIV:
1285       case ISD::UREM:
1286       case ISD::SREM:
1287       case ISD::SRL:
1288       case ISD::SHL:
1289         return getConstant(0, VT);    // fold op(undef, arg2) -> 0
1290       }
1291     }
1292   }
1293   
1294   // Fold a bunch of operators when the RHS is undef. 
1295   if (N2.getOpcode() == ISD::UNDEF) {
1296     switch (Opcode) {
1297     case ISD::ADD:
1298     case ISD::SUB:
1299     case ISD::FADD:
1300     case ISD::FSUB:
1301     case ISD::FMUL:
1302     case ISD::FDIV:
1303     case ISD::FREM:
1304     case ISD::UDIV:
1305     case ISD::SDIV:
1306     case ISD::UREM:
1307     case ISD::SREM:
1308     case ISD::XOR:
1309       return N2;       // fold op(arg1, undef) -> undef
1310     case ISD::MUL: 
1311     case ISD::AND:
1312     case ISD::SRL:
1313     case ISD::SHL:
1314       return getConstant(0, VT);  // fold op(arg1, undef) -> 0
1315     case ISD::OR:
1316       return getConstant(MVT::getIntVTBitMask(VT), VT);
1317     case ISD::SRA:
1318       return N1;
1319     }
1320   }
1321
1322   // Finally, fold operations that do not require constants.
1323   switch (Opcode) {
1324   case ISD::FP_ROUND_INREG:
1325     if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
1326     break;
1327   case ISD::SIGN_EXTEND_INREG: {
1328     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1329     if (EVT == VT) return N1;  // Not actually extending
1330     break;
1331   }
1332
1333   // FIXME: figure out how to safely handle things like
1334   // int foo(int x) { return 1 << (x & 255); }
1335   // int bar() { return foo(256); }
1336 #if 0
1337   case ISD::SHL:
1338   case ISD::SRL:
1339   case ISD::SRA:
1340     if (N2.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1341         cast<VTSDNode>(N2.getOperand(1))->getVT() != MVT::i1)
1342       return getNode(Opcode, VT, N1, N2.getOperand(0));
1343     else if (N2.getOpcode() == ISD::AND)
1344       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N2.getOperand(1))) {
1345         // If the and is only masking out bits that cannot effect the shift,
1346         // eliminate the and.
1347         unsigned NumBits = MVT::getSizeInBits(VT);
1348         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
1349           return getNode(Opcode, VT, N1, N2.getOperand(0));
1350       }
1351     break;
1352 #endif
1353   }
1354
1355   // Memoize this node if possible.
1356   SDNode *N;
1357   SDVTList VTs = getVTList(VT);
1358   if (VT != MVT::Flag) {
1359     SelectionDAGCSEMap::NodeID ID(Opcode, VTs, N1, N2);
1360     void *IP = 0;
1361     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1362       return SDOperand(E, 0);
1363     N = new SDNode(Opcode, N1, N2);
1364     N->setValueTypes(VTs);
1365     CSEMap.InsertNode(N, IP);
1366   } else {
1367     N = new SDNode(Opcode, N1, N2);
1368     N->setValueTypes(VTs);
1369   }
1370
1371   AllNodes.push_back(N);
1372   return SDOperand(N, 0);
1373 }
1374
1375 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1376                                 SDOperand N1, SDOperand N2, SDOperand N3) {
1377   // Perform various simplifications.
1378   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1379   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1380   //ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
1381   switch (Opcode) {
1382   case ISD::SETCC: {
1383     // Use SimplifySetCC  to simplify SETCC's.
1384     SDOperand Simp = SimplifySetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
1385     if (Simp.Val) return Simp;
1386     break;
1387   }
1388   case ISD::SELECT:
1389     if (N1C)
1390       if (N1C->getValue())
1391         return N2;             // select true, X, Y -> X
1392       else
1393         return N3;             // select false, X, Y -> Y
1394
1395     if (N2 == N3) return N2;   // select C, X, X -> X
1396     break;
1397   case ISD::BRCOND:
1398     if (N2C)
1399       if (N2C->getValue()) // Unconditional branch
1400         return getNode(ISD::BR, MVT::Other, N1, N3);
1401       else
1402         return N1;         // Never-taken branch
1403     break;
1404   case ISD::VECTOR_SHUFFLE:
1405     assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1406            MVT::isVector(VT) && MVT::isVector(N3.getValueType()) &&
1407            N3.getOpcode() == ISD::BUILD_VECTOR &&
1408            MVT::getVectorNumElements(VT) == N3.getNumOperands() &&
1409            "Illegal VECTOR_SHUFFLE node!");
1410     break;
1411   }
1412
1413   // Memoize node if it doesn't produce a flag.
1414   SDNode *N;
1415   SDVTList VTs = getVTList(VT);
1416   if (VT != MVT::Flag) {
1417     SelectionDAGCSEMap::NodeID ID(Opcode, VTs, N1, N2, N3);
1418     void *IP = 0;
1419     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1420       return SDOperand(E, 0);
1421     N = new SDNode(Opcode, N1, N2, N3);
1422     N->setValueTypes(VTs);
1423     CSEMap.InsertNode(N, IP);
1424   } else {
1425     N = new SDNode(Opcode, N1, N2, N3);
1426     N->setValueTypes(VTs);
1427   }
1428   AllNodes.push_back(N);
1429   return SDOperand(N, 0);
1430 }
1431
1432 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1433                                 SDOperand N1, SDOperand N2, SDOperand N3,
1434                                 SDOperand N4) {
1435   SDOperand Ops[] = { N1, N2, N3, N4 };
1436   return getNode(Opcode, VT, Ops, 4);
1437 }
1438
1439 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1440                                 SDOperand N1, SDOperand N2, SDOperand N3,
1441                                 SDOperand N4, SDOperand N5) {
1442   SDOperand Ops[] = { N1, N2, N3, N4, N5 };
1443   return getNode(Opcode, VT, Ops, 5);
1444 }
1445
1446 SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
1447                                 SDOperand Chain, SDOperand Ptr,
1448                                 SDOperand SV) {
1449   SDVTList VTs = getVTList(VT, MVT::Other);
1450   
1451   SelectionDAGCSEMap::NodeID ID(ISD::LOAD, VTs, Chain, Ptr, SV);
1452   void *IP = 0;
1453   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1454     return SDOperand(E, 0);
1455   SDNode *N = new SDNode(ISD::LOAD, Chain, Ptr, SV);
1456   N->setValueTypes(VTs);
1457   CSEMap.InsertNode(N, IP);
1458   AllNodes.push_back(N);
1459   return SDOperand(N, 0);
1460 }
1461
1462 SDOperand SelectionDAG::getVecLoad(unsigned Count, MVT::ValueType EVT,
1463                                    SDOperand Chain, SDOperand Ptr,
1464                                    SDOperand SV) {
1465   SDOperand Ops[] = { Chain, Ptr, SV, getConstant(Count, MVT::i32), 
1466                       getValueType(EVT) };
1467   return getNode(ISD::VLOAD, getVTList(MVT::Vector, MVT::Other), Ops, 5);
1468 }
1469
1470 SDOperand SelectionDAG::getExtLoad(unsigned Opcode, MVT::ValueType VT,
1471                                    SDOperand Chain, SDOperand Ptr, SDOperand SV,
1472                                    MVT::ValueType EVT) {
1473   SDOperand Ops[] = { Chain, Ptr, SV, getValueType(EVT) };
1474   return getNode(Opcode, getVTList(VT, MVT::Other), Ops, 4);
1475 }
1476
1477 SDOperand SelectionDAG::getVAArg(MVT::ValueType VT,
1478                                  SDOperand Chain, SDOperand Ptr,
1479                                  SDOperand SV) {
1480   SDOperand Ops[] = { Chain, Ptr, SV };
1481   return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
1482 }
1483
1484 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1485                                 const SDOperand *Ops, unsigned NumOps) {
1486   switch (NumOps) {
1487   case 0: return getNode(Opcode, VT);
1488   case 1: return getNode(Opcode, VT, Ops[0]);
1489   case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
1490   case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
1491   default: break;
1492   }
1493   
1494   switch (Opcode) {
1495   default: break;
1496   case ISD::TRUNCSTORE: {
1497     assert(NumOps == 5 && "TRUNCSTORE takes 5 operands!");
1498     MVT::ValueType EVT = cast<VTSDNode>(Ops[4])->getVT();
1499 #if 0 // FIXME: If the target supports EVT natively, convert to a truncate/store
1500     // If this is a truncating store of a constant, convert to the desired type
1501     // and store it instead.
1502     if (isa<Constant>(Ops[0])) {
1503       SDOperand Op = getNode(ISD::TRUNCATE, EVT, N1);
1504       if (isa<Constant>(Op))
1505         N1 = Op;
1506     }
1507     // Also for ConstantFP?
1508 #endif
1509     if (Ops[0].getValueType() == EVT)       // Normal store?
1510       return getNode(ISD::STORE, VT, Ops[0], Ops[1], Ops[2], Ops[3]);
1511     assert(Ops[1].getValueType() > EVT && "Not a truncation?");
1512     assert(MVT::isInteger(Ops[1].getValueType()) == MVT::isInteger(EVT) &&
1513            "Can't do FP-INT conversion!");
1514     break;
1515   }
1516   case ISD::SELECT_CC: {
1517     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
1518     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
1519            "LHS and RHS of condition must have same type!");
1520     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
1521            "True and False arms of SelectCC must have same type!");
1522     assert(Ops[2].getValueType() == VT &&
1523            "select_cc node must be of same type as true and false value!");
1524     break;
1525   }
1526   case ISD::BR_CC: {
1527     assert(NumOps == 5 && "BR_CC takes 5 operands!");
1528     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
1529            "LHS/RHS of comparison should match types!");
1530     break;
1531   }
1532   }
1533
1534   // Memoize nodes.
1535   SDNode *N;
1536   SDVTList VTs = getVTList(VT);
1537   if (VT != MVT::Flag) {
1538     SelectionDAGCSEMap::NodeID ID(Opcode, VTs, Ops, NumOps);
1539     void *IP = 0;
1540     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1541       return SDOperand(E, 0);
1542     N = new SDNode(Opcode, Ops, NumOps);
1543     N->setValueTypes(VTs);
1544     CSEMap.InsertNode(N, IP);
1545   } else {
1546     N = new SDNode(Opcode, Ops, NumOps);
1547     N->setValueTypes(VTs);
1548   }
1549   AllNodes.push_back(N);
1550   return SDOperand(N, 0);
1551 }
1552
1553 SDOperand SelectionDAG::getNode(unsigned Opcode,
1554                                 std::vector<MVT::ValueType> &ResultTys,
1555                                 const SDOperand *Ops, unsigned NumOps) {
1556   return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
1557                  Ops, NumOps);
1558 }
1559
1560 SDOperand SelectionDAG::getNode(unsigned Opcode,
1561                                 const MVT::ValueType *VTs, unsigned NumVTs,
1562                                 const SDOperand *Ops, unsigned NumOps) {
1563   if (NumVTs == 1)
1564     return getNode(Opcode, VTs[0], Ops, NumOps);
1565   return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
1566 }  
1567   
1568 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
1569                                 const SDOperand *Ops, unsigned NumOps) {
1570   if (VTList.NumVTs == 1)
1571     return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
1572
1573   switch (Opcode) {
1574   case ISD::EXTLOAD:
1575   case ISD::SEXTLOAD:
1576   case ISD::ZEXTLOAD: {
1577     MVT::ValueType EVT = cast<VTSDNode>(Ops[3])->getVT();
1578     assert(NumOps == 4 && VTList.NumVTs == 2 && "Bad *EXTLOAD!");
1579     // If they are asking for an extending load from/to the same thing, return a
1580     // normal load.
1581     if (VTList.VTs[0] == EVT)
1582       return getLoad(VTList.VTs[0], Ops[0], Ops[1], Ops[2]);
1583     if (MVT::isVector(VTList.VTs[0])) {
1584       assert(EVT == MVT::getVectorBaseType(VTList.VTs[0]) &&
1585              "Invalid vector extload!");
1586     } else {
1587       assert(EVT < VTList.VTs[0] &&
1588              "Should only be an extending load, not truncating!");
1589     }
1590     assert((Opcode == ISD::EXTLOAD || MVT::isInteger(VTList.VTs[0])) &&
1591            "Cannot sign/zero extend a FP/Vector load!");
1592     assert(MVT::isInteger(VTList.VTs[0]) == MVT::isInteger(EVT) &&
1593            "Cannot convert from FP to Int or Int -> FP!");
1594     break;
1595   }
1596
1597   // FIXME: figure out how to safely handle things like
1598   // int foo(int x) { return 1 << (x & 255); }
1599   // int bar() { return foo(256); }
1600 #if 0
1601   case ISD::SRA_PARTS:
1602   case ISD::SRL_PARTS:
1603   case ISD::SHL_PARTS:
1604     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1605         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
1606       return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
1607     else if (N3.getOpcode() == ISD::AND)
1608       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
1609         // If the and is only masking out bits that cannot effect the shift,
1610         // eliminate the and.
1611         unsigned NumBits = MVT::getSizeInBits(VT)*2;
1612         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
1613           return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
1614       }
1615     break;
1616 #endif
1617   }
1618
1619   // Memoize the node unless it returns a flag.
1620   SDNode *N;
1621   if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
1622     SelectionDAGCSEMap::NodeID ID;
1623     ID.SetOpcode(Opcode);
1624     ID.SetValueTypes(VTList);
1625     ID.SetOperands(&Ops[0], NumOps);
1626     void *IP = 0;
1627     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1628       return SDOperand(E, 0);
1629     N = new SDNode(Opcode, Ops, NumOps);
1630     N->setValueTypes(VTList);
1631     CSEMap.InsertNode(N, IP);
1632   } else {
1633     N = new SDNode(Opcode, Ops, NumOps);
1634     N->setValueTypes(VTList);
1635   }
1636   AllNodes.push_back(N);
1637   return SDOperand(N, 0);
1638 }
1639
1640 SDVTList SelectionDAG::getVTList(MVT::ValueType VT) {
1641   return makeVTList(SDNode::getValueTypeList(VT), 1);
1642 }
1643
1644 SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2) {
1645   for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
1646        E = VTList.end(); I != E; ++I) {
1647     if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2)
1648       return makeVTList(&(*I)[0], 2);
1649   }
1650   std::vector<MVT::ValueType> V;
1651   V.push_back(VT1);
1652   V.push_back(VT2);
1653   VTList.push_front(V);
1654   return makeVTList(&(*VTList.begin())[0], 2);
1655 }
1656 SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2,
1657                                  MVT::ValueType VT3) {
1658   for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
1659        E = VTList.end(); I != E; ++I) {
1660     if (I->size() == 3 && (*I)[0] == VT1 && (*I)[1] == VT2 &&
1661         (*I)[2] == VT3)
1662       return makeVTList(&(*I)[0], 3);
1663   }
1664   std::vector<MVT::ValueType> V;
1665   V.push_back(VT1);
1666   V.push_back(VT2);
1667   V.push_back(VT3);
1668   VTList.push_front(V);
1669   return makeVTList(&(*VTList.begin())[0], 3);
1670 }
1671
1672 SDVTList SelectionDAG::getVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
1673   switch (NumVTs) {
1674     case 0: assert(0 && "Cannot have nodes without results!");
1675     case 1: return makeVTList(SDNode::getValueTypeList(VTs[0]), 1);
1676     case 2: return getVTList(VTs[0], VTs[1]);
1677     case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
1678     default: break;
1679   }
1680
1681   for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
1682        E = VTList.end(); I != E; ++I) {
1683     if (I->size() != NumVTs || VTs[0] != (*I)[0] || VTs[1] != (*I)[1]) continue;
1684    
1685     bool NoMatch = false;
1686     for (unsigned i = 2; i != NumVTs; ++i)
1687       if (VTs[i] != (*I)[i]) {
1688         NoMatch = true;
1689         break;
1690       }
1691     if (!NoMatch)
1692       return makeVTList(&*I->begin(), NumVTs);
1693   }
1694   
1695   VTList.push_front(std::vector<MVT::ValueType>(VTs, VTs+NumVTs));
1696   return makeVTList(&*VTList.begin()->begin(), NumVTs);
1697 }
1698
1699
1700 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
1701 /// specified operands.  If the resultant node already exists in the DAG,
1702 /// this does not modify the specified node, instead it returns the node that
1703 /// already exists.  If the resultant node does not exist in the DAG, the
1704 /// input node is returned.  As a degenerate case, if you specify the same
1705 /// input operands as the node already has, the input node is returned.
1706 SDOperand SelectionDAG::
1707 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
1708   SDNode *N = InN.Val;
1709   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
1710   
1711   // Check to see if there is no change.
1712   if (Op == N->getOperand(0)) return InN;
1713   
1714   // See if the modified node already exists.
1715   void *InsertPos = 0;
1716   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
1717     return SDOperand(Existing, InN.ResNo);
1718   
1719   // Nope it doesn't.  Remove the node from it's current place in the maps.
1720   if (InsertPos)
1721     RemoveNodeFromCSEMaps(N);
1722   
1723   // Now we update the operands.
1724   N->OperandList[0].Val->removeUser(N);
1725   Op.Val->addUser(N);
1726   N->OperandList[0] = Op;
1727   
1728   // If this gets put into a CSE map, add it.
1729   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
1730   return InN;
1731 }
1732
1733 SDOperand SelectionDAG::
1734 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
1735   SDNode *N = InN.Val;
1736   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
1737   
1738   // Check to see if there is no change.
1739   bool AnyChange = false;
1740   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
1741     return InN;   // No operands changed, just return the input node.
1742   
1743   // See if the modified node already exists.
1744   void *InsertPos = 0;
1745   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
1746     return SDOperand(Existing, InN.ResNo);
1747   
1748   // Nope it doesn't.  Remove the node from it's current place in the maps.
1749   if (InsertPos)
1750     RemoveNodeFromCSEMaps(N);
1751   
1752   // Now we update the operands.
1753   if (N->OperandList[0] != Op1) {
1754     N->OperandList[0].Val->removeUser(N);
1755     Op1.Val->addUser(N);
1756     N->OperandList[0] = Op1;
1757   }
1758   if (N->OperandList[1] != Op2) {
1759     N->OperandList[1].Val->removeUser(N);
1760     Op2.Val->addUser(N);
1761     N->OperandList[1] = Op2;
1762   }
1763   
1764   // If this gets put into a CSE map, add it.
1765   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
1766   return InN;
1767 }
1768
1769 SDOperand SelectionDAG::
1770 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
1771   SDOperand Ops[] = { Op1, Op2, Op3 };
1772   return UpdateNodeOperands(N, Ops, 3);
1773 }
1774
1775 SDOperand SelectionDAG::
1776 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, 
1777                    SDOperand Op3, SDOperand Op4) {
1778   SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
1779   return UpdateNodeOperands(N, Ops, 4);
1780 }
1781
1782 SDOperand SelectionDAG::
1783 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
1784                    SDOperand Op3, SDOperand Op4, SDOperand Op5) {
1785   SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
1786   return UpdateNodeOperands(N, Ops, 5);
1787 }
1788
1789
1790 SDOperand SelectionDAG::
1791 UpdateNodeOperands(SDOperand InN, SDOperand *Ops, unsigned NumOps) {
1792   SDNode *N = InN.Val;
1793   assert(N->getNumOperands() == NumOps &&
1794          "Update with wrong number of operands");
1795   
1796   // Check to see if there is no change.
1797   bool AnyChange = false;
1798   for (unsigned i = 0; i != NumOps; ++i) {
1799     if (Ops[i] != N->getOperand(i)) {
1800       AnyChange = true;
1801       break;
1802     }
1803   }
1804   
1805   // No operands changed, just return the input node.
1806   if (!AnyChange) return InN;
1807   
1808   // See if the modified node already exists.
1809   void *InsertPos = 0;
1810   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
1811     return SDOperand(Existing, InN.ResNo);
1812   
1813   // Nope it doesn't.  Remove the node from it's current place in the maps.
1814   if (InsertPos)
1815     RemoveNodeFromCSEMaps(N);
1816   
1817   // Now we update the operands.
1818   for (unsigned i = 0; i != NumOps; ++i) {
1819     if (N->OperandList[i] != Ops[i]) {
1820       N->OperandList[i].Val->removeUser(N);
1821       Ops[i].Val->addUser(N);
1822       N->OperandList[i] = Ops[i];
1823     }
1824   }
1825
1826   // If this gets put into a CSE map, add it.
1827   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
1828   return InN;
1829 }
1830
1831
1832
1833
1834 /// SelectNodeTo - These are used for target selectors to *mutate* the
1835 /// specified node to have the specified return type, Target opcode, and
1836 /// operands.  Note that target opcodes are stored as
1837 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
1838 ///
1839 /// Note that SelectNodeTo returns the resultant node.  If there is already a
1840 /// node of the specified opcode and operands, it returns that node instead of
1841 /// the current one.
1842 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1843                                    MVT::ValueType VT) {
1844   SDVTList VTs = getVTList(VT);
1845   SelectionDAGCSEMap::NodeID ID(ISD::BUILTIN_OP_END+TargetOpc, VTs);
1846   void *IP = 0;
1847   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
1848     return ON;
1849    
1850   RemoveNodeFromCSEMaps(N);
1851   
1852   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1853   N->setValueTypes(VTs);
1854
1855   CSEMap.InsertNode(N, IP);
1856   return N;
1857 }
1858
1859 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1860                                    MVT::ValueType VT, SDOperand Op1) {
1861   // If an identical node already exists, use it.
1862   SDVTList VTs = getVTList(VT);
1863   SelectionDAGCSEMap::NodeID ID(ISD::BUILTIN_OP_END+TargetOpc, VTs, Op1);
1864   void *IP = 0;
1865   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
1866     return ON;
1867                                        
1868   RemoveNodeFromCSEMaps(N);
1869   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1870   N->setValueTypes(VTs);
1871   N->setOperands(Op1);
1872   CSEMap.InsertNode(N, IP);
1873   return N;
1874 }
1875
1876 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1877                                    MVT::ValueType VT, SDOperand Op1,
1878                                    SDOperand Op2) {
1879   // If an identical node already exists, use it.
1880   SDVTList VTs = getVTList(VT);
1881   SelectionDAGCSEMap::NodeID ID(ISD::BUILTIN_OP_END+TargetOpc, VTs, Op1, Op2);
1882   void *IP = 0;
1883   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
1884     return ON;
1885                                        
1886   RemoveNodeFromCSEMaps(N);
1887   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1888   N->setValueTypes(VTs);
1889   N->setOperands(Op1, Op2);
1890   
1891   CSEMap.InsertNode(N, IP);   // Memoize the new node.
1892   return N;
1893 }
1894
1895 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1896                                    MVT::ValueType VT, SDOperand Op1,
1897                                    SDOperand Op2, SDOperand Op3) {
1898   // If an identical node already exists, use it.
1899   SDVTList VTs = getVTList(VT);
1900   SelectionDAGCSEMap::NodeID ID(ISD::BUILTIN_OP_END+TargetOpc, VTs,
1901                                 Op1, Op2, Op3);
1902   void *IP = 0;
1903   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
1904     return ON;
1905                                        
1906   RemoveNodeFromCSEMaps(N);
1907   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1908   N->setValueTypes(VTs);
1909   N->setOperands(Op1, Op2, Op3);
1910
1911   CSEMap.InsertNode(N, IP);   // Memoize the new node.
1912   return N;
1913 }
1914
1915 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1916                                    MVT::ValueType VT, const SDOperand *Ops,
1917                                    unsigned NumOps) {
1918   // If an identical node already exists, use it.
1919   SDVTList VTs = getVTList(VT);
1920   SelectionDAGCSEMap::NodeID ID(ISD::BUILTIN_OP_END+TargetOpc, VTs);
1921   for (unsigned i = 0; i != NumOps; ++i)
1922     ID.AddOperand(Ops[i]);
1923   void *IP = 0;
1924   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
1925     return ON;
1926                                        
1927   RemoveNodeFromCSEMaps(N);
1928   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1929   N->setValueTypes(VTs);
1930   N->setOperands(Ops, NumOps);
1931   
1932   CSEMap.InsertNode(N, IP);   // Memoize the new node.
1933   return N;
1934 }
1935
1936 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc, 
1937                                    MVT::ValueType VT1, MVT::ValueType VT2,
1938                                    SDOperand Op1, SDOperand Op2) {
1939   SDVTList VTs = getVTList(VT1, VT2);
1940   SelectionDAGCSEMap::NodeID ID(ISD::BUILTIN_OP_END+TargetOpc, VTs, Op1, Op2);
1941   void *IP = 0;
1942   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
1943     return ON;
1944
1945   RemoveNodeFromCSEMaps(N);
1946   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1947   N->setValueTypes(VTs);
1948   N->setOperands(Op1, Op2);
1949   
1950   CSEMap.InsertNode(N, IP);   // Memoize the new node.
1951   return N;
1952 }
1953
1954 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1955                                    MVT::ValueType VT1, MVT::ValueType VT2,
1956                                    SDOperand Op1, SDOperand Op2, 
1957                                    SDOperand Op3) {
1958   // If an identical node already exists, use it.
1959   SDVTList VTs = getVTList(VT1, VT2);
1960   SelectionDAGCSEMap::NodeID ID(ISD::BUILTIN_OP_END+TargetOpc, VTs,
1961                                 Op1, Op2, Op3);
1962   void *IP = 0;
1963   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
1964     return ON;
1965
1966   RemoveNodeFromCSEMaps(N);
1967   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1968   N->setValueTypes(VTs);
1969   N->setOperands(Op1, Op2, Op3);
1970   
1971   CSEMap.InsertNode(N, IP);   // Memoize the new node.
1972   return N;
1973 }
1974
1975
1976 /// getTargetNode - These are used for target selectors to create a new node
1977 /// with specified return type(s), target opcode, and operands.
1978 ///
1979 /// Note that getTargetNode returns the resultant node.  If there is already a
1980 /// node of the specified opcode and operands, it returns that node instead of
1981 /// the current one.
1982 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT) {
1983   return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
1984 }
1985 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
1986                                     SDOperand Op1) {
1987   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
1988 }
1989 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
1990                                     SDOperand Op1, SDOperand Op2) {
1991   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
1992 }
1993 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
1994                                     SDOperand Op1, SDOperand Op2, SDOperand Op3) {
1995   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
1996 }
1997 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
1998                                     const SDOperand *Ops, unsigned NumOps) {
1999   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val;
2000 }
2001 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2002                                     MVT::ValueType VT2, SDOperand Op1) {
2003   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
2004   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op1, 1).Val;
2005 }
2006 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2007                                     MVT::ValueType VT2, SDOperand Op1,
2008                                     SDOperand Op2) {
2009   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
2010   SDOperand Ops[] = { Op1, Op2 };
2011   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 2).Val;
2012 }
2013 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2014                                     MVT::ValueType VT2, SDOperand Op1,
2015                                     SDOperand Op2, SDOperand Op3) {
2016   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
2017   SDOperand Ops[] = { Op1, Op2, Op3 };
2018   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 3).Val;
2019 }
2020 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, 
2021                                     MVT::ValueType VT2,
2022                                     const SDOperand *Ops, unsigned NumOps) {
2023   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
2024   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, NumOps).Val;
2025 }
2026 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2027                                     MVT::ValueType VT2, MVT::ValueType VT3,
2028                                     SDOperand Op1, SDOperand Op2) {
2029   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
2030   SDOperand Ops[] = { Op1, Op2 };
2031   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 2).Val;
2032 }
2033 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, 
2034                                     MVT::ValueType VT2, MVT::ValueType VT3,
2035                                     const SDOperand *Ops, unsigned NumOps) {
2036   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
2037   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, NumOps).Val;
2038 }
2039
2040 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
2041 /// This can cause recursive merging of nodes in the DAG.
2042 ///
2043 /// This version assumes From/To have a single result value.
2044 ///
2045 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand ToN,
2046                                       std::vector<SDNode*> *Deleted) {
2047   SDNode *From = FromN.Val, *To = ToN.Val;
2048   assert(From->getNumValues() == 1 && To->getNumValues() == 1 &&
2049          "Cannot replace with this method!");
2050   assert(From != To && "Cannot replace uses of with self");
2051   
2052   while (!From->use_empty()) {
2053     // Process users until they are all gone.
2054     SDNode *U = *From->use_begin();
2055     
2056     // This node is about to morph, remove its old self from the CSE maps.
2057     RemoveNodeFromCSEMaps(U);
2058     
2059     for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
2060          I != E; ++I)
2061       if (I->Val == From) {
2062         From->removeUser(U);
2063         I->Val = To;
2064         To->addUser(U);
2065       }
2066
2067     // Now that we have modified U, add it back to the CSE maps.  If it already
2068     // exists there, recursively merge the results together.
2069     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
2070       ReplaceAllUsesWith(U, Existing, Deleted);
2071       // U is now dead.
2072       if (Deleted) Deleted->push_back(U);
2073       DeleteNodeNotInCSEMaps(U);
2074     }
2075   }
2076 }
2077
2078 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
2079 /// This can cause recursive merging of nodes in the DAG.
2080 ///
2081 /// This version assumes From/To have matching types and numbers of result
2082 /// values.
2083 ///
2084 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
2085                                       std::vector<SDNode*> *Deleted) {
2086   assert(From != To && "Cannot replace uses of with self");
2087   assert(From->getNumValues() == To->getNumValues() &&
2088          "Cannot use this version of ReplaceAllUsesWith!");
2089   if (From->getNumValues() == 1) {  // If possible, use the faster version.
2090     ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0), Deleted);
2091     return;
2092   }
2093   
2094   while (!From->use_empty()) {
2095     // Process users until they are all gone.
2096     SDNode *U = *From->use_begin();
2097     
2098     // This node is about to morph, remove its old self from the CSE maps.
2099     RemoveNodeFromCSEMaps(U);
2100     
2101     for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
2102          I != E; ++I)
2103       if (I->Val == From) {
2104         From->removeUser(U);
2105         I->Val = To;
2106         To->addUser(U);
2107       }
2108         
2109     // Now that we have modified U, add it back to the CSE maps.  If it already
2110     // exists there, recursively merge the results together.
2111     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
2112       ReplaceAllUsesWith(U, Existing, Deleted);
2113       // U is now dead.
2114       if (Deleted) Deleted->push_back(U);
2115       DeleteNodeNotInCSEMaps(U);
2116     }
2117   }
2118 }
2119
2120 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
2121 /// This can cause recursive merging of nodes in the DAG.
2122 ///
2123 /// This version can replace From with any result values.  To must match the
2124 /// number and types of values returned by From.
2125 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
2126                                       const SDOperand *To,
2127                                       std::vector<SDNode*> *Deleted) {
2128   if (From->getNumValues() == 1 && To[0].Val->getNumValues() == 1) {
2129     // Degenerate case handled above.
2130     ReplaceAllUsesWith(SDOperand(From, 0), To[0], Deleted);
2131     return;
2132   }
2133
2134   while (!From->use_empty()) {
2135     // Process users until they are all gone.
2136     SDNode *U = *From->use_begin();
2137     
2138     // This node is about to morph, remove its old self from the CSE maps.
2139     RemoveNodeFromCSEMaps(U);
2140     
2141     for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
2142          I != E; ++I)
2143       if (I->Val == From) {
2144         const SDOperand &ToOp = To[I->ResNo];
2145         From->removeUser(U);
2146         *I = ToOp;
2147         ToOp.Val->addUser(U);
2148       }
2149         
2150     // Now that we have modified U, add it back to the CSE maps.  If it already
2151     // exists there, recursively merge the results together.
2152     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
2153       ReplaceAllUsesWith(U, Existing, Deleted);
2154       // U is now dead.
2155       if (Deleted) Deleted->push_back(U);
2156       DeleteNodeNotInCSEMaps(U);
2157     }
2158   }
2159 }
2160
2161 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
2162 /// uses of other values produced by From.Val alone.  The Deleted vector is
2163 /// handled the same was as for ReplaceAllUsesWith.
2164 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
2165                                              std::vector<SDNode*> &Deleted) {
2166   assert(From != To && "Cannot replace a value with itself");
2167   // Handle the simple, trivial, case efficiently.
2168   if (From.Val->getNumValues() == 1 && To.Val->getNumValues() == 1) {
2169     ReplaceAllUsesWith(From, To, &Deleted);
2170     return;
2171   }
2172   
2173   // Get all of the users in a nice, deterministically ordered, uniqued set.
2174   SetVector<SDNode*> Users(From.Val->use_begin(), From.Val->use_end());
2175
2176   while (!Users.empty()) {
2177     // We know that this user uses some value of From.  If it is the right
2178     // value, update it.
2179     SDNode *User = Users.back();
2180     Users.pop_back();
2181     
2182     for (SDOperand *Op = User->OperandList,
2183          *E = User->OperandList+User->NumOperands; Op != E; ++Op) {
2184       if (*Op == From) {
2185         // Okay, we know this user needs to be updated.  Remove its old self
2186         // from the CSE maps.
2187         RemoveNodeFromCSEMaps(User);
2188         
2189         // Update all operands that match "From".
2190         for (; Op != E; ++Op) {
2191           if (*Op == From) {
2192             From.Val->removeUser(User);
2193             *Op = To;
2194             To.Val->addUser(User);
2195           }
2196         }
2197                    
2198         // Now that we have modified User, add it back to the CSE maps.  If it
2199         // already exists there, recursively merge the results together.
2200         if (SDNode *Existing = AddNonLeafNodeToCSEMaps(User)) {
2201           unsigned NumDeleted = Deleted.size();
2202           ReplaceAllUsesWith(User, Existing, &Deleted);
2203           
2204           // User is now dead.
2205           Deleted.push_back(User);
2206           DeleteNodeNotInCSEMaps(User);
2207           
2208           // We have to be careful here, because ReplaceAllUsesWith could have
2209           // deleted a user of From, which means there may be dangling pointers
2210           // in the "Users" setvector.  Scan over the deleted node pointers and
2211           // remove them from the setvector.
2212           for (unsigned i = NumDeleted, e = Deleted.size(); i != e; ++i)
2213             Users.remove(Deleted[i]);
2214         }
2215         break;   // Exit the operand scanning loop.
2216       }
2217     }
2218   }
2219 }
2220
2221
2222 /// AssignNodeIds - Assign a unique node id for each node in the DAG based on
2223 /// their allnodes order. It returns the maximum id.
2224 unsigned SelectionDAG::AssignNodeIds() {
2225   unsigned Id = 0;
2226   for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I){
2227     SDNode *N = I;
2228     N->setNodeId(Id++);
2229   }
2230   return Id;
2231 }
2232
2233 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
2234 /// based on their topological order. It returns the maximum id and a vector
2235 /// of the SDNodes* in assigned order by reference.
2236 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
2237   unsigned DAGSize = AllNodes.size();
2238   std::vector<unsigned> InDegree(DAGSize);
2239   std::vector<SDNode*> Sources;
2240
2241   // Use a two pass approach to avoid using a std::map which is slow.
2242   unsigned Id = 0;
2243   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
2244     SDNode *N = I;
2245     N->setNodeId(Id++);
2246     unsigned Degree = N->use_size();
2247     InDegree[N->getNodeId()] = Degree;
2248     if (Degree == 0)
2249       Sources.push_back(N);
2250   }
2251
2252   TopOrder.clear();
2253   while (!Sources.empty()) {
2254     SDNode *N = Sources.back();
2255     Sources.pop_back();
2256     TopOrder.push_back(N);
2257     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
2258       SDNode *P = I->Val;
2259       unsigned Degree = --InDegree[P->getNodeId()];
2260       if (Degree == 0)
2261         Sources.push_back(P);
2262     }
2263   }
2264
2265   // Second pass, assign the actual topological order as node ids.
2266   Id = 0;
2267   for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
2268        TI != TE; ++TI)
2269     (*TI)->setNodeId(Id++);
2270
2271   return Id;
2272 }
2273
2274
2275
2276 //===----------------------------------------------------------------------===//
2277 //                              SDNode Class
2278 //===----------------------------------------------------------------------===//
2279
2280 // Out-of-line virtual method to give class a home.
2281 void SDNode::ANCHOR() {
2282 }
2283
2284 /// getValueTypeList - Return a pointer to the specified value type.
2285 ///
2286 MVT::ValueType *SDNode::getValueTypeList(MVT::ValueType VT) {
2287   static MVT::ValueType VTs[MVT::LAST_VALUETYPE];
2288   VTs[VT] = VT;
2289   return &VTs[VT];
2290 }
2291   
2292 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
2293 /// indicated value.  This method ignores uses of other values defined by this
2294 /// operation.
2295 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
2296   assert(Value < getNumValues() && "Bad value!");
2297
2298   // If there is only one value, this is easy.
2299   if (getNumValues() == 1)
2300     return use_size() == NUses;
2301   if (Uses.size() < NUses) return false;
2302
2303   SDOperand TheValue(const_cast<SDNode *>(this), Value);
2304
2305   std::set<SDNode*> UsersHandled;
2306
2307   for (SDNode::use_iterator UI = Uses.begin(), E = Uses.end(); UI != E; ++UI) {
2308     SDNode *User = *UI;
2309     if (User->getNumOperands() == 1 ||
2310         UsersHandled.insert(User).second)     // First time we've seen this?
2311       for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
2312         if (User->getOperand(i) == TheValue) {
2313           if (NUses == 0)
2314             return false;   // too many uses
2315           --NUses;
2316         }
2317   }
2318
2319   // Found exactly the right number of uses?
2320   return NUses == 0;
2321 }
2322
2323
2324 // isOnlyUse - Return true if this node is the only use of N.
2325 bool SDNode::isOnlyUse(SDNode *N) const {
2326   bool Seen = false;
2327   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
2328     SDNode *User = *I;
2329     if (User == this)
2330       Seen = true;
2331     else
2332       return false;
2333   }
2334
2335   return Seen;
2336 }
2337
2338 // isOperand - Return true if this node is an operand of N.
2339 bool SDOperand::isOperand(SDNode *N) const {
2340   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
2341     if (*this == N->getOperand(i))
2342       return true;
2343   return false;
2344 }
2345
2346 bool SDNode::isOperand(SDNode *N) const {
2347   for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
2348     if (this == N->OperandList[i].Val)
2349       return true;
2350   return false;
2351 }
2352
2353 const char *SDNode::getOperationName(const SelectionDAG *G) const {
2354   switch (getOpcode()) {
2355   default:
2356     if (getOpcode() < ISD::BUILTIN_OP_END)
2357       return "<<Unknown DAG Node>>";
2358     else {
2359       if (G) {
2360         if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
2361           if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
2362             return TII->getName(getOpcode()-ISD::BUILTIN_OP_END);
2363
2364         TargetLowering &TLI = G->getTargetLoweringInfo();
2365         const char *Name =
2366           TLI.getTargetNodeName(getOpcode());
2367         if (Name) return Name;
2368       }
2369
2370       return "<<Unknown Target Node>>";
2371     }
2372    
2373   case ISD::PCMARKER:      return "PCMarker";
2374   case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
2375   case ISD::SRCVALUE:      return "SrcValue";
2376   case ISD::EntryToken:    return "EntryToken";
2377   case ISD::TokenFactor:   return "TokenFactor";
2378   case ISD::AssertSext:    return "AssertSext";
2379   case ISD::AssertZext:    return "AssertZext";
2380
2381   case ISD::STRING:        return "String";
2382   case ISD::BasicBlock:    return "BasicBlock";
2383   case ISD::VALUETYPE:     return "ValueType";
2384   case ISD::Register:      return "Register";
2385
2386   case ISD::Constant:      return "Constant";
2387   case ISD::ConstantFP:    return "ConstantFP";
2388   case ISD::GlobalAddress: return "GlobalAddress";
2389   case ISD::FrameIndex:    return "FrameIndex";
2390   case ISD::JumpTable:     return "JumpTable";
2391   case ISD::ConstantPool:  return "ConstantPool";
2392   case ISD::ExternalSymbol: return "ExternalSymbol";
2393   case ISD::INTRINSIC_WO_CHAIN: {
2394     unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
2395     return Intrinsic::getName((Intrinsic::ID)IID);
2396   }
2397   case ISD::INTRINSIC_VOID:
2398   case ISD::INTRINSIC_W_CHAIN: {
2399     unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
2400     return Intrinsic::getName((Intrinsic::ID)IID);
2401   }
2402
2403   case ISD::BUILD_VECTOR:   return "BUILD_VECTOR";
2404   case ISD::TargetConstant: return "TargetConstant";
2405   case ISD::TargetConstantFP:return "TargetConstantFP";
2406   case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
2407   case ISD::TargetFrameIndex: return "TargetFrameIndex";
2408   case ISD::TargetJumpTable:  return "TargetJumpTable";
2409   case ISD::TargetConstantPool:  return "TargetConstantPool";
2410   case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
2411
2412   case ISD::CopyToReg:     return "CopyToReg";
2413   case ISD::CopyFromReg:   return "CopyFromReg";
2414   case ISD::UNDEF:         return "undef";
2415   case ISD::MERGE_VALUES:  return "mergevalues";
2416   case ISD::INLINEASM:     return "inlineasm";
2417   case ISD::HANDLENODE:    return "handlenode";
2418   case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
2419   case ISD::CALL:          return "call";
2420     
2421   // Unary operators
2422   case ISD::FABS:   return "fabs";
2423   case ISD::FNEG:   return "fneg";
2424   case ISD::FSQRT:  return "fsqrt";
2425   case ISD::FSIN:   return "fsin";
2426   case ISD::FCOS:   return "fcos";
2427   case ISD::FPOWI:  return "fpowi";
2428
2429   // Binary operators
2430   case ISD::ADD:    return "add";
2431   case ISD::SUB:    return "sub";
2432   case ISD::MUL:    return "mul";
2433   case ISD::MULHU:  return "mulhu";
2434   case ISD::MULHS:  return "mulhs";
2435   case ISD::SDIV:   return "sdiv";
2436   case ISD::UDIV:   return "udiv";
2437   case ISD::SREM:   return "srem";
2438   case ISD::UREM:   return "urem";
2439   case ISD::AND:    return "and";
2440   case ISD::OR:     return "or";
2441   case ISD::XOR:    return "xor";
2442   case ISD::SHL:    return "shl";
2443   case ISD::SRA:    return "sra";
2444   case ISD::SRL:    return "srl";
2445   case ISD::ROTL:   return "rotl";
2446   case ISD::ROTR:   return "rotr";
2447   case ISD::FADD:   return "fadd";
2448   case ISD::FSUB:   return "fsub";
2449   case ISD::FMUL:   return "fmul";
2450   case ISD::FDIV:   return "fdiv";
2451   case ISD::FREM:   return "frem";
2452   case ISD::FCOPYSIGN: return "fcopysign";
2453   case ISD::VADD:   return "vadd";
2454   case ISD::VSUB:   return "vsub";
2455   case ISD::VMUL:   return "vmul";
2456   case ISD::VSDIV:  return "vsdiv";
2457   case ISD::VUDIV:  return "vudiv";
2458   case ISD::VAND:   return "vand";
2459   case ISD::VOR:    return "vor";
2460   case ISD::VXOR:   return "vxor";
2461
2462   case ISD::SETCC:       return "setcc";
2463   case ISD::SELECT:      return "select";
2464   case ISD::SELECT_CC:   return "select_cc";
2465   case ISD::VSELECT:     return "vselect";
2466   case ISD::INSERT_VECTOR_ELT:   return "insert_vector_elt";
2467   case ISD::VINSERT_VECTOR_ELT:  return "vinsert_vector_elt";
2468   case ISD::EXTRACT_VECTOR_ELT:  return "extract_vector_elt";
2469   case ISD::VEXTRACT_VECTOR_ELT: return "vextract_vector_elt";
2470   case ISD::SCALAR_TO_VECTOR:    return "scalar_to_vector";
2471   case ISD::VBUILD_VECTOR:       return "vbuild_vector";
2472   case ISD::VECTOR_SHUFFLE:      return "vector_shuffle";
2473   case ISD::VVECTOR_SHUFFLE:     return "vvector_shuffle";
2474   case ISD::VBIT_CONVERT:        return "vbit_convert";
2475   case ISD::ADDC:        return "addc";
2476   case ISD::ADDE:        return "adde";
2477   case ISD::SUBC:        return "subc";
2478   case ISD::SUBE:        return "sube";
2479   case ISD::SHL_PARTS:   return "shl_parts";
2480   case ISD::SRA_PARTS:   return "sra_parts";
2481   case ISD::SRL_PARTS:   return "srl_parts";
2482
2483   // Conversion operators.
2484   case ISD::SIGN_EXTEND: return "sign_extend";
2485   case ISD::ZERO_EXTEND: return "zero_extend";
2486   case ISD::ANY_EXTEND:  return "any_extend";
2487   case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
2488   case ISD::TRUNCATE:    return "truncate";
2489   case ISD::FP_ROUND:    return "fp_round";
2490   case ISD::FP_ROUND_INREG: return "fp_round_inreg";
2491   case ISD::FP_EXTEND:   return "fp_extend";
2492
2493   case ISD::SINT_TO_FP:  return "sint_to_fp";
2494   case ISD::UINT_TO_FP:  return "uint_to_fp";
2495   case ISD::FP_TO_SINT:  return "fp_to_sint";
2496   case ISD::FP_TO_UINT:  return "fp_to_uint";
2497   case ISD::BIT_CONVERT: return "bit_convert";
2498
2499     // Control flow instructions
2500   case ISD::BR:      return "br";
2501   case ISD::BRIND:   return "brind";
2502   case ISD::BRCOND:  return "brcond";
2503   case ISD::BR_CC:   return "br_cc";
2504   case ISD::RET:     return "ret";
2505   case ISD::CALLSEQ_START:  return "callseq_start";
2506   case ISD::CALLSEQ_END:    return "callseq_end";
2507
2508     // Other operators
2509   case ISD::LOAD:               return "load";
2510   case ISD::STORE:              return "store";
2511   case ISD::VLOAD:              return "vload";
2512   case ISD::EXTLOAD:            return "extload";
2513   case ISD::SEXTLOAD:           return "sextload";
2514   case ISD::ZEXTLOAD:           return "zextload";
2515   case ISD::TRUNCSTORE:         return "truncstore";
2516   case ISD::VAARG:              return "vaarg";
2517   case ISD::VACOPY:             return "vacopy";
2518   case ISD::VAEND:              return "vaend";
2519   case ISD::VASTART:            return "vastart";
2520   case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
2521   case ISD::EXTRACT_ELEMENT:    return "extract_element";
2522   case ISD::BUILD_PAIR:         return "build_pair";
2523   case ISD::STACKSAVE:          return "stacksave";
2524   case ISD::STACKRESTORE:       return "stackrestore";
2525     
2526   // Block memory operations.
2527   case ISD::MEMSET:  return "memset";
2528   case ISD::MEMCPY:  return "memcpy";
2529   case ISD::MEMMOVE: return "memmove";
2530
2531   // Bit manipulation
2532   case ISD::BSWAP:   return "bswap";
2533   case ISD::CTPOP:   return "ctpop";
2534   case ISD::CTTZ:    return "cttz";
2535   case ISD::CTLZ:    return "ctlz";
2536
2537   // Debug info
2538   case ISD::LOCATION: return "location";
2539   case ISD::DEBUG_LOC: return "debug_loc";
2540   case ISD::DEBUG_LABEL: return "debug_label";
2541
2542   case ISD::CONDCODE:
2543     switch (cast<CondCodeSDNode>(this)->get()) {
2544     default: assert(0 && "Unknown setcc condition!");
2545     case ISD::SETOEQ:  return "setoeq";
2546     case ISD::SETOGT:  return "setogt";
2547     case ISD::SETOGE:  return "setoge";
2548     case ISD::SETOLT:  return "setolt";
2549     case ISD::SETOLE:  return "setole";
2550     case ISD::SETONE:  return "setone";
2551
2552     case ISD::SETO:    return "seto";
2553     case ISD::SETUO:   return "setuo";
2554     case ISD::SETUEQ:  return "setue";
2555     case ISD::SETUGT:  return "setugt";
2556     case ISD::SETUGE:  return "setuge";
2557     case ISD::SETULT:  return "setult";
2558     case ISD::SETULE:  return "setule";
2559     case ISD::SETUNE:  return "setune";
2560
2561     case ISD::SETEQ:   return "seteq";
2562     case ISD::SETGT:   return "setgt";
2563     case ISD::SETGE:   return "setge";
2564     case ISD::SETLT:   return "setlt";
2565     case ISD::SETLE:   return "setle";
2566     case ISD::SETNE:   return "setne";
2567     }
2568   }
2569 }
2570
2571 void SDNode::dump() const { dump(0); }
2572 void SDNode::dump(const SelectionDAG *G) const {
2573   std::cerr << (void*)this << ": ";
2574
2575   for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
2576     if (i) std::cerr << ",";
2577     if (getValueType(i) == MVT::Other)
2578       std::cerr << "ch";
2579     else
2580       std::cerr << MVT::getValueTypeString(getValueType(i));
2581   }
2582   std::cerr << " = " << getOperationName(G);
2583
2584   std::cerr << " ";
2585   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2586     if (i) std::cerr << ", ";
2587     std::cerr << (void*)getOperand(i).Val;
2588     if (unsigned RN = getOperand(i).ResNo)
2589       std::cerr << ":" << RN;
2590   }
2591
2592   if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
2593     std::cerr << "<" << CSDN->getValue() << ">";
2594   } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
2595     std::cerr << "<" << CSDN->getValue() << ">";
2596   } else if (const GlobalAddressSDNode *GADN =
2597              dyn_cast<GlobalAddressSDNode>(this)) {
2598     int offset = GADN->getOffset();
2599     std::cerr << "<";
2600     WriteAsOperand(std::cerr, GADN->getGlobal()) << ">";
2601     if (offset > 0)
2602       std::cerr << " + " << offset;
2603     else
2604       std::cerr << " " << offset;
2605   } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
2606     std::cerr << "<" << FIDN->getIndex() << ">";
2607   } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
2608     int offset = CP->getOffset();
2609     if (CP->isMachineConstantPoolEntry())
2610       std::cerr << "<" << *CP->getMachineCPVal() << ">";
2611     else
2612       std::cerr << "<" << *CP->getConstVal() << ">";
2613     if (offset > 0)
2614       std::cerr << " + " << offset;
2615     else
2616       std::cerr << " " << offset;
2617   } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
2618     std::cerr << "<";
2619     const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
2620     if (LBB)
2621       std::cerr << LBB->getName() << " ";
2622     std::cerr << (const void*)BBDN->getBasicBlock() << ">";
2623   } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
2624     if (G && R->getReg() && MRegisterInfo::isPhysicalRegister(R->getReg())) {
2625       std::cerr << " " <<G->getTarget().getRegisterInfo()->getName(R->getReg());
2626     } else {
2627       std::cerr << " #" << R->getReg();
2628     }
2629   } else if (const ExternalSymbolSDNode *ES =
2630              dyn_cast<ExternalSymbolSDNode>(this)) {
2631     std::cerr << "'" << ES->getSymbol() << "'";
2632   } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
2633     if (M->getValue())
2634       std::cerr << "<" << M->getValue() << ":" << M->getOffset() << ">";
2635     else
2636       std::cerr << "<null:" << M->getOffset() << ">";
2637   } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
2638     std::cerr << ":" << getValueTypeString(N->getVT());
2639   }
2640 }
2641
2642 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
2643   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
2644     if (N->getOperand(i).Val->hasOneUse())
2645       DumpNodes(N->getOperand(i).Val, indent+2, G);
2646     else
2647       std::cerr << "\n" << std::string(indent+2, ' ')
2648                 << (void*)N->getOperand(i).Val << ": <multiple use>";
2649
2650
2651   std::cerr << "\n" << std::string(indent, ' ');
2652   N->dump(G);
2653 }
2654
2655 void SelectionDAG::dump() const {
2656   std::cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
2657   std::vector<const SDNode*> Nodes;
2658   for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
2659        I != E; ++I)
2660     Nodes.push_back(I);
2661   
2662   std::sort(Nodes.begin(), Nodes.end());
2663
2664   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2665     if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
2666       DumpNodes(Nodes[i], 2, this);
2667   }
2668
2669   DumpNodes(getRoot().Val, 2, this);
2670
2671   std::cerr << "\n\n";
2672 }
2673
2674 const Type *ConstantPoolSDNode::getType() const {
2675   if (isMachineConstantPoolEntry())
2676     return Val.MachineCPVal->getType();
2677   return Val.ConstVal->getType();
2678 }