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