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