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