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