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