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