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