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