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