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