Do not CSE DEBUG_LOC, DBG_LABEL, DBG_STOPPOINT, DECLARE, and EH_LABEL SDNode's. This...
[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 is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements the SelectionDAG class.
11 //
12 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "llvm/Constants.h"
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/GlobalAlias.h"
17 #include "llvm/GlobalVariable.h"
18 #include "llvm/Intrinsics.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/PseudoSourceValue.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetLowering.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/ADT/SetVector.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include <algorithm>
39 #include <cmath>
40 using namespace llvm;
41
42 /// makeVTList - Return an instance of the SDVTList struct initialized with the
43 /// specified members.
44 static SDVTList makeVTList(const MVT *VTs, unsigned NumVTs) {
45   SDVTList Res = {VTs, NumVTs};
46   return Res;
47 }
48
49 static const fltSemantics *MVTToAPFloatSemantics(MVT VT) {
50   switch (VT.getSimpleVT()) {
51   default: assert(0 && "Unknown FP format");
52   case MVT::f32:     return &APFloat::IEEEsingle;
53   case MVT::f64:     return &APFloat::IEEEdouble;
54   case MVT::f80:     return &APFloat::x87DoubleExtended;
55   case MVT::f128:    return &APFloat::IEEEquad;
56   case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
57   }
58 }
59
60 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
61
62 //===----------------------------------------------------------------------===//
63 //                              ConstantFPSDNode Class
64 //===----------------------------------------------------------------------===//
65
66 /// isExactlyValue - We don't rely on operator== working on double values, as
67 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
68 /// As such, this method can be used to do an exact bit-for-bit comparison of
69 /// two floating point values.
70 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
71   return Value.bitwiseIsEqual(V);
72 }
73
74 bool ConstantFPSDNode::isValueValidForType(MVT VT,
75                                            const APFloat& Val) {
76   assert(VT.isFloatingPoint() && "Can only convert between FP types");
77   
78   // PPC long double cannot be converted to any other type.
79   if (VT == MVT::ppcf128 ||
80       &Val.getSemantics() == &APFloat::PPCDoubleDouble)
81     return false;
82   
83   // convert modifies in place, so make a copy.
84   APFloat Val2 = APFloat(Val);
85   return Val2.convert(*MVTToAPFloatSemantics(VT),
86                       APFloat::rmNearestTiesToEven) == APFloat::opOK;
87 }
88
89 //===----------------------------------------------------------------------===//
90 //                              ISD Namespace
91 //===----------------------------------------------------------------------===//
92
93 /// isBuildVectorAllOnes - Return true if the specified node is a
94 /// BUILD_VECTOR where all of the elements are ~0 or undef.
95 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
96   // Look through a bit convert.
97   if (N->getOpcode() == ISD::BIT_CONVERT)
98     N = N->getOperand(0).Val;
99   
100   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
101   
102   unsigned i = 0, e = N->getNumOperands();
103   
104   // Skip over all of the undef values.
105   while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
106     ++i;
107   
108   // Do not accept an all-undef vector.
109   if (i == e) return false;
110   
111   // Do not accept build_vectors that aren't all constants or which have non-~0
112   // elements.
113   SDOperand NotZero = N->getOperand(i);
114   if (isa<ConstantSDNode>(NotZero)) {
115     if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
116       return false;
117   } else if (isa<ConstantFPSDNode>(NotZero)) {
118     if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
119                 convertToAPInt().isAllOnesValue())
120       return false;
121   } else
122     return false;
123   
124   // Okay, we have at least one ~0 value, check to see if the rest match or are
125   // undefs.
126   for (++i; i != e; ++i)
127     if (N->getOperand(i) != NotZero &&
128         N->getOperand(i).getOpcode() != ISD::UNDEF)
129       return false;
130   return true;
131 }
132
133
134 /// isBuildVectorAllZeros - Return true if the specified node is a
135 /// BUILD_VECTOR where all of the elements are 0 or undef.
136 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
137   // Look through a bit convert.
138   if (N->getOpcode() == ISD::BIT_CONVERT)
139     N = N->getOperand(0).Val;
140   
141   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
142   
143   unsigned i = 0, e = N->getNumOperands();
144   
145   // Skip over all of the undef values.
146   while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
147     ++i;
148   
149   // Do not accept an all-undef vector.
150   if (i == e) return false;
151   
152   // Do not accept build_vectors that aren't all constants or which have non-~0
153   // elements.
154   SDOperand Zero = N->getOperand(i);
155   if (isa<ConstantSDNode>(Zero)) {
156     if (!cast<ConstantSDNode>(Zero)->isNullValue())
157       return false;
158   } else if (isa<ConstantFPSDNode>(Zero)) {
159     if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
160       return false;
161   } else
162     return false;
163   
164   // Okay, we have at least one ~0 value, check to see if the rest match or are
165   // undefs.
166   for (++i; i != e; ++i)
167     if (N->getOperand(i) != Zero &&
168         N->getOperand(i).getOpcode() != ISD::UNDEF)
169       return false;
170   return true;
171 }
172
173 /// isScalarToVector - Return true if the specified node is a
174 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
175 /// element is not an undef.
176 bool ISD::isScalarToVector(const SDNode *N) {
177   if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
178     return true;
179
180   if (N->getOpcode() != ISD::BUILD_VECTOR)
181     return false;
182   if (N->getOperand(0).getOpcode() == ISD::UNDEF)
183     return false;
184   unsigned NumElems = N->getNumOperands();
185   for (unsigned i = 1; i < NumElems; ++i) {
186     SDOperand V = N->getOperand(i);
187     if (V.getOpcode() != ISD::UNDEF)
188       return false;
189   }
190   return true;
191 }
192
193
194 /// isDebugLabel - Return true if the specified node represents a debug
195 /// label (i.e. ISD::DBG_LABEL or TargetInstrInfo::DBG_LABEL node).
196 bool ISD::isDebugLabel(const SDNode *N) {
197   SDOperand Zero;
198   if (N->getOpcode() == ISD::DBG_LABEL)
199     return true;
200   if (N->isTargetOpcode() &&
201       N->getTargetOpcode() == TargetInstrInfo::DBG_LABEL)
202     return true;
203   return false;
204 }
205
206 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
207 /// when given the operation for (X op Y).
208 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
209   // To perform this operation, we just need to swap the L and G bits of the
210   // operation.
211   unsigned OldL = (Operation >> 2) & 1;
212   unsigned OldG = (Operation >> 1) & 1;
213   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
214                        (OldL << 1) |       // New G bit
215                        (OldG << 2));        // New L bit.
216 }
217
218 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
219 /// 'op' is a valid SetCC operation.
220 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
221   unsigned Operation = Op;
222   if (isInteger)
223     Operation ^= 7;   // Flip L, G, E bits, but not U.
224   else
225     Operation ^= 15;  // Flip all of the condition bits.
226   if (Operation > ISD::SETTRUE2)
227     Operation &= ~8;     // Don't let N and U bits get set.
228   return ISD::CondCode(Operation);
229 }
230
231
232 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
233 /// signed operation and 2 if the result is an unsigned comparison.  Return zero
234 /// if the operation does not depend on the sign of the input (setne and seteq).
235 static int isSignedOp(ISD::CondCode Opcode) {
236   switch (Opcode) {
237   default: assert(0 && "Illegal integer setcc operation!");
238   case ISD::SETEQ:
239   case ISD::SETNE: return 0;
240   case ISD::SETLT:
241   case ISD::SETLE:
242   case ISD::SETGT:
243   case ISD::SETGE: return 1;
244   case ISD::SETULT:
245   case ISD::SETULE:
246   case ISD::SETUGT:
247   case ISD::SETUGE: return 2;
248   }
249 }
250
251 /// getSetCCOrOperation - Return the result of a logical OR between different
252 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This function
253 /// returns SETCC_INVALID if it is not possible to represent the resultant
254 /// comparison.
255 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
256                                        bool isInteger) {
257   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
258     // Cannot fold a signed integer setcc with an unsigned integer setcc.
259     return ISD::SETCC_INVALID;
260
261   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
262
263   // If the N and U bits get set then the resultant comparison DOES suddenly
264   // care about orderedness, and is true when ordered.
265   if (Op > ISD::SETTRUE2)
266     Op &= ~16;     // Clear the U bit if the N bit is set.
267   
268   // Canonicalize illegal integer setcc's.
269   if (isInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
270     Op = ISD::SETNE;
271   
272   return ISD::CondCode(Op);
273 }
274
275 /// getSetCCAndOperation - Return the result of a logical AND between different
276 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
277 /// function returns zero if it is not possible to represent the resultant
278 /// comparison.
279 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
280                                         bool isInteger) {
281   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
282     // Cannot fold a signed setcc with an unsigned setcc.
283     return ISD::SETCC_INVALID;
284
285   // Combine all of the condition bits.
286   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
287   
288   // Canonicalize illegal integer setcc's.
289   if (isInteger) {
290     switch (Result) {
291     default: break;
292     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
293     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
294     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
295     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
296     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
297     }
298   }
299   
300   return Result;
301 }
302
303 const TargetMachine &SelectionDAG::getTarget() const {
304   return TLI.getTargetMachine();
305 }
306
307 //===----------------------------------------------------------------------===//
308 //                           SDNode Profile Support
309 //===----------------------------------------------------------------------===//
310
311 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
312 ///
313 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
314   ID.AddInteger(OpC);
315 }
316
317 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
318 /// solely with their pointer.
319 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
320   ID.AddPointer(VTList.VTs);  
321 }
322
323 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
324 ///
325 static void AddNodeIDOperands(FoldingSetNodeID &ID,
326                               const SDOperand *Ops, unsigned NumOps) {
327   for (; NumOps; --NumOps, ++Ops) {
328     ID.AddPointer(Ops->Val);
329     ID.AddInteger(Ops->ResNo);
330   }
331 }
332
333 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
334 ///
335 static void AddNodeIDOperands(FoldingSetNodeID &ID,
336                               const SDUse *Ops, unsigned NumOps) {
337   for (; NumOps; --NumOps, ++Ops) {
338     ID.AddPointer(Ops->getSDOperand().Val);
339     ID.AddInteger(Ops->getSDOperand().ResNo);
340   }
341 }
342
343 static void AddNodeIDNode(FoldingSetNodeID &ID,
344                           unsigned short OpC, SDVTList VTList, 
345                           const SDOperand *OpList, unsigned N) {
346   AddNodeIDOpcode(ID, OpC);
347   AddNodeIDValueTypes(ID, VTList);
348   AddNodeIDOperands(ID, OpList, N);
349 }
350
351
352 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
353 /// data.
354 static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
355   AddNodeIDOpcode(ID, N->getOpcode());
356   // Add the return value info.
357   AddNodeIDValueTypes(ID, N->getVTList());
358   // Add the operand info.
359   AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
360
361   // Handle SDNode leafs with special info.
362   switch (N->getOpcode()) {
363   default: break;  // Normal nodes don't need extra info.
364   case ISD::ARG_FLAGS:
365     ID.AddInteger(cast<ARG_FLAGSSDNode>(N)->getArgFlags().getRawBits());
366     break;
367   case ISD::TargetConstant:
368   case ISD::Constant:
369     ID.Add(cast<ConstantSDNode>(N)->getAPIntValue());
370     break;
371   case ISD::TargetConstantFP:
372   case ISD::ConstantFP: {
373     ID.Add(cast<ConstantFPSDNode>(N)->getValueAPF());
374     break;
375   }
376   case ISD::TargetGlobalAddress:
377   case ISD::GlobalAddress:
378   case ISD::TargetGlobalTLSAddress:
379   case ISD::GlobalTLSAddress: {
380     GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
381     ID.AddPointer(GA->getGlobal());
382     ID.AddInteger(GA->getOffset());
383     break;
384   }
385   case ISD::BasicBlock:
386     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
387     break;
388   case ISD::Register:
389     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
390     break;
391   case ISD::DBG_STOPPOINT: {
392     const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(N);
393     ID.AddInteger(DSP->getLine());
394     ID.AddInteger(DSP->getColumn());
395     ID.AddPointer(DSP->getCompileUnit());
396     break;
397   }
398   case ISD::SRCVALUE:
399     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
400     break;
401   case ISD::MEMOPERAND: {
402     const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO;
403     ID.AddPointer(MO.getValue());
404     ID.AddInteger(MO.getFlags());
405     ID.AddInteger(MO.getOffset());
406     ID.AddInteger(MO.getSize());
407     ID.AddInteger(MO.getAlignment());
408     break;
409   }
410   case ISD::FrameIndex:
411   case ISD::TargetFrameIndex:
412     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
413     break;
414   case ISD::JumpTable:
415   case ISD::TargetJumpTable:
416     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
417     break;
418   case ISD::ConstantPool:
419   case ISD::TargetConstantPool: {
420     ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
421     ID.AddInteger(CP->getAlignment());
422     ID.AddInteger(CP->getOffset());
423     if (CP->isMachineConstantPoolEntry())
424       CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
425     else
426       ID.AddPointer(CP->getConstVal());
427     break;
428   }
429   case ISD::LOAD: {
430     LoadSDNode *LD = cast<LoadSDNode>(N);
431     ID.AddInteger(LD->getAddressingMode());
432     ID.AddInteger(LD->getExtensionType());
433     ID.AddInteger(LD->getMemoryVT().getRawBits());
434     ID.AddInteger(LD->getAlignment());
435     ID.AddInteger(LD->isVolatile());
436     break;
437   }
438   case ISD::STORE: {
439     StoreSDNode *ST = cast<StoreSDNode>(N);
440     ID.AddInteger(ST->getAddressingMode());
441     ID.AddInteger(ST->isTruncatingStore());
442     ID.AddInteger(ST->getMemoryVT().getRawBits());
443     ID.AddInteger(ST->getAlignment());
444     ID.AddInteger(ST->isVolatile());
445     break;
446   }
447   case ISD::ATOMIC_CMP_SWAP:
448   case ISD::ATOMIC_LOAD_ADD:
449   case ISD::ATOMIC_SWAP:
450   case ISD::ATOMIC_LOAD_SUB:
451   case ISD::ATOMIC_LOAD_AND:
452   case ISD::ATOMIC_LOAD_OR:
453   case ISD::ATOMIC_LOAD_XOR:
454   case ISD::ATOMIC_LOAD_NAND:
455   case ISD::ATOMIC_LOAD_MIN:
456   case ISD::ATOMIC_LOAD_MAX:
457   case ISD::ATOMIC_LOAD_UMIN:
458   case ISD::ATOMIC_LOAD_UMAX: {
459     AtomicSDNode *AT = cast<AtomicSDNode>(N);
460     ID.AddInteger(AT->getAlignment());
461     ID.AddInteger(AT->isVolatile());
462     break;
463   }
464   } // end switch (N->getOpcode())
465 }
466
467 //===----------------------------------------------------------------------===//
468 //                              SelectionDAG Class
469 //===----------------------------------------------------------------------===//
470
471 inline alist_traits<SDNode, LargestSDNode>::AllocatorType &
472 SelectionDAG::getAllocator() {
473   return AllNodes.getTraits().Allocator;
474 }
475
476 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
477 /// SelectionDAG.
478 void SelectionDAG::RemoveDeadNodes() {
479   // Create a dummy node (which is not added to allnodes), that adds a reference
480   // to the root node, preventing it from being deleted.
481   HandleSDNode Dummy(getRoot());
482
483   SmallVector<SDNode*, 128> DeadNodes;
484   
485   // Add all obviously-dead nodes to the DeadNodes worklist.
486   for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
487     if (I->use_empty())
488       DeadNodes.push_back(I);
489
490   RemoveDeadNodes(DeadNodes);
491   
492   // If the root changed (e.g. it was a dead load, update the root).
493   setRoot(Dummy.getValue());
494 }
495
496 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
497 /// given list, and any nodes that become unreachable as a result.
498 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
499                                    DAGUpdateListener *UpdateListener) {
500
501   // Process the worklist, deleting the nodes and adding their uses to the
502   // worklist.
503   while (!DeadNodes.empty()) {
504     SDNode *N = DeadNodes.back();
505     DeadNodes.pop_back();
506     
507     if (UpdateListener)
508       UpdateListener->NodeDeleted(N, 0);
509     
510     // Take the node out of the appropriate CSE map.
511     RemoveNodeFromCSEMaps(N);
512
513     // Next, brutally remove the operand list.  This is safe to do, as there are
514     // no cycles in the graph.
515     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
516       SDNode *Operand = I->getVal();
517       Operand->removeUser(std::distance(N->op_begin(), I), N);
518       
519       // Now that we removed this operand, see if there are no uses of it left.
520       if (Operand->use_empty())
521         DeadNodes.push_back(Operand);
522     }
523     if (N->OperandsNeedDelete) {
524       delete[] N->OperandList;
525     }
526     N->OperandList = 0;
527     N->NumOperands = 0;
528     
529     // Finally, remove N itself.
530     AllNodes.erase(N);
531   }
532 }
533
534 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
535   SmallVector<SDNode*, 16> DeadNodes;
536   DeadNodes.push_back(N);
537   RemoveDeadNodes(DeadNodes, UpdateListener);
538 }
539
540 void SelectionDAG::DeleteNode(SDNode *N) {
541   assert(N->use_empty() && "Cannot delete a node that is not dead!");
542
543   // First take this out of the appropriate CSE map.
544   RemoveNodeFromCSEMaps(N);
545
546   // Finally, remove uses due to operands of this node, remove from the 
547   // AllNodes list, and delete the node.
548   DeleteNodeNotInCSEMaps(N);
549 }
550
551 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
552
553   // Drop all of the operands and decrement used nodes use counts.
554   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
555     I->getVal()->removeUser(std::distance(N->op_begin(), I), N);
556   if (N->OperandsNeedDelete) {
557     delete[] N->OperandList;
558   }
559   N->OperandList = 0;
560   N->NumOperands = 0;
561   
562   AllNodes.erase(N);
563 }
564
565 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
566 /// correspond to it.  This is useful when we're about to delete or repurpose
567 /// the node.  We don't want future request for structurally identical nodes
568 /// to return N anymore.
569 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
570   bool Erased = false;
571   switch (N->getOpcode()) {
572   case ISD::HANDLENODE: return;  // noop.
573   case ISD::CONDCODE:
574     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
575            "Cond code doesn't exist!");
576     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
577     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
578     break;
579   case ISD::ExternalSymbol:
580     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
581     break;
582   case ISD::TargetExternalSymbol:
583     Erased =
584       TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
585     break;
586   case ISD::VALUETYPE: {
587     MVT VT = cast<VTSDNode>(N)->getVT();
588     if (VT.isExtended()) {
589       Erased = ExtendedValueTypeNodes.erase(VT);
590     } else {
591       Erased = ValueTypeNodes[VT.getSimpleVT()] != 0;
592       ValueTypeNodes[VT.getSimpleVT()] = 0;
593     }
594     break;
595   }
596   default:
597     // Remove it from the CSE Map.
598     Erased = CSEMap.RemoveNode(N);
599     break;
600   }
601 #ifndef NDEBUG
602   // Verify that the node was actually in one of the CSE maps, unless it has a 
603   // flag result (which cannot be CSE'd) or is one of the special cases that are
604   // not subject to CSE.
605   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
606       !N->isTargetOpcode() &&
607       N->getOpcode() != ISD::DBG_LABEL &&
608       N->getOpcode() != ISD::DBG_STOPPOINT &&
609       N->getOpcode() != ISD::EH_LABEL &&
610       N->getOpcode() != ISD::DECLARE) {
611     N->dump(this);
612     cerr << "\n";
613     assert(0 && "Node is not in map!");
614   }
615 #endif
616 }
617
618 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps.  It
619 /// has been taken out and modified in some way.  If the specified node already
620 /// exists in the CSE maps, do not modify the maps, but return the existing node
621 /// instead.  If it doesn't exist, add it and return null.
622 ///
623 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
624   assert(N->getNumOperands() && "This is a leaf node!");
625
626   if (N->getValueType(0) == MVT::Flag)
627     return 0;   // Never CSE anything that produces a flag.
628
629   switch (N->getOpcode()) {
630   default: break;
631   case ISD::HANDLENODE:
632   case ISD::DBG_LABEL:
633   case ISD::DBG_STOPPOINT:
634   case ISD::EH_LABEL:
635   case ISD::DECLARE:
636     return 0;    // Never add these nodes.
637   }
638   
639   // Check that remaining values produced are not flags.
640   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
641     if (N->getValueType(i) == MVT::Flag)
642       return 0;   // Never CSE anything that produces a flag.
643   
644   SDNode *New = CSEMap.GetOrInsertNode(N);
645   if (New != N) return New;  // Node already existed.
646   return 0;
647 }
648
649 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
650 /// were replaced with those specified.  If this node is never memoized, 
651 /// return null, otherwise return a pointer to the slot it would take.  If a
652 /// node already exists with these operands, the slot will be non-null.
653 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
654                                            void *&InsertPos) {
655   if (N->getValueType(0) == MVT::Flag)
656     return 0;   // Never CSE anything that produces a flag.
657
658   switch (N->getOpcode()) {
659   default: break;
660   case ISD::HANDLENODE:
661   case ISD::DBG_LABEL:
662   case ISD::DBG_STOPPOINT:
663   case ISD::EH_LABEL:
664     return 0;    // Never add these nodes.
665   }
666   
667   // Check that remaining values produced are not flags.
668   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
669     if (N->getValueType(i) == MVT::Flag)
670       return 0;   // Never CSE anything that produces a flag.
671   
672   SDOperand Ops[] = { Op };
673   FoldingSetNodeID ID;
674   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
675   return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
676 }
677
678 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
679 /// were replaced with those specified.  If this node is never memoized, 
680 /// return null, otherwise return a pointer to the slot it would take.  If a
681 /// node already exists with these operands, the slot will be non-null.
682 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 
683                                            SDOperand Op1, SDOperand Op2,
684                                            void *&InsertPos) {
685   if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
686   
687   // Check that remaining values produced are not flags.
688   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
689     if (N->getValueType(i) == MVT::Flag)
690       return 0;   // Never CSE anything that produces a flag.
691                                               
692   SDOperand Ops[] = { Op1, Op2 };
693   FoldingSetNodeID ID;
694   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
695   return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
696 }
697
698
699 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
700 /// were replaced with those specified.  If this node is never memoized, 
701 /// return null, otherwise return a pointer to the slot it would take.  If a
702 /// node already exists with these operands, the slot will be non-null.
703 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 
704                                            const SDOperand *Ops,unsigned NumOps,
705                                            void *&InsertPos) {
706   if (N->getValueType(0) == MVT::Flag)
707     return 0;   // Never CSE anything that produces a flag.
708
709   switch (N->getOpcode()) {
710   default: break;
711   case ISD::HANDLENODE:
712   case ISD::DBG_LABEL:
713   case ISD::DBG_STOPPOINT:
714   case ISD::EH_LABEL:
715   case ISD::DECLARE:
716     return 0;    // Never add these nodes.
717   }
718   
719   // Check that remaining values produced are not flags.
720   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
721     if (N->getValueType(i) == MVT::Flag)
722       return 0;   // Never CSE anything that produces a flag.
723   
724   FoldingSetNodeID ID;
725   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
726   
727   if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
728     ID.AddInteger(LD->getAddressingMode());
729     ID.AddInteger(LD->getExtensionType());
730     ID.AddInteger(LD->getMemoryVT().getRawBits());
731     ID.AddInteger(LD->getAlignment());
732     ID.AddInteger(LD->isVolatile());
733   } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
734     ID.AddInteger(ST->getAddressingMode());
735     ID.AddInteger(ST->isTruncatingStore());
736     ID.AddInteger(ST->getMemoryVT().getRawBits());
737     ID.AddInteger(ST->getAlignment());
738     ID.AddInteger(ST->isVolatile());
739   }
740   
741   return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
742 }
743
744
745 SelectionDAG::~SelectionDAG() {
746   while (!AllNodes.empty()) {
747     SDNode *N = AllNodes.begin();
748     N->SetNextInBucket(0);
749     if (N->OperandsNeedDelete) {
750       delete [] N->OperandList;
751     }
752     N->OperandList = 0;
753     N->NumOperands = 0;
754     AllNodes.pop_front();
755   }
756 }
757
758 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT VT) {
759   if (Op.getValueType() == VT) return Op;
760   APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
761                                    VT.getSizeInBits());
762   return getNode(ISD::AND, Op.getValueType(), Op,
763                  getConstant(Imm, Op.getValueType()));
764 }
765
766 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
767   MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
768   return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
769 }
770
771 SDOperand SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
772   assert(VT.isInteger() && "Cannot create FP integer constant!");
773
774   MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
775   assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
776          "APInt size does not match type size!");
777
778   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
779   FoldingSetNodeID ID;
780   AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
781   ID.Add(Val);
782   void *IP = 0;
783   SDNode *N = NULL;
784   if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
785     if (!VT.isVector())
786       return SDOperand(N, 0);
787   if (!N) {
788     N = getAllocator().Allocate<ConstantSDNode>();
789     new (N) ConstantSDNode(isT, Val, EltVT);
790     CSEMap.InsertNode(N, IP);
791     AllNodes.push_back(N);
792   }
793
794   SDOperand Result(N, 0);
795   if (VT.isVector()) {
796     SmallVector<SDOperand, 8> Ops;
797     Ops.assign(VT.getVectorNumElements(), Result);
798     Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
799   }
800   return Result;
801 }
802
803 SDOperand SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
804   return getConstant(Val, TLI.getPointerTy(), isTarget);
805 }
806
807
808 SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
809   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
810                                 
811   MVT EltVT =
812     VT.isVector() ? VT.getVectorElementType() : VT;
813
814   // Do the map lookup using the actual bit pattern for the floating point
815   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
816   // we don't have issues with SNANs.
817   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
818   FoldingSetNodeID ID;
819   AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
820   ID.Add(V);
821   void *IP = 0;
822   SDNode *N = NULL;
823   if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
824     if (!VT.isVector())
825       return SDOperand(N, 0);
826   if (!N) {
827     N = getAllocator().Allocate<ConstantFPSDNode>();
828     new (N) ConstantFPSDNode(isTarget, V, EltVT);
829     CSEMap.InsertNode(N, IP);
830     AllNodes.push_back(N);
831   }
832
833   SDOperand Result(N, 0);
834   if (VT.isVector()) {
835     SmallVector<SDOperand, 8> Ops;
836     Ops.assign(VT.getVectorNumElements(), Result);
837     Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
838   }
839   return Result;
840 }
841
842 SDOperand SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
843   MVT EltVT =
844     VT.isVector() ? VT.getVectorElementType() : VT;
845   if (EltVT==MVT::f32)
846     return getConstantFP(APFloat((float)Val), VT, isTarget);
847   else
848     return getConstantFP(APFloat(Val), VT, isTarget);
849 }
850
851 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
852                                          MVT VT, int Offset,
853                                          bool isTargetGA) {
854   unsigned Opc;
855
856   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
857   if (!GVar) {
858     // If GV is an alias then use the aliasee for determining thread-localness.
859     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
860       GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
861   }
862
863   if (GVar && GVar->isThreadLocal())
864     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
865   else
866     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
867
868   FoldingSetNodeID ID;
869   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
870   ID.AddPointer(GV);
871   ID.AddInteger(Offset);
872   void *IP = 0;
873   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
874    return SDOperand(E, 0);
875   SDNode *N = getAllocator().Allocate<GlobalAddressSDNode>();
876   new (N) GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
877   CSEMap.InsertNode(N, IP);
878   AllNodes.push_back(N);
879   return SDOperand(N, 0);
880 }
881
882 SDOperand SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
883   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
884   FoldingSetNodeID ID;
885   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
886   ID.AddInteger(FI);
887   void *IP = 0;
888   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
889     return SDOperand(E, 0);
890   SDNode *N = getAllocator().Allocate<FrameIndexSDNode>();
891   new (N) FrameIndexSDNode(FI, VT, isTarget);
892   CSEMap.InsertNode(N, IP);
893   AllNodes.push_back(N);
894   return SDOperand(N, 0);
895 }
896
897 SDOperand SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget){
898   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
899   FoldingSetNodeID ID;
900   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
901   ID.AddInteger(JTI);
902   void *IP = 0;
903   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
904     return SDOperand(E, 0);
905   SDNode *N = getAllocator().Allocate<JumpTableSDNode>();
906   new (N) JumpTableSDNode(JTI, VT, isTarget);
907   CSEMap.InsertNode(N, IP);
908   AllNodes.push_back(N);
909   return SDOperand(N, 0);
910 }
911
912 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT VT,
913                                         unsigned Alignment, int Offset,
914                                         bool isTarget) {
915   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
916   FoldingSetNodeID ID;
917   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
918   ID.AddInteger(Alignment);
919   ID.AddInteger(Offset);
920   ID.AddPointer(C);
921   void *IP = 0;
922   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
923     return SDOperand(E, 0);
924   SDNode *N = getAllocator().Allocate<ConstantPoolSDNode>();
925   new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
926   CSEMap.InsertNode(N, IP);
927   AllNodes.push_back(N);
928   return SDOperand(N, 0);
929 }
930
931
932 SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
933                                         unsigned Alignment, int Offset,
934                                         bool isTarget) {
935   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
936   FoldingSetNodeID ID;
937   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
938   ID.AddInteger(Alignment);
939   ID.AddInteger(Offset);
940   C->AddSelectionDAGCSEId(ID);
941   void *IP = 0;
942   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
943     return SDOperand(E, 0);
944   SDNode *N = getAllocator().Allocate<ConstantPoolSDNode>();
945   new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
946   CSEMap.InsertNode(N, IP);
947   AllNodes.push_back(N);
948   return SDOperand(N, 0);
949 }
950
951
952 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
953   FoldingSetNodeID ID;
954   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
955   ID.AddPointer(MBB);
956   void *IP = 0;
957   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
958     return SDOperand(E, 0);
959   SDNode *N = getAllocator().Allocate<BasicBlockSDNode>();
960   new (N) BasicBlockSDNode(MBB);
961   CSEMap.InsertNode(N, IP);
962   AllNodes.push_back(N);
963   return SDOperand(N, 0);
964 }
965
966 SDOperand SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
967   FoldingSetNodeID ID;
968   AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), 0, 0);
969   ID.AddInteger(Flags.getRawBits());
970   void *IP = 0;
971   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
972     return SDOperand(E, 0);
973   SDNode *N = getAllocator().Allocate<ARG_FLAGSSDNode>();
974   new (N) ARG_FLAGSSDNode(Flags);
975   CSEMap.InsertNode(N, IP);
976   AllNodes.push_back(N);
977   return SDOperand(N, 0);
978 }
979
980 SDOperand SelectionDAG::getValueType(MVT VT) {
981   if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
982     ValueTypeNodes.resize(VT.getSimpleVT()+1);
983
984   SDNode *&N = VT.isExtended() ?
985     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
986
987   if (N) return SDOperand(N, 0);
988   N = getAllocator().Allocate<VTSDNode>();
989   new (N) VTSDNode(VT);
990   AllNodes.push_back(N);
991   return SDOperand(N, 0);
992 }
993
994 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
995   SDNode *&N = ExternalSymbols[Sym];
996   if (N) return SDOperand(N, 0);
997   N = getAllocator().Allocate<ExternalSymbolSDNode>();
998   new (N) ExternalSymbolSDNode(false, Sym, VT);
999   AllNodes.push_back(N);
1000   return SDOperand(N, 0);
1001 }
1002
1003 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT) {
1004   SDNode *&N = TargetExternalSymbols[Sym];
1005   if (N) return SDOperand(N, 0);
1006   N = getAllocator().Allocate<ExternalSymbolSDNode>();
1007   new (N) ExternalSymbolSDNode(true, Sym, VT);
1008   AllNodes.push_back(N);
1009   return SDOperand(N, 0);
1010 }
1011
1012 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
1013   if ((unsigned)Cond >= CondCodeNodes.size())
1014     CondCodeNodes.resize(Cond+1);
1015
1016   if (CondCodeNodes[Cond] == 0) {
1017     CondCodeSDNode *N = getAllocator().Allocate<CondCodeSDNode>();
1018     new (N) CondCodeSDNode(Cond);
1019     CondCodeNodes[Cond] = N;
1020     AllNodes.push_back(N);
1021   }
1022   return SDOperand(CondCodeNodes[Cond], 0);
1023 }
1024
1025 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
1026   FoldingSetNodeID ID;
1027   AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
1028   ID.AddInteger(RegNo);
1029   void *IP = 0;
1030   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1031     return SDOperand(E, 0);
1032   SDNode *N = getAllocator().Allocate<RegisterSDNode>();
1033   new (N) RegisterSDNode(RegNo, VT);
1034   CSEMap.InsertNode(N, IP);
1035   AllNodes.push_back(N);
1036   return SDOperand(N, 0);
1037 }
1038
1039 SDOperand SelectionDAG::getDbgStopPoint(SDOperand Root,
1040                                         unsigned Line, unsigned Col,
1041                                         const CompileUnitDesc *CU) {
1042   SDNode *N = getAllocator().Allocate<DbgStopPointSDNode>();
1043   new (N) DbgStopPointSDNode(Root, Line, Col, CU);
1044   AllNodes.push_back(N);
1045   return SDOperand(N, 0);
1046 }
1047
1048 SDOperand SelectionDAG::getLabel(unsigned Opcode,
1049                                  SDOperand Root,
1050                                  unsigned LabelID) {
1051   FoldingSetNodeID ID;
1052   SDOperand Ops[] = { Root };
1053   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1054   ID.AddInteger(LabelID);
1055   void *IP = 0;
1056   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1057     return SDOperand(E, 0);
1058   SDNode *N = getAllocator().Allocate<LabelSDNode>();
1059   new (N) LabelSDNode(Opcode, Root, LabelID);
1060   CSEMap.InsertNode(N, IP);
1061   AllNodes.push_back(N);
1062   return SDOperand(N, 0);
1063 }
1064
1065 SDOperand SelectionDAG::getSrcValue(const Value *V) {
1066   assert((!V || isa<PointerType>(V->getType())) &&
1067          "SrcValue is not a pointer?");
1068
1069   FoldingSetNodeID ID;
1070   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1071   ID.AddPointer(V);
1072
1073   void *IP = 0;
1074   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1075     return SDOperand(E, 0);
1076
1077   SDNode *N = getAllocator().Allocate<SrcValueSDNode>();
1078   new (N) SrcValueSDNode(V);
1079   CSEMap.InsertNode(N, IP);
1080   AllNodes.push_back(N);
1081   return SDOperand(N, 0);
1082 }
1083
1084 SDOperand SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1085   const Value *v = MO.getValue();
1086   assert((!v || isa<PointerType>(v->getType())) &&
1087          "SrcValue is not a pointer?");
1088
1089   FoldingSetNodeID ID;
1090   AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
1091   ID.AddPointer(v);
1092   ID.AddInteger(MO.getFlags());
1093   ID.AddInteger(MO.getOffset());
1094   ID.AddInteger(MO.getSize());
1095   ID.AddInteger(MO.getAlignment());
1096
1097   void *IP = 0;
1098   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1099     return SDOperand(E, 0);
1100
1101   SDNode *N = getAllocator().Allocate<MemOperandSDNode>();
1102   new (N) MemOperandSDNode(MO);
1103   CSEMap.InsertNode(N, IP);
1104   AllNodes.push_back(N);
1105   return SDOperand(N, 0);
1106 }
1107
1108 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1109 /// specified value type.
1110 SDOperand SelectionDAG::CreateStackTemporary(MVT VT, unsigned minAlign) {
1111   MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1112   unsigned ByteSize = VT.getSizeInBits()/8;
1113   const Type *Ty = VT.getTypeForMVT();
1114   unsigned StackAlign =
1115   std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1116   
1117   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1118   return getFrameIndex(FrameIdx, TLI.getPointerTy());
1119 }
1120
1121 SDOperand SelectionDAG::FoldSetCC(MVT VT, SDOperand N1,
1122                                   SDOperand N2, ISD::CondCode Cond) {
1123   // These setcc operations always fold.
1124   switch (Cond) {
1125   default: break;
1126   case ISD::SETFALSE:
1127   case ISD::SETFALSE2: return getConstant(0, VT);
1128   case ISD::SETTRUE:
1129   case ISD::SETTRUE2:  return getConstant(1, VT);
1130     
1131   case ISD::SETOEQ:
1132   case ISD::SETOGT:
1133   case ISD::SETOGE:
1134   case ISD::SETOLT:
1135   case ISD::SETOLE:
1136   case ISD::SETONE:
1137   case ISD::SETO:
1138   case ISD::SETUO:
1139   case ISD::SETUEQ:
1140   case ISD::SETUNE:
1141     assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1142     break;
1143   }
1144   
1145   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
1146     const APInt &C2 = N2C->getAPIntValue();
1147     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1148       const APInt &C1 = N1C->getAPIntValue();
1149       
1150       switch (Cond) {
1151       default: assert(0 && "Unknown integer setcc!");
1152       case ISD::SETEQ:  return getConstant(C1 == C2, VT);
1153       case ISD::SETNE:  return getConstant(C1 != C2, VT);
1154       case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1155       case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1156       case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1157       case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1158       case ISD::SETLT:  return getConstant(C1.slt(C2), VT);
1159       case ISD::SETGT:  return getConstant(C1.sgt(C2), VT);
1160       case ISD::SETLE:  return getConstant(C1.sle(C2), VT);
1161       case ISD::SETGE:  return getConstant(C1.sge(C2), VT);
1162       }
1163     }
1164   }
1165   if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val)) {
1166     if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
1167       // No compile time operations on this type yet.
1168       if (N1C->getValueType(0) == MVT::ppcf128)
1169         return SDOperand();
1170
1171       APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1172       switch (Cond) {
1173       default: break;
1174       case ISD::SETEQ:  if (R==APFloat::cmpUnordered) 
1175                           return getNode(ISD::UNDEF, VT);
1176                         // fall through
1177       case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1178       case ISD::SETNE:  if (R==APFloat::cmpUnordered) 
1179                           return getNode(ISD::UNDEF, VT);
1180                         // fall through
1181       case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1182                                            R==APFloat::cmpLessThan, VT);
1183       case ISD::SETLT:  if (R==APFloat::cmpUnordered) 
1184                           return getNode(ISD::UNDEF, VT);
1185                         // fall through
1186       case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1187       case ISD::SETGT:  if (R==APFloat::cmpUnordered) 
1188                           return getNode(ISD::UNDEF, VT);
1189                         // fall through
1190       case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1191       case ISD::SETLE:  if (R==APFloat::cmpUnordered) 
1192                           return getNode(ISD::UNDEF, VT);
1193                         // fall through
1194       case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1195                                            R==APFloat::cmpEqual, VT);
1196       case ISD::SETGE:  if (R==APFloat::cmpUnordered) 
1197                           return getNode(ISD::UNDEF, VT);
1198                         // fall through
1199       case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1200                                            R==APFloat::cmpEqual, VT);
1201       case ISD::SETO:   return getConstant(R!=APFloat::cmpUnordered, VT);
1202       case ISD::SETUO:  return getConstant(R==APFloat::cmpUnordered, VT);
1203       case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1204                                            R==APFloat::cmpEqual, VT);
1205       case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1206       case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1207                                            R==APFloat::cmpLessThan, VT);
1208       case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1209                                            R==APFloat::cmpUnordered, VT);
1210       case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1211       case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1212       }
1213     } else {
1214       // Ensure that the constant occurs on the RHS.
1215       return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1216     }
1217   }
1218
1219   // Could not fold it.
1220   return SDOperand();
1221 }
1222
1223 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
1224 /// use this predicate to simplify operations downstream.
1225 bool SelectionDAG::SignBitIsZero(SDOperand Op, unsigned Depth) const {
1226   unsigned BitWidth = Op.getValueSizeInBits();
1227   return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1228 }
1229
1230 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
1231 /// this predicate to simplify operations downstream.  Mask is known to be zero
1232 /// for bits that V cannot have.
1233 bool SelectionDAG::MaskedValueIsZero(SDOperand Op, const APInt &Mask, 
1234                                      unsigned Depth) const {
1235   APInt KnownZero, KnownOne;
1236   ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1237   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1238   return (KnownZero & Mask) == Mask;
1239 }
1240
1241 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1242 /// known to be either zero or one and return them in the KnownZero/KnownOne
1243 /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
1244 /// processing.
1245 void SelectionDAG::ComputeMaskedBits(SDOperand Op, const APInt &Mask, 
1246                                      APInt &KnownZero, APInt &KnownOne,
1247                                      unsigned Depth) const {
1248   unsigned BitWidth = Mask.getBitWidth();
1249   assert(BitWidth == Op.getValueType().getSizeInBits() &&
1250          "Mask size mismatches value type size!");
1251
1252   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
1253   if (Depth == 6 || Mask == 0)
1254     return;  // Limit search depth.
1255   
1256   APInt KnownZero2, KnownOne2;
1257
1258   switch (Op.getOpcode()) {
1259   case ISD::Constant:
1260     // We know all of the bits for a constant!
1261     KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1262     KnownZero = ~KnownOne & Mask;
1263     return;
1264   case ISD::AND:
1265     // If either the LHS or the RHS are Zero, the result is zero.
1266     ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1267     ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1268                       KnownZero2, KnownOne2, Depth+1);
1269     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1270     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1271
1272     // Output known-1 bits are only known if set in both the LHS & RHS.
1273     KnownOne &= KnownOne2;
1274     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1275     KnownZero |= KnownZero2;
1276     return;
1277   case ISD::OR:
1278     ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1279     ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1280                       KnownZero2, KnownOne2, Depth+1);
1281     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1282     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1283     
1284     // Output known-0 bits are only known if clear in both the LHS & RHS.
1285     KnownZero &= KnownZero2;
1286     // Output known-1 are known to be set if set in either the LHS | RHS.
1287     KnownOne |= KnownOne2;
1288     return;
1289   case ISD::XOR: {
1290     ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1291     ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1292     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1293     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1294     
1295     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1296     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1297     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1298     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1299     KnownZero = KnownZeroOut;
1300     return;
1301   }
1302   case ISD::MUL: {
1303     APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1304     ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1305     ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1306     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1307     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1308
1309     // If low bits are zero in either operand, output low known-0 bits.
1310     // Also compute a conserative estimate for high known-0 bits.
1311     // More trickiness is possible, but this is sufficient for the
1312     // interesting case of alignment computation.
1313     KnownOne.clear();
1314     unsigned TrailZ = KnownZero.countTrailingOnes() +
1315                       KnownZero2.countTrailingOnes();
1316     unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
1317                                KnownZero2.countLeadingOnes(),
1318                                BitWidth) - BitWidth;
1319
1320     TrailZ = std::min(TrailZ, BitWidth);
1321     LeadZ = std::min(LeadZ, BitWidth);
1322     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1323                 APInt::getHighBitsSet(BitWidth, LeadZ);
1324     KnownZero &= Mask;
1325     return;
1326   }
1327   case ISD::UDIV: {
1328     // For the purposes of computing leading zeros we can conservatively
1329     // treat a udiv as a logical right shift by the power of 2 known to
1330     // be less than the denominator.
1331     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1332     ComputeMaskedBits(Op.getOperand(0),
1333                       AllOnes, KnownZero2, KnownOne2, Depth+1);
1334     unsigned LeadZ = KnownZero2.countLeadingOnes();
1335
1336     KnownOne2.clear();
1337     KnownZero2.clear();
1338     ComputeMaskedBits(Op.getOperand(1),
1339                       AllOnes, KnownZero2, KnownOne2, Depth+1);
1340     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1341     if (RHSUnknownLeadingOnes != BitWidth)
1342       LeadZ = std::min(BitWidth,
1343                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1344
1345     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1346     return;
1347   }
1348   case ISD::SELECT:
1349     ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1350     ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1351     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1352     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1353     
1354     // Only known if known in both the LHS and RHS.
1355     KnownOne &= KnownOne2;
1356     KnownZero &= KnownZero2;
1357     return;
1358   case ISD::SELECT_CC:
1359     ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1360     ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1361     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1362     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1363     
1364     // Only known if known in both the LHS and RHS.
1365     KnownOne &= KnownOne2;
1366     KnownZero &= KnownZero2;
1367     return;
1368   case ISD::SETCC:
1369     // If we know the result of a setcc has the top bits zero, use this info.
1370     if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult &&
1371         BitWidth > 1)
1372       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1373     return;
1374   case ISD::SHL:
1375     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
1376     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1377       unsigned ShAmt = SA->getValue();
1378
1379       // If the shift count is an invalid immediate, don't do anything.
1380       if (ShAmt >= BitWidth)
1381         return;
1382
1383       ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1384                         KnownZero, KnownOne, Depth+1);
1385       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1386       KnownZero <<= ShAmt;
1387       KnownOne  <<= ShAmt;
1388       // low bits known zero.
1389       KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1390     }
1391     return;
1392   case ISD::SRL:
1393     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
1394     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1395       unsigned ShAmt = SA->getValue();
1396
1397       // If the shift count is an invalid immediate, don't do anything.
1398       if (ShAmt >= BitWidth)
1399         return;
1400
1401       ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1402                         KnownZero, KnownOne, Depth+1);
1403       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1404       KnownZero = KnownZero.lshr(ShAmt);
1405       KnownOne  = KnownOne.lshr(ShAmt);
1406
1407       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1408       KnownZero |= HighBits;  // High bits known zero.
1409     }
1410     return;
1411   case ISD::SRA:
1412     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1413       unsigned ShAmt = SA->getValue();
1414
1415       // If the shift count is an invalid immediate, don't do anything.
1416       if (ShAmt >= BitWidth)
1417         return;
1418
1419       APInt InDemandedMask = (Mask << ShAmt);
1420       // If any of the demanded bits are produced by the sign extension, we also
1421       // demand the input sign bit.
1422       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1423       if (HighBits.getBoolValue())
1424         InDemandedMask |= APInt::getSignBit(BitWidth);
1425       
1426       ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1427                         Depth+1);
1428       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1429       KnownZero = KnownZero.lshr(ShAmt);
1430       KnownOne  = KnownOne.lshr(ShAmt);
1431       
1432       // Handle the sign bits.
1433       APInt SignBit = APInt::getSignBit(BitWidth);
1434       SignBit = SignBit.lshr(ShAmt);  // Adjust to where it is now in the mask.
1435       
1436       if (KnownZero.intersects(SignBit)) {
1437         KnownZero |= HighBits;  // New bits are known zero.
1438       } else if (KnownOne.intersects(SignBit)) {
1439         KnownOne  |= HighBits;  // New bits are known one.
1440       }
1441     }
1442     return;
1443   case ISD::SIGN_EXTEND_INREG: {
1444     MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1445     unsigned EBits = EVT.getSizeInBits();
1446     
1447     // Sign extension.  Compute the demanded bits in the result that are not 
1448     // present in the input.
1449     APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1450
1451     APInt InSignBit = APInt::getSignBit(EBits);
1452     APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1453     
1454     // If the sign extended bits are demanded, we know that the sign
1455     // bit is demanded.
1456     InSignBit.zext(BitWidth);
1457     if (NewBits.getBoolValue())
1458       InputDemandedBits |= InSignBit;
1459     
1460     ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1461                       KnownZero, KnownOne, Depth+1);
1462     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1463     
1464     // If the sign bit of the input is known set or clear, then we know the
1465     // top bits of the result.
1466     if (KnownZero.intersects(InSignBit)) {         // Input sign bit known clear
1467       KnownZero |= NewBits;
1468       KnownOne  &= ~NewBits;
1469     } else if (KnownOne.intersects(InSignBit)) {   // Input sign bit known set
1470       KnownOne  |= NewBits;
1471       KnownZero &= ~NewBits;
1472     } else {                              // Input sign bit unknown
1473       KnownZero &= ~NewBits;
1474       KnownOne  &= ~NewBits;
1475     }
1476     return;
1477   }
1478   case ISD::CTTZ:
1479   case ISD::CTLZ:
1480   case ISD::CTPOP: {
1481     unsigned LowBits = Log2_32(BitWidth)+1;
1482     KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1483     KnownOne.clear();
1484     return;
1485   }
1486   case ISD::LOAD: {
1487     if (ISD::isZEXTLoad(Op.Val)) {
1488       LoadSDNode *LD = cast<LoadSDNode>(Op);
1489       MVT VT = LD->getMemoryVT();
1490       unsigned MemBits = VT.getSizeInBits();
1491       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1492     }
1493     return;
1494   }
1495   case ISD::ZERO_EXTEND: {
1496     MVT InVT = Op.getOperand(0).getValueType();
1497     unsigned InBits = InVT.getSizeInBits();
1498     APInt NewBits   = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1499     APInt InMask    = Mask;
1500     InMask.trunc(InBits);
1501     KnownZero.trunc(InBits);
1502     KnownOne.trunc(InBits);
1503     ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1504     KnownZero.zext(BitWidth);
1505     KnownOne.zext(BitWidth);
1506     KnownZero |= NewBits;
1507     return;
1508   }
1509   case ISD::SIGN_EXTEND: {
1510     MVT InVT = Op.getOperand(0).getValueType();
1511     unsigned InBits = InVT.getSizeInBits();
1512     APInt InSignBit = APInt::getSignBit(InBits);
1513     APInt NewBits   = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1514     APInt InMask = Mask;
1515     InMask.trunc(InBits);
1516
1517     // If any of the sign extended bits are demanded, we know that the sign
1518     // bit is demanded. Temporarily set this bit in the mask for our callee.
1519     if (NewBits.getBoolValue())
1520       InMask |= InSignBit;
1521
1522     KnownZero.trunc(InBits);
1523     KnownOne.trunc(InBits);
1524     ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1525
1526     // Note if the sign bit is known to be zero or one.
1527     bool SignBitKnownZero = KnownZero.isNegative();
1528     bool SignBitKnownOne  = KnownOne.isNegative();
1529     assert(!(SignBitKnownZero && SignBitKnownOne) &&
1530            "Sign bit can't be known to be both zero and one!");
1531
1532     // If the sign bit wasn't actually demanded by our caller, we don't
1533     // want it set in the KnownZero and KnownOne result values. Reset the
1534     // mask and reapply it to the result values.
1535     InMask = Mask;
1536     InMask.trunc(InBits);
1537     KnownZero &= InMask;
1538     KnownOne  &= InMask;
1539
1540     KnownZero.zext(BitWidth);
1541     KnownOne.zext(BitWidth);
1542
1543     // If the sign bit is known zero or one, the top bits match.
1544     if (SignBitKnownZero)
1545       KnownZero |= NewBits;
1546     else if (SignBitKnownOne)
1547       KnownOne  |= NewBits;
1548     return;
1549   }
1550   case ISD::ANY_EXTEND: {
1551     MVT InVT = Op.getOperand(0).getValueType();
1552     unsigned InBits = InVT.getSizeInBits();
1553     APInt InMask = Mask;
1554     InMask.trunc(InBits);
1555     KnownZero.trunc(InBits);
1556     KnownOne.trunc(InBits);
1557     ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1558     KnownZero.zext(BitWidth);
1559     KnownOne.zext(BitWidth);
1560     return;
1561   }
1562   case ISD::TRUNCATE: {
1563     MVT InVT = Op.getOperand(0).getValueType();
1564     unsigned InBits = InVT.getSizeInBits();
1565     APInt InMask = Mask;
1566     InMask.zext(InBits);
1567     KnownZero.zext(InBits);
1568     KnownOne.zext(InBits);
1569     ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1570     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1571     KnownZero.trunc(BitWidth);
1572     KnownOne.trunc(BitWidth);
1573     break;
1574   }
1575   case ISD::AssertZext: {
1576     MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1577     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1578     ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero, 
1579                       KnownOne, Depth+1);
1580     KnownZero |= (~InMask) & Mask;
1581     return;
1582   }
1583   case ISD::FGETSIGN:
1584     // All bits are zero except the low bit.
1585     KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1586     return;
1587   
1588   case ISD::SUB: {
1589     if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1590       // We know that the top bits of C-X are clear if X contains less bits
1591       // than C (i.e. no wrap-around can happen).  For example, 20-X is
1592       // positive if we can prove that X is >= 0 and < 16.
1593       if (CLHS->getAPIntValue().isNonNegative()) {
1594         unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1595         // NLZ can't be BitWidth with no sign bit
1596         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1597         ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1598                           Depth+1);
1599
1600         // If all of the MaskV bits are known to be zero, then we know the
1601         // output top bits are zero, because we now know that the output is
1602         // from [0-C].
1603         if ((KnownZero2 & MaskV) == MaskV) {
1604           unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1605           // Top bits known zero.
1606           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1607         }
1608       }
1609     }
1610   }
1611   // fall through
1612   case ISD::ADD: {
1613     // Output known-0 bits are known if clear or set in both the low clear bits
1614     // common to both LHS & RHS.  For example, 8+(X<<3) is known to have the
1615     // low 3 bits clear.
1616     APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1617     ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1618     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1619     unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1620
1621     ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1622     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1623     KnownZeroOut = std::min(KnownZeroOut,
1624                             KnownZero2.countTrailingOnes());
1625
1626     KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1627     return;
1628   }
1629   case ISD::SREM:
1630     if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1631       const APInt &RA = Rem->getAPIntValue();
1632       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1633         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1634         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1635         ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1636
1637         // The sign of a remainder is equal to the sign of the first
1638         // operand (zero being positive).
1639         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1640           KnownZero2 |= ~LowBits;
1641         else if (KnownOne2[BitWidth-1])
1642           KnownOne2 |= ~LowBits;
1643
1644         KnownZero |= KnownZero2 & Mask;
1645         KnownOne |= KnownOne2 & Mask;
1646
1647         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1648       }
1649     }
1650     return;
1651   case ISD::UREM: {
1652     if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1653       const APInt &RA = Rem->getAPIntValue();
1654       if (RA.isPowerOf2()) {
1655         APInt LowBits = (RA - 1);
1656         APInt Mask2 = LowBits & Mask;
1657         KnownZero |= ~LowBits & Mask;
1658         ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1659         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1660         break;
1661       }
1662     }
1663
1664     // Since the result is less than or equal to either operand, any leading
1665     // zero bits in either operand must also exist in the result.
1666     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1667     ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1668                       Depth+1);
1669     ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1670                       Depth+1);
1671
1672     uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1673                                 KnownZero2.countLeadingOnes());
1674     KnownOne.clear();
1675     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1676     return;
1677   }
1678   default:
1679     // Allow the target to implement this method for its nodes.
1680     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1681   case ISD::INTRINSIC_WO_CHAIN:
1682   case ISD::INTRINSIC_W_CHAIN:
1683   case ISD::INTRINSIC_VOID:
1684       TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1685     }
1686     return;
1687   }
1688 }
1689
1690 /// ComputeNumSignBits - Return the number of times the sign bit of the
1691 /// register is replicated into the other bits.  We know that at least 1 bit
1692 /// is always equal to the sign bit (itself), but other cases can give us
1693 /// information.  For example, immediately after an "SRA X, 2", we know that
1694 /// the top 3 bits are all equal to each other, so we return 3.
1695 unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
1696   MVT VT = Op.getValueType();
1697   assert(VT.isInteger() && "Invalid VT!");
1698   unsigned VTBits = VT.getSizeInBits();
1699   unsigned Tmp, Tmp2;
1700   unsigned FirstAnswer = 1;
1701   
1702   if (Depth == 6)
1703     return 1;  // Limit search depth.
1704
1705   switch (Op.getOpcode()) {
1706   default: break;
1707   case ISD::AssertSext:
1708     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1709     return VTBits-Tmp+1;
1710   case ISD::AssertZext:
1711     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1712     return VTBits-Tmp;
1713     
1714   case ISD::Constant: {
1715     const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1716     // If negative, return # leading ones.
1717     if (Val.isNegative())
1718       return Val.countLeadingOnes();
1719     
1720     // Return # leading zeros.
1721     return Val.countLeadingZeros();
1722   }
1723     
1724   case ISD::SIGN_EXTEND:
1725     Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
1726     return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1727     
1728   case ISD::SIGN_EXTEND_INREG:
1729     // Max of the input and what this extends.
1730     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1731     Tmp = VTBits-Tmp+1;
1732     
1733     Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1734     return std::max(Tmp, Tmp2);
1735
1736   case ISD::SRA:
1737     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1738     // SRA X, C   -> adds C sign bits.
1739     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1740       Tmp += C->getValue();
1741       if (Tmp > VTBits) Tmp = VTBits;
1742     }
1743     return Tmp;
1744   case ISD::SHL:
1745     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1746       // shl destroys sign bits.
1747       Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1748       if (C->getValue() >= VTBits ||      // Bad shift.
1749           C->getValue() >= Tmp) break;    // Shifted all sign bits out.
1750       return Tmp - C->getValue();
1751     }
1752     break;
1753   case ISD::AND:
1754   case ISD::OR:
1755   case ISD::XOR:    // NOT is handled here.
1756     // Logical binary ops preserve the number of sign bits at the worst.
1757     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1758     if (Tmp != 1) {
1759       Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1760       FirstAnswer = std::min(Tmp, Tmp2);
1761       // We computed what we know about the sign bits as our first
1762       // answer. Now proceed to the generic code that uses
1763       // ComputeMaskedBits, and pick whichever answer is better.
1764     }
1765     break;
1766
1767   case ISD::SELECT:
1768     Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1769     if (Tmp == 1) return 1;  // Early out.
1770     Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
1771     return std::min(Tmp, Tmp2);
1772     
1773   case ISD::SETCC:
1774     // If setcc returns 0/-1, all bits are sign bits.
1775     if (TLI.getSetCCResultContents() ==
1776         TargetLowering::ZeroOrNegativeOneSetCCResult)
1777       return VTBits;
1778     break;
1779   case ISD::ROTL:
1780   case ISD::ROTR:
1781     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1782       unsigned RotAmt = C->getValue() & (VTBits-1);
1783       
1784       // Handle rotate right by N like a rotate left by 32-N.
1785       if (Op.getOpcode() == ISD::ROTR)
1786         RotAmt = (VTBits-RotAmt) & (VTBits-1);
1787
1788       // If we aren't rotating out all of the known-in sign bits, return the
1789       // number that are left.  This handles rotl(sext(x), 1) for example.
1790       Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1791       if (Tmp > RotAmt+1) return Tmp-RotAmt;
1792     }
1793     break;
1794   case ISD::ADD:
1795     // Add can have at most one carry bit.  Thus we know that the output
1796     // is, at worst, one more bit than the inputs.
1797     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1798     if (Tmp == 1) return 1;  // Early out.
1799       
1800     // Special case decrementing a value (ADD X, -1):
1801     if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1802       if (CRHS->isAllOnesValue()) {
1803         APInt KnownZero, KnownOne;
1804         APInt Mask = APInt::getAllOnesValue(VTBits);
1805         ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1806         
1807         // If the input is known to be 0 or 1, the output is 0/-1, which is all
1808         // sign bits set.
1809         if ((KnownZero | APInt(VTBits, 1)) == Mask)
1810           return VTBits;
1811         
1812         // If we are subtracting one from a positive number, there is no carry
1813         // out of the result.
1814         if (KnownZero.isNegative())
1815           return Tmp;
1816       }
1817       
1818     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1819     if (Tmp2 == 1) return 1;
1820       return std::min(Tmp, Tmp2)-1;
1821     break;
1822     
1823   case ISD::SUB:
1824     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1825     if (Tmp2 == 1) return 1;
1826       
1827     // Handle NEG.
1828     if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1829       if (CLHS->isNullValue()) {
1830         APInt KnownZero, KnownOne;
1831         APInt Mask = APInt::getAllOnesValue(VTBits);
1832         ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1833         // If the input is known to be 0 or 1, the output is 0/-1, which is all
1834         // sign bits set.
1835         if ((KnownZero | APInt(VTBits, 1)) == Mask)
1836           return VTBits;
1837         
1838         // If the input is known to be positive (the sign bit is known clear),
1839         // the output of the NEG has the same number of sign bits as the input.
1840         if (KnownZero.isNegative())
1841           return Tmp2;
1842         
1843         // Otherwise, we treat this like a SUB.
1844       }
1845     
1846     // Sub can have at most one carry bit.  Thus we know that the output
1847     // is, at worst, one more bit than the inputs.
1848     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1849     if (Tmp == 1) return 1;  // Early out.
1850       return std::min(Tmp, Tmp2)-1;
1851     break;
1852   case ISD::TRUNCATE:
1853     // FIXME: it's tricky to do anything useful for this, but it is an important
1854     // case for targets like X86.
1855     break;
1856   }
1857   
1858   // Handle LOADX separately here. EXTLOAD case will fallthrough.
1859   if (Op.getOpcode() == ISD::LOAD) {
1860     LoadSDNode *LD = cast<LoadSDNode>(Op);
1861     unsigned ExtType = LD->getExtensionType();
1862     switch (ExtType) {
1863     default: break;
1864     case ISD::SEXTLOAD:    // '17' bits known
1865       Tmp = LD->getMemoryVT().getSizeInBits();
1866       return VTBits-Tmp+1;
1867     case ISD::ZEXTLOAD:    // '16' bits known
1868       Tmp = LD->getMemoryVT().getSizeInBits();
1869       return VTBits-Tmp;
1870     }
1871   }
1872
1873   // Allow the target to implement this method for its nodes.
1874   if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1875       Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 
1876       Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1877       Op.getOpcode() == ISD::INTRINSIC_VOID) {
1878     unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1879     if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
1880   }
1881   
1882   // Finally, if we can prove that the top bits of the result are 0's or 1's,
1883   // use this information.
1884   APInt KnownZero, KnownOne;
1885   APInt Mask = APInt::getAllOnesValue(VTBits);
1886   ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1887   
1888   if (KnownZero.isNegative()) {        // sign bit is 0
1889     Mask = KnownZero;
1890   } else if (KnownOne.isNegative()) {  // sign bit is 1;
1891     Mask = KnownOne;
1892   } else {
1893     // Nothing known.
1894     return FirstAnswer;
1895   }
1896   
1897   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
1898   // the number of identical bits in the top of the input value.
1899   Mask = ~Mask;
1900   Mask <<= Mask.getBitWidth()-VTBits;
1901   // Return # leading zeros.  We use 'min' here in case Val was zero before
1902   // shifting.  We don't want to return '64' as for an i32 "0".
1903   return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
1904 }
1905
1906
1907 bool SelectionDAG::isVerifiedDebugInfoDesc(SDOperand Op) const {
1908   GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1909   if (!GA) return false;
1910   GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
1911   if (!GV) return false;
1912   MachineModuleInfo *MMI = getMachineModuleInfo();
1913   return MMI && MMI->hasDebugInfo() && MMI->isVerified(GV);
1914 }
1915
1916
1917 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
1918 /// element of the result of the vector shuffle.
1919 SDOperand SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned i) {
1920   MVT VT = N->getValueType(0);
1921   SDOperand PermMask = N->getOperand(2);
1922   SDOperand Idx = PermMask.getOperand(i);
1923   if (Idx.getOpcode() == ISD::UNDEF)
1924     return getNode(ISD::UNDEF, VT.getVectorElementType());
1925   unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
1926   unsigned NumElems = PermMask.getNumOperands();
1927   SDOperand V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
1928   Index %= NumElems;
1929
1930   if (V.getOpcode() == ISD::BIT_CONVERT) {
1931     V = V.getOperand(0);
1932     if (V.getValueType().getVectorNumElements() != NumElems)
1933       return SDOperand();
1934   }
1935   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
1936     return (Index == 0) ? V.getOperand(0)
1937                       : getNode(ISD::UNDEF, VT.getVectorElementType());
1938   if (V.getOpcode() == ISD::BUILD_VECTOR)
1939     return V.getOperand(Index);
1940   if (V.getOpcode() == ISD::VECTOR_SHUFFLE)
1941     return getShuffleScalarElt(V.Val, Index);
1942   return SDOperand();
1943 }
1944
1945
1946 /// getNode - Gets or creates the specified node.
1947 ///
1948 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT) {
1949   FoldingSetNodeID ID;
1950   AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
1951   void *IP = 0;
1952   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1953     return SDOperand(E, 0);
1954   SDNode *N = getAllocator().Allocate<SDNode>();
1955   new (N) SDNode(Opcode, SDNode::getSDVTList(VT));
1956   CSEMap.InsertNode(N, IP);
1957   
1958   AllNodes.push_back(N);
1959   return SDOperand(N, 0);
1960 }
1961
1962 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT, SDOperand Operand) {
1963   // Constant fold unary operations with an integer constant operand.
1964   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1965     const APInt &Val = C->getAPIntValue();
1966     unsigned BitWidth = VT.getSizeInBits();
1967     switch (Opcode) {
1968     default: break;
1969     case ISD::SIGN_EXTEND:
1970       return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
1971     case ISD::ANY_EXTEND:
1972     case ISD::ZERO_EXTEND:
1973     case ISD::TRUNCATE:
1974       return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
1975     case ISD::UINT_TO_FP:
1976     case ISD::SINT_TO_FP: {
1977       const uint64_t zero[] = {0, 0};
1978       // No compile time operations on this type.
1979       if (VT==MVT::ppcf128)
1980         break;
1981       APFloat apf = APFloat(APInt(BitWidth, 2, zero));
1982       (void)apf.convertFromAPInt(Val, 
1983                                  Opcode==ISD::SINT_TO_FP,
1984                                  APFloat::rmNearestTiesToEven);
1985       return getConstantFP(apf, VT);
1986     }
1987     case ISD::BIT_CONVERT:
1988       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
1989         return getConstantFP(Val.bitsToFloat(), VT);
1990       else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
1991         return getConstantFP(Val.bitsToDouble(), VT);
1992       break;
1993     case ISD::BSWAP:
1994       return getConstant(Val.byteSwap(), VT);
1995     case ISD::CTPOP:
1996       return getConstant(Val.countPopulation(), VT);
1997     case ISD::CTLZ:
1998       return getConstant(Val.countLeadingZeros(), VT);
1999     case ISD::CTTZ:
2000       return getConstant(Val.countTrailingZeros(), VT);
2001     }
2002   }
2003
2004   // Constant fold unary operations with a floating point constant operand.
2005   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
2006     APFloat V = C->getValueAPF();    // make copy
2007     if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
2008       switch (Opcode) {
2009       case ISD::FNEG:
2010         V.changeSign();
2011         return getConstantFP(V, VT);
2012       case ISD::FABS:
2013         V.clearSign();
2014         return getConstantFP(V, VT);
2015       case ISD::FP_ROUND:
2016       case ISD::FP_EXTEND:
2017         // This can return overflow, underflow, or inexact; we don't care.
2018         // FIXME need to be more flexible about rounding mode.
2019         (void)V.convert(*MVTToAPFloatSemantics(VT),
2020                         APFloat::rmNearestTiesToEven);
2021         return getConstantFP(V, VT);
2022       case ISD::FP_TO_SINT:
2023       case ISD::FP_TO_UINT: {
2024         integerPart x;
2025         assert(integerPartWidth >= 64);
2026         // FIXME need to be more flexible about rounding mode.
2027         APFloat::opStatus s = V.convertToInteger(&x, 64U,
2028                               Opcode==ISD::FP_TO_SINT,
2029                               APFloat::rmTowardZero);
2030         if (s==APFloat::opInvalidOp)     // inexact is OK, in fact usual
2031           break;
2032         return getConstant(x, VT);
2033       }
2034       case ISD::BIT_CONVERT:
2035         if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2036           return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
2037         else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2038           return getConstant(V.convertToAPInt().getZExtValue(), VT);
2039         break;
2040       }
2041     }
2042   }
2043
2044   unsigned OpOpcode = Operand.Val->getOpcode();
2045   switch (Opcode) {
2046   case ISD::TokenFactor:
2047     return Operand;         // Factor of one node?  No need.
2048   case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
2049   case ISD::FP_EXTEND:
2050     assert(VT.isFloatingPoint() &&
2051            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2052     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
2053     if (Operand.getOpcode() == ISD::UNDEF)
2054       return getNode(ISD::UNDEF, VT);
2055     break;
2056   case ISD::SIGN_EXTEND:
2057     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2058            "Invalid SIGN_EXTEND!");
2059     if (Operand.getValueType() == VT) return Operand;   // noop extension
2060     assert(Operand.getValueType().bitsLT(VT)
2061            && "Invalid sext node, dst < src!");
2062     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2063       return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2064     break;
2065   case ISD::ZERO_EXTEND:
2066     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2067            "Invalid ZERO_EXTEND!");
2068     if (Operand.getValueType() == VT) return Operand;   // noop extension
2069     assert(Operand.getValueType().bitsLT(VT)
2070            && "Invalid zext node, dst < src!");
2071     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
2072       return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
2073     break;
2074   case ISD::ANY_EXTEND:
2075     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2076            "Invalid ANY_EXTEND!");
2077     if (Operand.getValueType() == VT) return Operand;   // noop extension
2078     assert(Operand.getValueType().bitsLT(VT)
2079            && "Invalid anyext node, dst < src!");
2080     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2081       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
2082       return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2083     break;
2084   case ISD::TRUNCATE:
2085     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2086            "Invalid TRUNCATE!");
2087     if (Operand.getValueType() == VT) return Operand;   // noop truncate
2088     assert(Operand.getValueType().bitsGT(VT)
2089            && "Invalid truncate node, src < dst!");
2090     if (OpOpcode == ISD::TRUNCATE)
2091       return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2092     else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2093              OpOpcode == ISD::ANY_EXTEND) {
2094       // If the source is smaller than the dest, we still need an extend.
2095       if (Operand.Val->getOperand(0).getValueType().bitsLT(VT))
2096         return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2097       else if (Operand.Val->getOperand(0).getValueType().bitsGT(VT))
2098         return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2099       else
2100         return Operand.Val->getOperand(0);
2101     }
2102     break;
2103   case ISD::BIT_CONVERT:
2104     // Basic sanity checking.
2105     assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2106            && "Cannot BIT_CONVERT between types of different sizes!");
2107     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
2108     if (OpOpcode == ISD::BIT_CONVERT)  // bitconv(bitconv(x)) -> bitconv(x)
2109       return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
2110     if (OpOpcode == ISD::UNDEF)
2111       return getNode(ISD::UNDEF, VT);
2112     break;
2113   case ISD::SCALAR_TO_VECTOR:
2114     assert(VT.isVector() && !Operand.getValueType().isVector() &&
2115            VT.getVectorElementType() == Operand.getValueType() &&
2116            "Illegal SCALAR_TO_VECTOR node!");
2117     if (OpOpcode == ISD::UNDEF)
2118       return getNode(ISD::UNDEF, VT);
2119     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2120     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2121         isa<ConstantSDNode>(Operand.getOperand(1)) &&
2122         Operand.getConstantOperandVal(1) == 0 &&
2123         Operand.getOperand(0).getValueType() == VT)
2124       return Operand.getOperand(0);
2125     break;
2126   case ISD::FNEG:
2127     if (OpOpcode == ISD::FSUB)   // -(X-Y) -> (Y-X)
2128       return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
2129                      Operand.Val->getOperand(0));
2130     if (OpOpcode == ISD::FNEG)  // --X -> X
2131       return Operand.Val->getOperand(0);
2132     break;
2133   case ISD::FABS:
2134     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
2135       return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
2136     break;
2137   }
2138
2139   SDNode *N;
2140   SDVTList VTs = getVTList(VT);
2141   if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2142     FoldingSetNodeID ID;
2143     SDOperand Ops[1] = { Operand };
2144     AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2145     void *IP = 0;
2146     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2147       return SDOperand(E, 0);
2148     N = getAllocator().Allocate<UnarySDNode>();
2149     new (N) UnarySDNode(Opcode, VTs, Operand);
2150     CSEMap.InsertNode(N, IP);
2151   } else {
2152     N = getAllocator().Allocate<UnarySDNode>();
2153     new (N) UnarySDNode(Opcode, VTs, Operand);
2154   }
2155   AllNodes.push_back(N);
2156   return SDOperand(N, 0);
2157 }
2158
2159
2160
2161 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2162                                 SDOperand N1, SDOperand N2) {
2163   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2164   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2165   switch (Opcode) {
2166   default: break;
2167   case ISD::TokenFactor:
2168     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2169            N2.getValueType() == MVT::Other && "Invalid token factor!");
2170     // Fold trivial token factors.
2171     if (N1.getOpcode() == ISD::EntryToken) return N2;
2172     if (N2.getOpcode() == ISD::EntryToken) return N1;
2173     break;
2174   case ISD::AND:
2175     assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2176            N1.getValueType() == VT && "Binary operator types must match!");
2177     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
2178     // worth handling here.
2179     if (N2C && N2C->isNullValue())
2180       return N2;
2181     if (N2C && N2C->isAllOnesValue())  // X & -1 -> X
2182       return N1;
2183     break;
2184   case ISD::OR:
2185   case ISD::XOR:
2186   case ISD::ADD:
2187   case ISD::SUB:
2188     assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2189            N1.getValueType() == VT && "Binary operator types must match!");
2190     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
2191     // it's worth handling here.
2192     if (N2C && N2C->isNullValue())
2193       return N1;
2194     break;
2195   case ISD::UDIV:
2196   case ISD::UREM:
2197   case ISD::MULHU:
2198   case ISD::MULHS:
2199     assert(VT.isInteger() && "This operator does not apply to FP types!");
2200     // fall through
2201   case ISD::MUL:
2202   case ISD::SDIV:
2203   case ISD::SREM:
2204   case ISD::FADD:
2205   case ISD::FSUB:
2206   case ISD::FMUL:
2207   case ISD::FDIV:
2208   case ISD::FREM:
2209     assert(N1.getValueType() == N2.getValueType() &&
2210            N1.getValueType() == VT && "Binary operator types must match!");
2211     break;
2212   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
2213     assert(N1.getValueType() == VT &&
2214            N1.getValueType().isFloatingPoint() &&
2215            N2.getValueType().isFloatingPoint() &&
2216            "Invalid FCOPYSIGN!");
2217     break;
2218   case ISD::SHL:
2219   case ISD::SRA:
2220   case ISD::SRL:
2221   case ISD::ROTL:
2222   case ISD::ROTR:
2223     assert(VT == N1.getValueType() &&
2224            "Shift operators return type must be the same as their first arg");
2225     assert(VT.isInteger() && N2.getValueType().isInteger() &&
2226            "Shifts only work on integers");
2227
2228     // Always fold shifts of i1 values so the code generator doesn't need to
2229     // handle them.  Since we know the size of the shift has to be less than the
2230     // size of the value, the shift/rotate count is guaranteed to be zero.
2231     if (VT == MVT::i1)
2232       return N1;
2233     break;
2234   case ISD::FP_ROUND_INREG: {
2235     MVT EVT = cast<VTSDNode>(N2)->getVT();
2236     assert(VT == N1.getValueType() && "Not an inreg round!");
2237     assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2238            "Cannot FP_ROUND_INREG integer types");
2239     assert(EVT.bitsLE(VT) && "Not rounding down!");
2240     if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
2241     break;
2242   }
2243   case ISD::FP_ROUND:
2244     assert(VT.isFloatingPoint() &&
2245            N1.getValueType().isFloatingPoint() &&
2246            VT.bitsLE(N1.getValueType()) &&
2247            isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2248     if (N1.getValueType() == VT) return N1;  // noop conversion.
2249     break;
2250   case ISD::AssertSext:
2251   case ISD::AssertZext: {
2252     MVT EVT = cast<VTSDNode>(N2)->getVT();
2253     assert(VT == N1.getValueType() && "Not an inreg extend!");
2254     assert(VT.isInteger() && EVT.isInteger() &&
2255            "Cannot *_EXTEND_INREG FP types");
2256     assert(EVT.bitsLE(VT) && "Not extending!");
2257     if (VT == EVT) return N1; // noop assertion.
2258     break;
2259   }
2260   case ISD::SIGN_EXTEND_INREG: {
2261     MVT EVT = cast<VTSDNode>(N2)->getVT();
2262     assert(VT == N1.getValueType() && "Not an inreg extend!");
2263     assert(VT.isInteger() && EVT.isInteger() &&
2264            "Cannot *_EXTEND_INREG FP types");
2265     assert(EVT.bitsLE(VT) && "Not extending!");
2266     if (EVT == VT) return N1;  // Not actually extending
2267
2268     if (N1C) {
2269       APInt Val = N1C->getAPIntValue();
2270       unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2271       Val <<= Val.getBitWidth()-FromBits;
2272       Val = Val.ashr(Val.getBitWidth()-FromBits);
2273       return getConstant(Val, VT);
2274     }
2275     break;
2276   }
2277   case ISD::EXTRACT_VECTOR_ELT:
2278     assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
2279
2280     // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2281     if (N1.getOpcode() == ISD::UNDEF)
2282       return getNode(ISD::UNDEF, VT);
2283       
2284     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2285     // expanding copies of large vectors from registers.
2286     if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
2287         N1.getNumOperands() > 0) {
2288       unsigned Factor =
2289         N1.getOperand(0).getValueType().getVectorNumElements();
2290       return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2291                      N1.getOperand(N2C->getValue() / Factor),
2292                      getConstant(N2C->getValue() % Factor, N2.getValueType()));
2293     }
2294
2295     // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2296     // expanding large vector constants.
2297     if (N1.getOpcode() == ISD::BUILD_VECTOR)
2298       return N1.getOperand(N2C->getValue());
2299       
2300     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2301     // operations are lowered to scalars.
2302     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
2303       if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
2304         if (IEC == N2C)
2305           return N1.getOperand(1);
2306         else
2307           return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2308       }
2309     break;
2310   case ISD::EXTRACT_ELEMENT:
2311     assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2312     assert(!N1.getValueType().isVector() && !VT.isVector() &&
2313            (N1.getValueType().isInteger() == VT.isInteger()) &&
2314            "Wrong types for EXTRACT_ELEMENT!");
2315
2316     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2317     // 64-bit integers into 32-bit parts.  Instead of building the extract of
2318     // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 
2319     if (N1.getOpcode() == ISD::BUILD_PAIR)
2320       return N1.getOperand(N2C->getValue());
2321
2322     // EXTRACT_ELEMENT of a constant int is also very common.
2323     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2324       unsigned ElementSize = VT.getSizeInBits();
2325       unsigned Shift = ElementSize * N2C->getValue();
2326       APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2327       return getConstant(ShiftedVal.trunc(ElementSize), VT);
2328     }
2329     break;
2330   case ISD::EXTRACT_SUBVECTOR:
2331     if (N1.getValueType() == VT) // Trivial extraction.
2332       return N1;
2333     break;
2334   }
2335
2336   if (N1C) {
2337     if (N2C) {
2338       const APInt &C1 = N1C->getAPIntValue(), &C2 = N2C->getAPIntValue();
2339       switch (Opcode) {
2340       case ISD::ADD: return getConstant(C1 + C2, VT);
2341       case ISD::SUB: return getConstant(C1 - C2, VT);
2342       case ISD::MUL: return getConstant(C1 * C2, VT);
2343       case ISD::UDIV:
2344         if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2345         break;
2346       case ISD::UREM :
2347         if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2348         break;
2349       case ISD::SDIV :
2350         if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2351         break;
2352       case ISD::SREM :
2353         if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2354         break;
2355       case ISD::AND  : return getConstant(C1 & C2, VT);
2356       case ISD::OR   : return getConstant(C1 | C2, VT);
2357       case ISD::XOR  : return getConstant(C1 ^ C2, VT);
2358       case ISD::SHL  : return getConstant(C1 << C2, VT);
2359       case ISD::SRL  : return getConstant(C1.lshr(C2), VT);
2360       case ISD::SRA  : return getConstant(C1.ashr(C2), VT);
2361       case ISD::ROTL : return getConstant(C1.rotl(C2), VT);
2362       case ISD::ROTR : return getConstant(C1.rotr(C2), VT);
2363       default: break;
2364       }
2365     } else {      // Cannonicalize constant to RHS if commutative
2366       if (isCommutativeBinOp(Opcode)) {
2367         std::swap(N1C, N2C);
2368         std::swap(N1, N2);
2369       }
2370     }
2371   }
2372
2373   // Constant fold FP operations.
2374   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
2375   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
2376   if (N1CFP) {
2377     if (!N2CFP && isCommutativeBinOp(Opcode)) {
2378       // Cannonicalize constant to RHS if commutative
2379       std::swap(N1CFP, N2CFP);
2380       std::swap(N1, N2);
2381     } else if (N2CFP && VT != MVT::ppcf128) {
2382       APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2383       APFloat::opStatus s;
2384       switch (Opcode) {
2385       case ISD::FADD: 
2386         s = V1.add(V2, APFloat::rmNearestTiesToEven);
2387         if (s != APFloat::opInvalidOp)
2388           return getConstantFP(V1, VT);
2389         break;
2390       case ISD::FSUB: 
2391         s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2392         if (s!=APFloat::opInvalidOp)
2393           return getConstantFP(V1, VT);
2394         break;
2395       case ISD::FMUL:
2396         s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2397         if (s!=APFloat::opInvalidOp)
2398           return getConstantFP(V1, VT);
2399         break;
2400       case ISD::FDIV:
2401         s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2402         if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2403           return getConstantFP(V1, VT);
2404         break;
2405       case ISD::FREM :
2406         s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2407         if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2408           return getConstantFP(V1, VT);
2409         break;
2410       case ISD::FCOPYSIGN:
2411         V1.copySign(V2);
2412         return getConstantFP(V1, VT);
2413       default: break;
2414       }
2415     }
2416   }
2417   
2418   // Canonicalize an UNDEF to the RHS, even over a constant.
2419   if (N1.getOpcode() == ISD::UNDEF) {
2420     if (isCommutativeBinOp(Opcode)) {
2421       std::swap(N1, N2);
2422     } else {
2423       switch (Opcode) {
2424       case ISD::FP_ROUND_INREG:
2425       case ISD::SIGN_EXTEND_INREG:
2426       case ISD::SUB:
2427       case ISD::FSUB:
2428       case ISD::FDIV:
2429       case ISD::FREM:
2430       case ISD::SRA:
2431         return N1;     // fold op(undef, arg2) -> undef
2432       case ISD::UDIV:
2433       case ISD::SDIV:
2434       case ISD::UREM:
2435       case ISD::SREM:
2436       case ISD::SRL:
2437       case ISD::SHL:
2438         if (!VT.isVector())
2439           return getConstant(0, VT);    // fold op(undef, arg2) -> 0
2440         // For vectors, we can't easily build an all zero vector, just return
2441         // the LHS.
2442         return N2;
2443       }
2444     }
2445   }
2446   
2447   // Fold a bunch of operators when the RHS is undef. 
2448   if (N2.getOpcode() == ISD::UNDEF) {
2449     switch (Opcode) {
2450     case ISD::XOR:
2451       if (N1.getOpcode() == ISD::UNDEF)
2452         // Handle undef ^ undef -> 0 special case. This is a common
2453         // idiom (misuse).
2454         return getConstant(0, VT);
2455       // fallthrough
2456     case ISD::ADD:
2457     case ISD::ADDC:
2458     case ISD::ADDE:
2459     case ISD::SUB:
2460     case ISD::FADD:
2461     case ISD::FSUB:
2462     case ISD::FMUL:
2463     case ISD::FDIV:
2464     case ISD::FREM:
2465     case ISD::UDIV:
2466     case ISD::SDIV:
2467     case ISD::UREM:
2468     case ISD::SREM:
2469       return N2;       // fold op(arg1, undef) -> undef
2470     case ISD::MUL: 
2471     case ISD::AND:
2472     case ISD::SRL:
2473     case ISD::SHL:
2474       if (!VT.isVector())
2475         return getConstant(0, VT);  // fold op(arg1, undef) -> 0
2476       // For vectors, we can't easily build an all zero vector, just return
2477       // the LHS.
2478       return N1;
2479     case ISD::OR:
2480       if (!VT.isVector())
2481         return getConstant(VT.getIntegerVTBitMask(), VT);
2482       // For vectors, we can't easily build an all one vector, just return
2483       // the LHS.
2484       return N1;
2485     case ISD::SRA:
2486       return N1;
2487     }
2488   }
2489
2490   // Memoize this node if possible.
2491   SDNode *N;
2492   SDVTList VTs = getVTList(VT);
2493   if (VT != MVT::Flag) {
2494     SDOperand Ops[] = { N1, N2 };
2495     FoldingSetNodeID ID;
2496     AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2497     void *IP = 0;
2498     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2499       return SDOperand(E, 0);
2500     N = getAllocator().Allocate<BinarySDNode>();
2501     new (N) BinarySDNode(Opcode, VTs, N1, N2);
2502     CSEMap.InsertNode(N, IP);
2503   } else {
2504     N = getAllocator().Allocate<BinarySDNode>();
2505     new (N) BinarySDNode(Opcode, VTs, N1, N2);
2506   }
2507
2508   AllNodes.push_back(N);
2509   return SDOperand(N, 0);
2510 }
2511
2512 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2513                                 SDOperand N1, SDOperand N2, SDOperand N3) {
2514   // Perform various simplifications.
2515   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2516   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2517   switch (Opcode) {
2518   case ISD::SETCC: {
2519     // Use FoldSetCC to simplify SETCC's.
2520     SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2521     if (Simp.Val) return Simp;
2522     break;
2523   }
2524   case ISD::SELECT:
2525     if (N1C) {
2526      if (N1C->getValue())
2527         return N2;             // select true, X, Y -> X
2528       else
2529         return N3;             // select false, X, Y -> Y
2530     }
2531
2532     if (N2 == N3) return N2;   // select C, X, X -> X
2533     break;
2534   case ISD::BRCOND:
2535     if (N2C) {
2536       if (N2C->getValue()) // Unconditional branch
2537         return getNode(ISD::BR, MVT::Other, N1, N3);
2538       else
2539         return N1;         // Never-taken branch
2540     }
2541     break;
2542   case ISD::VECTOR_SHUFFLE:
2543     assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2544            VT.isVector() && N3.getValueType().isVector() &&
2545            N3.getOpcode() == ISD::BUILD_VECTOR &&
2546            VT.getVectorNumElements() == N3.getNumOperands() &&
2547            "Illegal VECTOR_SHUFFLE node!");
2548     break;
2549   case ISD::BIT_CONVERT:
2550     // Fold bit_convert nodes from a type to themselves.
2551     if (N1.getValueType() == VT)
2552       return N1;
2553     break;
2554   }
2555
2556   // Memoize node if it doesn't produce a flag.
2557   SDNode *N;
2558   SDVTList VTs = getVTList(VT);
2559   if (VT != MVT::Flag) {
2560     SDOperand Ops[] = { N1, N2, N3 };
2561     FoldingSetNodeID ID;
2562     AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2563     void *IP = 0;
2564     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2565       return SDOperand(E, 0);
2566     N = getAllocator().Allocate<TernarySDNode>();
2567     new (N) TernarySDNode(Opcode, VTs, N1, N2, N3);
2568     CSEMap.InsertNode(N, IP);
2569   } else {
2570     N = getAllocator().Allocate<TernarySDNode>();
2571     new (N) TernarySDNode(Opcode, VTs, N1, N2, N3);
2572   }
2573   AllNodes.push_back(N);
2574   return SDOperand(N, 0);
2575 }
2576
2577 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2578                                 SDOperand N1, SDOperand N2, SDOperand N3,
2579                                 SDOperand N4) {
2580   SDOperand Ops[] = { N1, N2, N3, N4 };
2581   return getNode(Opcode, VT, Ops, 4);
2582 }
2583
2584 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2585                                 SDOperand N1, SDOperand N2, SDOperand N3,
2586                                 SDOperand N4, SDOperand N5) {
2587   SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2588   return getNode(Opcode, VT, Ops, 5);
2589 }
2590
2591 /// getMemsetValue - Vectorized representation of the memset value
2592 /// operand.
2593 static SDOperand getMemsetValue(SDOperand Value, MVT VT, SelectionDAG &DAG) {
2594   unsigned NumBits = VT.isVector() ?
2595     VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
2596   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2597     APInt Val = APInt(NumBits, C->getValue() & 255);
2598     unsigned Shift = 8;
2599     for (unsigned i = NumBits; i > 8; i >>= 1) {
2600       Val = (Val << Shift) | Val;
2601       Shift <<= 1;
2602     }
2603     if (VT.isInteger())
2604       return DAG.getConstant(Val, VT);
2605     return DAG.getConstantFP(APFloat(Val), VT);
2606   }
2607
2608   Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2609   unsigned Shift = 8;
2610   for (unsigned i = NumBits; i > 8; i >>= 1) {
2611     Value = DAG.getNode(ISD::OR, VT,
2612                         DAG.getNode(ISD::SHL, VT, Value,
2613                                     DAG.getConstant(Shift, MVT::i8)), Value);
2614     Shift <<= 1;
2615   }
2616
2617   return Value;
2618 }
2619
2620 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2621 /// used when a memcpy is turned into a memset when the source is a constant
2622 /// string ptr.
2623 static SDOperand getMemsetStringVal(MVT VT, SelectionDAG &DAG,
2624                                     const TargetLowering &TLI,
2625                                     std::string &Str, unsigned Offset) {
2626   // Handle vector with all elements zero.
2627   if (Str.empty()) {
2628     if (VT.isInteger())
2629       return DAG.getConstant(0, VT);
2630     unsigned NumElts = VT.getVectorNumElements();
2631     MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
2632     return DAG.getNode(ISD::BIT_CONVERT, VT,
2633                        DAG.getConstant(0, MVT::getVectorVT(EltVT, NumElts)));
2634   }
2635
2636   assert(!VT.isVector() && "Can't handle vector type here!");
2637   unsigned NumBits = VT.getSizeInBits();
2638   unsigned MSB = NumBits / 8;
2639   uint64_t Val = 0;
2640   if (TLI.isLittleEndian())
2641     Offset = Offset + MSB - 1;
2642   for (unsigned i = 0; i != MSB; ++i) {
2643     Val = (Val << 8) | (unsigned char)Str[Offset];
2644     Offset += TLI.isLittleEndian() ? -1 : 1;
2645   }
2646   return DAG.getConstant(Val, VT);
2647 }
2648
2649 /// getMemBasePlusOffset - Returns base and offset node for the 
2650 ///
2651 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2652                                       SelectionDAG &DAG) {
2653   MVT VT = Base.getValueType();
2654   return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2655 }
2656
2657 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
2658 ///
2659 static bool isMemSrcFromString(SDOperand Src, std::string &Str) {
2660   unsigned SrcDelta = 0;
2661   GlobalAddressSDNode *G = NULL;
2662   if (Src.getOpcode() == ISD::GlobalAddress)
2663     G = cast<GlobalAddressSDNode>(Src);
2664   else if (Src.getOpcode() == ISD::ADD &&
2665            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2666            Src.getOperand(1).getOpcode() == ISD::Constant) {
2667     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
2668     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getValue();
2669   }
2670   if (!G)
2671     return false;
2672
2673   GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2674   if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
2675     return true;
2676
2677   return false;
2678 }
2679
2680 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2681 /// to replace the memset / memcpy is below the threshold. It also returns the
2682 /// types of the sequence of memory ops to perform memset / memcpy.
2683 static
2684 bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
2685                               SDOperand Dst, SDOperand Src,
2686                               unsigned Limit, uint64_t Size, unsigned &Align,
2687                               std::string &Str, bool &isSrcStr,
2688                               SelectionDAG &DAG,
2689                               const TargetLowering &TLI) {
2690   isSrcStr = isMemSrcFromString(Src, Str);
2691   bool isSrcConst = isa<ConstantSDNode>(Src);
2692   bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
2693   MVT VT= TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
2694   if (VT != MVT::iAny) {
2695     unsigned NewAlign = (unsigned)
2696       TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT());
2697     // If source is a string constant, this will require an unaligned load.
2698     if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
2699       if (Dst.getOpcode() != ISD::FrameIndex) {
2700         // Can't change destination alignment. It requires a unaligned store.
2701         if (AllowUnalign)
2702           VT = MVT::iAny;
2703       } else {
2704         int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
2705         MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2706         if (MFI->isFixedObjectIndex(FI)) {
2707           // Can't change destination alignment. It requires a unaligned store.
2708           if (AllowUnalign)
2709             VT = MVT::iAny;
2710         } else {
2711           // Give the stack frame object a larger alignment if needed.
2712           if (MFI->getObjectAlignment(FI) < NewAlign)
2713             MFI->setObjectAlignment(FI, NewAlign);
2714           Align = NewAlign;
2715         }
2716       }
2717     }
2718   }
2719
2720   if (VT == MVT::iAny) {
2721     if (AllowUnalign) {
2722       VT = MVT::i64;
2723     } else {
2724       switch (Align & 7) {
2725       case 0:  VT = MVT::i64; break;
2726       case 4:  VT = MVT::i32; break;
2727       case 2:  VT = MVT::i16; break;
2728       default: VT = MVT::i8;  break;
2729       }
2730     }
2731
2732     MVT LVT = MVT::i64;
2733     while (!TLI.isTypeLegal(LVT))
2734       LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1);
2735     assert(LVT.isInteger());
2736
2737     if (VT.bitsGT(LVT))
2738       VT = LVT;
2739   }
2740
2741   unsigned NumMemOps = 0;
2742   while (Size != 0) {
2743     unsigned VTSize = VT.getSizeInBits() / 8;
2744     while (VTSize > Size) {
2745       // For now, only use non-vector load / store's for the left-over pieces.
2746       if (VT.isVector()) {
2747         VT = MVT::i64;
2748         while (!TLI.isTypeLegal(VT))
2749           VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2750         VTSize = VT.getSizeInBits() / 8;
2751       } else {
2752         VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2753         VTSize >>= 1;
2754       }
2755     }
2756
2757     if (++NumMemOps > Limit)
2758       return false;
2759     MemOps.push_back(VT);
2760     Size -= VTSize;
2761   }
2762
2763   return true;
2764 }
2765
2766 static SDOperand getMemcpyLoadsAndStores(SelectionDAG &DAG,
2767                                          SDOperand Chain, SDOperand Dst,
2768                                          SDOperand Src, uint64_t Size,
2769                                          unsigned Align, bool AlwaysInline,
2770                                          const Value *DstSV, uint64_t DstSVOff,
2771                                          const Value *SrcSV, uint64_t SrcSVOff){
2772   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2773
2774   // Expand memcpy to a series of load and store ops if the size operand falls
2775   // below a certain threshold.
2776   std::vector<MVT> MemOps;
2777   uint64_t Limit = -1;
2778   if (!AlwaysInline)
2779     Limit = TLI.getMaxStoresPerMemcpy();
2780   unsigned DstAlign = Align;  // Destination alignment can change.
2781   std::string Str;
2782   bool CopyFromStr;
2783   if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2784                                 Str, CopyFromStr, DAG, TLI))
2785     return SDOperand();
2786
2787
2788   bool isZeroStr = CopyFromStr && Str.empty();
2789   SmallVector<SDOperand, 8> OutChains;
2790   unsigned NumMemOps = MemOps.size();
2791   uint64_t SrcOff = 0, DstOff = 0;
2792   for (unsigned i = 0; i < NumMemOps; i++) {
2793     MVT VT = MemOps[i];
2794     unsigned VTSize = VT.getSizeInBits() / 8;
2795     SDOperand Value, Store;
2796
2797     if (CopyFromStr && (isZeroStr || !VT.isVector())) {
2798       // It's unlikely a store of a vector immediate can be done in a single
2799       // instruction. It would require a load from a constantpool first.
2800       // We also handle store a vector with all zero's.
2801       // FIXME: Handle other cases where store of vector immediate is done in
2802       // a single instruction.
2803       Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2804       Store = DAG.getStore(Chain, Value,
2805                            getMemBasePlusOffset(Dst, DstOff, DAG),
2806                            DstSV, DstSVOff + DstOff);
2807     } else {
2808       Value = DAG.getLoad(VT, Chain,
2809                           getMemBasePlusOffset(Src, SrcOff, DAG),
2810                           SrcSV, SrcSVOff + SrcOff, false, Align);
2811       Store = DAG.getStore(Chain, Value,
2812                            getMemBasePlusOffset(Dst, DstOff, DAG),
2813                            DstSV, DstSVOff + DstOff, false, DstAlign);
2814     }
2815     OutChains.push_back(Store);
2816     SrcOff += VTSize;
2817     DstOff += VTSize;
2818   }
2819
2820   return DAG.getNode(ISD::TokenFactor, MVT::Other,
2821                      &OutChains[0], OutChains.size());
2822 }
2823
2824 static SDOperand getMemmoveLoadsAndStores(SelectionDAG &DAG,
2825                                           SDOperand Chain, SDOperand Dst,
2826                                           SDOperand Src, uint64_t Size,
2827                                           unsigned Align, bool AlwaysInline,
2828                                           const Value *DstSV, uint64_t DstSVOff,
2829                                           const Value *SrcSV, uint64_t SrcSVOff){
2830   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2831
2832   // Expand memmove to a series of load and store ops if the size operand falls
2833   // below a certain threshold.
2834   std::vector<MVT> MemOps;
2835   uint64_t Limit = -1;
2836   if (!AlwaysInline)
2837     Limit = TLI.getMaxStoresPerMemmove();
2838   unsigned DstAlign = Align;  // Destination alignment can change.
2839   std::string Str;
2840   bool CopyFromStr;
2841   if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2842                                 Str, CopyFromStr, DAG, TLI))
2843     return SDOperand();
2844
2845   uint64_t SrcOff = 0, DstOff = 0;
2846
2847   SmallVector<SDOperand, 8> LoadValues;
2848   SmallVector<SDOperand, 8> LoadChains;
2849   SmallVector<SDOperand, 8> OutChains;
2850   unsigned NumMemOps = MemOps.size();
2851   for (unsigned i = 0; i < NumMemOps; i++) {
2852     MVT VT = MemOps[i];
2853     unsigned VTSize = VT.getSizeInBits() / 8;
2854     SDOperand Value, Store;
2855
2856     Value = DAG.getLoad(VT, Chain,
2857                         getMemBasePlusOffset(Src, SrcOff, DAG),
2858                         SrcSV, SrcSVOff + SrcOff, false, Align);
2859     LoadValues.push_back(Value);
2860     LoadChains.push_back(Value.getValue(1));
2861     SrcOff += VTSize;
2862   }
2863   Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2864                       &LoadChains[0], LoadChains.size());
2865   OutChains.clear();
2866   for (unsigned i = 0; i < NumMemOps; i++) {
2867     MVT VT = MemOps[i];
2868     unsigned VTSize = VT.getSizeInBits() / 8;
2869     SDOperand Value, Store;
2870
2871     Store = DAG.getStore(Chain, LoadValues[i],
2872                          getMemBasePlusOffset(Dst, DstOff, DAG),
2873                          DstSV, DstSVOff + DstOff, false, DstAlign);
2874     OutChains.push_back(Store);
2875     DstOff += VTSize;
2876   }
2877
2878   return DAG.getNode(ISD::TokenFactor, MVT::Other,
2879                      &OutChains[0], OutChains.size());
2880 }
2881
2882 static SDOperand getMemsetStores(SelectionDAG &DAG,
2883                                  SDOperand Chain, SDOperand Dst,
2884                                  SDOperand Src, uint64_t Size,
2885                                  unsigned Align,
2886                                  const Value *DstSV, uint64_t DstSVOff) {
2887   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2888
2889   // Expand memset to a series of load/store ops if the size operand
2890   // falls below a certain threshold.
2891   std::vector<MVT> MemOps;
2892   std::string Str;
2893   bool CopyFromStr;
2894   if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
2895                                 Size, Align, Str, CopyFromStr, DAG, TLI))
2896     return SDOperand();
2897
2898   SmallVector<SDOperand, 8> OutChains;
2899   uint64_t DstOff = 0;
2900
2901   unsigned NumMemOps = MemOps.size();
2902   for (unsigned i = 0; i < NumMemOps; i++) {
2903     MVT VT = MemOps[i];
2904     unsigned VTSize = VT.getSizeInBits() / 8;
2905     SDOperand Value = getMemsetValue(Src, VT, DAG);
2906     SDOperand Store = DAG.getStore(Chain, Value,
2907                                    getMemBasePlusOffset(Dst, DstOff, DAG),
2908                                    DstSV, DstSVOff + DstOff);
2909     OutChains.push_back(Store);
2910     DstOff += VTSize;
2911   }
2912
2913   return DAG.getNode(ISD::TokenFactor, MVT::Other,
2914                      &OutChains[0], OutChains.size());
2915 }
2916
2917 SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dst,
2918                                   SDOperand Src, SDOperand Size,
2919                                   unsigned Align, bool AlwaysInline,
2920                                   const Value *DstSV, uint64_t DstSVOff,
2921                                   const Value *SrcSV, uint64_t SrcSVOff) {
2922
2923   // Check to see if we should lower the memcpy to loads and stores first.
2924   // For cases within the target-specified limits, this is the best choice.
2925   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2926   if (ConstantSize) {
2927     // Memcpy with size zero? Just return the original chain.
2928     if (ConstantSize->isNullValue())
2929       return Chain;
2930
2931     SDOperand Result =
2932       getMemcpyLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2933                               Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2934     if (Result.Val)
2935       return Result;
2936   }
2937
2938   // Then check to see if we should lower the memcpy with target-specific
2939   // code. If the target chooses to do this, this is the next best.
2940   SDOperand Result =
2941     TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
2942                                 AlwaysInline,
2943                                 DstSV, DstSVOff, SrcSV, SrcSVOff);
2944   if (Result.Val)
2945     return Result;
2946
2947   // If we really need inline code and the target declined to provide it,
2948   // use a (potentially long) sequence of loads and stores.
2949   if (AlwaysInline) {
2950     assert(ConstantSize && "AlwaysInline requires a constant size!");
2951     return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
2952                                    ConstantSize->getValue(), Align, true,
2953                                    DstSV, DstSVOff, SrcSV, SrcSVOff);
2954   }
2955
2956   // Emit a library call.
2957   TargetLowering::ArgListTy Args;
2958   TargetLowering::ArgListEntry Entry;
2959   Entry.Ty = TLI.getTargetData()->getIntPtrType();
2960   Entry.Node = Dst; Args.push_back(Entry);
2961   Entry.Node = Src; Args.push_back(Entry);
2962   Entry.Node = Size; Args.push_back(Entry);
2963   std::pair<SDOperand,SDOperand> CallResult =
2964     TLI.LowerCallTo(Chain, Type::VoidTy,
2965                     false, false, false, CallingConv::C, false,
2966                     getExternalSymbol("memcpy", TLI.getPointerTy()),
2967                     Args, *this);
2968   return CallResult.second;
2969 }
2970
2971 SDOperand SelectionDAG::getMemmove(SDOperand Chain, SDOperand Dst,
2972                                    SDOperand Src, SDOperand Size,
2973                                    unsigned Align,
2974                                    const Value *DstSV, uint64_t DstSVOff,
2975                                    const Value *SrcSV, uint64_t SrcSVOff) {
2976
2977   // Check to see if we should lower the memmove to loads and stores first.
2978   // For cases within the target-specified limits, this is the best choice.
2979   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2980   if (ConstantSize) {
2981     // Memmove with size zero? Just return the original chain.
2982     if (ConstantSize->isNullValue())
2983       return Chain;
2984
2985     SDOperand Result =
2986       getMemmoveLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2987                                Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2988     if (Result.Val)
2989       return Result;
2990   }
2991
2992   // Then check to see if we should lower the memmove with target-specific
2993   // code. If the target chooses to do this, this is the next best.
2994   SDOperand Result =
2995     TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
2996                                  DstSV, DstSVOff, SrcSV, SrcSVOff);
2997   if (Result.Val)
2998     return Result;
2999
3000   // Emit a library call.
3001   TargetLowering::ArgListTy Args;
3002   TargetLowering::ArgListEntry Entry;
3003   Entry.Ty = TLI.getTargetData()->getIntPtrType();
3004   Entry.Node = Dst; Args.push_back(Entry);
3005   Entry.Node = Src; Args.push_back(Entry);
3006   Entry.Node = Size; Args.push_back(Entry);
3007   std::pair<SDOperand,SDOperand> CallResult =
3008     TLI.LowerCallTo(Chain, Type::VoidTy,
3009                     false, false, false, CallingConv::C, false,
3010                     getExternalSymbol("memmove", TLI.getPointerTy()),
3011                     Args, *this);
3012   return CallResult.second;
3013 }
3014
3015 SDOperand SelectionDAG::getMemset(SDOperand Chain, SDOperand Dst,
3016                                   SDOperand Src, SDOperand Size,
3017                                   unsigned Align,
3018                                   const Value *DstSV, uint64_t DstSVOff) {
3019
3020   // Check to see if we should lower the memset to stores first.
3021   // For cases within the target-specified limits, this is the best choice.
3022   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3023   if (ConstantSize) {
3024     // Memset with size zero? Just return the original chain.
3025     if (ConstantSize->isNullValue())
3026       return Chain;
3027
3028     SDOperand Result =
3029       getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getValue(), Align,
3030                       DstSV, DstSVOff);
3031     if (Result.Val)
3032       return Result;
3033   }
3034
3035   // Then check to see if we should lower the memset with target-specific
3036   // code. If the target chooses to do this, this is the next best.
3037   SDOperand Result =
3038     TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
3039                                 DstSV, DstSVOff);
3040   if (Result.Val)
3041     return Result;
3042
3043   // Emit a library call.
3044   const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
3045   TargetLowering::ArgListTy Args;
3046   TargetLowering::ArgListEntry Entry;
3047   Entry.Node = Dst; Entry.Ty = IntPtrTy;
3048   Args.push_back(Entry);
3049   // Extend or truncate the argument to be an i32 value for the call.
3050   if (Src.getValueType().bitsGT(MVT::i32))
3051     Src = getNode(ISD::TRUNCATE, MVT::i32, Src);
3052   else
3053     Src = getNode(ISD::ZERO_EXTEND, MVT::i32, Src);
3054   Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
3055   Args.push_back(Entry);
3056   Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
3057   Args.push_back(Entry);
3058   std::pair<SDOperand,SDOperand> CallResult =
3059     TLI.LowerCallTo(Chain, Type::VoidTy,
3060                     false, false, false, CallingConv::C, false,
3061                     getExternalSymbol("memset", TLI.getPointerTy()),
3062                     Args, *this);
3063   return CallResult.second;
3064 }
3065
3066 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain, 
3067                                   SDOperand Ptr, SDOperand Cmp, 
3068                                   SDOperand Swp, const Value* PtrVal,
3069                                   unsigned Alignment) {
3070   assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3071   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3072   SDVTList VTs = getVTList(Cmp.getValueType(), MVT::Other);
3073   FoldingSetNodeID ID;
3074   SDOperand Ops[] = {Chain, Ptr, Cmp, Swp};
3075   AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3076   void* IP = 0;
3077   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3078     return SDOperand(E, 0);
3079   SDNode* N = getAllocator().Allocate<AtomicSDNode>();
3080   new (N) AtomicSDNode(Opcode, VTs, Chain, Ptr, Cmp, Swp, PtrVal, Alignment);
3081   CSEMap.InsertNode(N, IP);
3082   AllNodes.push_back(N);
3083   return SDOperand(N, 0);
3084 }
3085
3086 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain, 
3087                                   SDOperand Ptr, SDOperand Val, 
3088                                   const Value* PtrVal,
3089                                   unsigned Alignment) {
3090   assert((   Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB
3091           || Opcode == ISD::ATOMIC_SWAP || Opcode == ISD::ATOMIC_LOAD_AND
3092           || Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR
3093           || Opcode == ISD::ATOMIC_LOAD_NAND 
3094           || Opcode == ISD::ATOMIC_LOAD_MIN || Opcode == ISD::ATOMIC_LOAD_MAX
3095           || Opcode == ISD::ATOMIC_LOAD_UMIN || Opcode == ISD::ATOMIC_LOAD_UMAX) 
3096          && "Invalid Atomic Op");
3097   SDVTList VTs = getVTList(Val.getValueType(), MVT::Other);
3098   FoldingSetNodeID ID;
3099   SDOperand Ops[] = {Chain, Ptr, Val};
3100   AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3101   void* IP = 0;
3102   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3103     return SDOperand(E, 0);
3104   SDNode* N = getAllocator().Allocate<AtomicSDNode>();
3105   new (N) AtomicSDNode(Opcode, VTs, Chain, Ptr, Val, PtrVal, Alignment);
3106   CSEMap.InsertNode(N, IP);
3107   AllNodes.push_back(N);
3108   return SDOperand(N, 0);
3109 }
3110
3111 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3112 /// Allowed to return something different (and simpler) if Simplify is true.
3113 SDOperand SelectionDAG::getMergeValues(const SDOperand *Ops, unsigned NumOps,
3114                                        bool Simplify) {
3115   if (Simplify && NumOps == 1)
3116     return Ops[0];
3117
3118   SmallVector<MVT, 4> VTs;
3119   VTs.reserve(NumOps);
3120   for (unsigned i = 0; i < NumOps; ++i)
3121     VTs.push_back(Ops[i].getValueType());
3122   return getNode(ISD::MERGE_VALUES, getVTList(&VTs[0], NumOps), Ops, NumOps);
3123 }
3124
3125 SDOperand
3126 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
3127                       MVT VT, SDOperand Chain,
3128                       SDOperand Ptr, SDOperand Offset,
3129                       const Value *SV, int SVOffset, MVT EVT,
3130                       bool isVolatile, unsigned Alignment) {
3131   if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3132     const Type *Ty = 0;
3133     if (VT != MVT::iPTR) {
3134       Ty = VT.getTypeForMVT();
3135     } else if (SV) {
3136       const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3137       assert(PT && "Value for load must be a pointer");
3138       Ty = PT->getElementType();
3139     }
3140     assert(Ty && "Could not get type information for load");
3141     Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3142   }
3143
3144   if (VT == EVT) {
3145     ExtType = ISD::NON_EXTLOAD;
3146   } else if (ExtType == ISD::NON_EXTLOAD) {
3147     assert(VT == EVT && "Non-extending load from different memory type!");
3148   } else {
3149     // Extending load.
3150     if (VT.isVector())
3151       assert(EVT == VT.getVectorElementType() && "Invalid vector extload!");
3152     else
3153       assert(EVT.bitsLT(VT) &&
3154              "Should only be an extending load, not truncating!");
3155     assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3156            "Cannot sign/zero extend a FP/Vector load!");
3157     assert(VT.isInteger() == EVT.isInteger() &&
3158            "Cannot convert from FP to Int or Int -> FP!");
3159   }
3160
3161   bool Indexed = AM != ISD::UNINDEXED;
3162   assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3163          "Unindexed load with an offset!");
3164
3165   SDVTList VTs = Indexed ?
3166     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3167   SDOperand Ops[] = { Chain, Ptr, Offset };
3168   FoldingSetNodeID ID;
3169   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3170   ID.AddInteger(AM);
3171   ID.AddInteger(ExtType);
3172   ID.AddInteger(EVT.getRawBits());
3173   ID.AddInteger(Alignment);
3174   ID.AddInteger(isVolatile);
3175   void *IP = 0;
3176   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3177     return SDOperand(E, 0);
3178   SDNode *N = getAllocator().Allocate<LoadSDNode>();
3179   new (N) LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
3180                      Alignment, isVolatile);
3181   CSEMap.InsertNode(N, IP);
3182   AllNodes.push_back(N);
3183   return SDOperand(N, 0);
3184 }
3185
3186 SDOperand SelectionDAG::getLoad(MVT VT,
3187                                 SDOperand Chain, SDOperand Ptr,
3188                                 const Value *SV, int SVOffset,
3189                                 bool isVolatile, unsigned Alignment) {
3190   SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3191   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3192                  SV, SVOffset, VT, isVolatile, Alignment);
3193 }
3194
3195 SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT VT,
3196                                    SDOperand Chain, SDOperand Ptr,
3197                                    const Value *SV,
3198                                    int SVOffset, MVT EVT,
3199                                    bool isVolatile, unsigned Alignment) {
3200   SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3201   return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
3202                  SV, SVOffset, EVT, isVolatile, Alignment);
3203 }
3204
3205 SDOperand
3206 SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
3207                              SDOperand Offset, ISD::MemIndexedMode AM) {
3208   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3209   assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3210          "Load is already a indexed load!");
3211   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(),
3212                  LD->getChain(), Base, Offset, LD->getSrcValue(),
3213                  LD->getSrcValueOffset(), LD->getMemoryVT(),
3214                  LD->isVolatile(), LD->getAlignment());
3215 }
3216
3217 SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
3218                                  SDOperand Ptr, const Value *SV, int SVOffset,
3219                                  bool isVolatile, unsigned Alignment) {
3220   MVT VT = Val.getValueType();
3221
3222   if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3223     const Type *Ty = 0;
3224     if (VT != MVT::iPTR) {
3225       Ty = VT.getTypeForMVT();
3226     } else if (SV) {
3227       const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3228       assert(PT && "Value for store must be a pointer");
3229       Ty = PT->getElementType();
3230     }
3231     assert(Ty && "Could not get type information for store");
3232     Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3233   }
3234   SDVTList VTs = getVTList(MVT::Other);
3235   SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3236   SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3237   FoldingSetNodeID ID;
3238   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3239   ID.AddInteger(ISD::UNINDEXED);
3240   ID.AddInteger(false);
3241   ID.AddInteger(VT.getRawBits());
3242   ID.AddInteger(Alignment);
3243   ID.AddInteger(isVolatile);
3244   void *IP = 0;
3245   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3246     return SDOperand(E, 0);
3247   SDNode *N = getAllocator().Allocate<StoreSDNode>();
3248   new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
3249                       VT, SV, SVOffset, Alignment, isVolatile);
3250   CSEMap.InsertNode(N, IP);
3251   AllNodes.push_back(N);
3252   return SDOperand(N, 0);
3253 }
3254
3255 SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
3256                                       SDOperand Ptr, const Value *SV,
3257                                       int SVOffset, MVT SVT,
3258                                       bool isVolatile, unsigned Alignment) {
3259   MVT VT = Val.getValueType();
3260
3261   if (VT == SVT)
3262     return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3263
3264   assert(VT.bitsGT(SVT) && "Not a truncation?");
3265   assert(VT.isInteger() == SVT.isInteger() &&
3266          "Can't do FP-INT conversion!");
3267
3268   if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3269     const Type *Ty = 0;
3270     if (VT != MVT::iPTR) {
3271       Ty = VT.getTypeForMVT();
3272     } else if (SV) {
3273       const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3274       assert(PT && "Value for store must be a pointer");
3275       Ty = PT->getElementType();
3276     }
3277     assert(Ty && "Could not get type information for store");
3278     Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3279   }
3280   SDVTList VTs = getVTList(MVT::Other);
3281   SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3282   SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3283   FoldingSetNodeID ID;
3284   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3285   ID.AddInteger(ISD::UNINDEXED);
3286   ID.AddInteger(1);
3287   ID.AddInteger(SVT.getRawBits());
3288   ID.AddInteger(Alignment);
3289   ID.AddInteger(isVolatile);
3290   void *IP = 0;
3291   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3292     return SDOperand(E, 0);
3293   SDNode *N = getAllocator().Allocate<StoreSDNode>();
3294   new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
3295                       SVT, SV, SVOffset, Alignment, isVolatile);
3296   CSEMap.InsertNode(N, IP);
3297   AllNodes.push_back(N);
3298   return SDOperand(N, 0);
3299 }
3300
3301 SDOperand
3302 SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
3303                               SDOperand Offset, ISD::MemIndexedMode AM) {
3304   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3305   assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3306          "Store is already a indexed store!");
3307   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3308   SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3309   FoldingSetNodeID ID;
3310   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3311   ID.AddInteger(AM);
3312   ID.AddInteger(ST->isTruncatingStore());
3313   ID.AddInteger(ST->getMemoryVT().getRawBits());
3314   ID.AddInteger(ST->getAlignment());
3315   ID.AddInteger(ST->isVolatile());
3316   void *IP = 0;
3317   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3318     return SDOperand(E, 0);
3319   SDNode *N = getAllocator().Allocate<StoreSDNode>();
3320   new (N) StoreSDNode(Ops, VTs, AM,
3321                       ST->isTruncatingStore(), ST->getMemoryVT(),
3322                       ST->getSrcValue(), ST->getSrcValueOffset(),
3323                       ST->getAlignment(), ST->isVolatile());
3324   CSEMap.InsertNode(N, IP);
3325   AllNodes.push_back(N);
3326   return SDOperand(N, 0);
3327 }
3328
3329 SDOperand SelectionDAG::getVAArg(MVT VT,
3330                                  SDOperand Chain, SDOperand Ptr,
3331                                  SDOperand SV) {
3332   SDOperand Ops[] = { Chain, Ptr, SV };
3333   return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
3334 }
3335
3336 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
3337                                 const SDUse *Ops, unsigned NumOps) {
3338   switch (NumOps) {
3339   case 0: return getNode(Opcode, VT);
3340   case 1: return getNode(Opcode, VT, Ops[0].getSDOperand());
3341   case 2: return getNode(Opcode, VT, Ops[0].getSDOperand(),
3342                          Ops[1].getSDOperand());
3343   case 3: return getNode(Opcode, VT, Ops[0].getSDOperand(),
3344                          Ops[1].getSDOperand(), Ops[2].getSDOperand());
3345   default: break;
3346   }
3347
3348   // Copy from an SDUse array into an SDOperand array for use with
3349   // the regular getNode logic.
3350   SmallVector<SDOperand, 8> NewOps;
3351   NewOps.reserve(NumOps);
3352   for (unsigned i = 0; i != NumOps; ++i)
3353     NewOps.push_back(Ops[i].getSDOperand());
3354   return getNode(Opcode, VT, Ops, NumOps);
3355 }
3356
3357 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
3358                                 const SDOperand *Ops, unsigned NumOps) {
3359   switch (NumOps) {
3360   case 0: return getNode(Opcode, VT);
3361   case 1: return getNode(Opcode, VT, Ops[0]);
3362   case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3363   case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3364   default: break;
3365   }
3366   
3367   switch (Opcode) {
3368   default: break;
3369   case ISD::SELECT_CC: {
3370     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3371     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3372            "LHS and RHS of condition must have same type!");
3373     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3374            "True and False arms of SelectCC must have same type!");
3375     assert(Ops[2].getValueType() == VT &&
3376            "select_cc node must be of same type as true and false value!");
3377     break;
3378   }
3379   case ISD::BR_CC: {
3380     assert(NumOps == 5 && "BR_CC takes 5 operands!");
3381     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3382            "LHS/RHS of comparison should match types!");
3383     break;
3384   }
3385   }
3386
3387   // Memoize nodes.
3388   SDNode *N;
3389   SDVTList VTs = getVTList(VT);
3390   if (VT != MVT::Flag) {
3391     FoldingSetNodeID ID;
3392     AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3393     void *IP = 0;
3394     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3395       return SDOperand(E, 0);
3396     N = getAllocator().Allocate<SDNode>();
3397     new (N) SDNode(Opcode, VTs, Ops, NumOps);
3398     CSEMap.InsertNode(N, IP);
3399   } else {
3400     N = getAllocator().Allocate<SDNode>();
3401     new (N) SDNode(Opcode, VTs, Ops, NumOps);
3402   }
3403   AllNodes.push_back(N);
3404   return SDOperand(N, 0);
3405 }
3406
3407 SDOperand SelectionDAG::getNode(unsigned Opcode,
3408                                 std::vector<MVT> &ResultTys,
3409                                 const SDOperand *Ops, unsigned NumOps) {
3410   return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
3411                  Ops, NumOps);
3412 }
3413
3414 SDOperand SelectionDAG::getNode(unsigned Opcode,
3415                                 const MVT *VTs, unsigned NumVTs,
3416                                 const SDOperand *Ops, unsigned NumOps) {
3417   if (NumVTs == 1)
3418     return getNode(Opcode, VTs[0], Ops, NumOps);
3419   return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
3420 }  
3421   
3422 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3423                                 const SDOperand *Ops, unsigned NumOps) {
3424   if (VTList.NumVTs == 1)
3425     return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
3426
3427   switch (Opcode) {
3428   // FIXME: figure out how to safely handle things like
3429   // int foo(int x) { return 1 << (x & 255); }
3430   // int bar() { return foo(256); }
3431 #if 0
3432   case ISD::SRA_PARTS:
3433   case ISD::SRL_PARTS:
3434   case ISD::SHL_PARTS:
3435     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3436         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
3437       return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3438     else if (N3.getOpcode() == ISD::AND)
3439       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
3440         // If the and is only masking out bits that cannot effect the shift,
3441         // eliminate the and.
3442         unsigned NumBits = VT.getSizeInBits()*2;
3443         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
3444           return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3445       }
3446     break;
3447 #endif
3448   }
3449
3450   // Memoize the node unless it returns a flag.
3451   SDNode *N;
3452   if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3453     FoldingSetNodeID ID;
3454     AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3455     void *IP = 0;
3456     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3457       return SDOperand(E, 0);
3458     if (NumOps == 1) {
3459       N = getAllocator().Allocate<UnarySDNode>();
3460       new (N) UnarySDNode(Opcode, VTList, Ops[0]);
3461     } else if (NumOps == 2) {
3462       N = getAllocator().Allocate<BinarySDNode>();
3463       new (N) BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3464     } else if (NumOps == 3) {
3465       N = getAllocator().Allocate<TernarySDNode>();
3466       new (N) TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3467     } else {
3468       N = getAllocator().Allocate<SDNode>();
3469       new (N) SDNode(Opcode, VTList, Ops, NumOps);
3470     }
3471     CSEMap.InsertNode(N, IP);
3472   } else {
3473     if (NumOps == 1) {
3474       N = getAllocator().Allocate<UnarySDNode>();
3475       new (N) UnarySDNode(Opcode, VTList, Ops[0]);
3476     } else if (NumOps == 2) {
3477       N = getAllocator().Allocate<BinarySDNode>();
3478       new (N) BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3479     } else if (NumOps == 3) {
3480       N = getAllocator().Allocate<TernarySDNode>();
3481       new (N) TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3482     } else {
3483       N = getAllocator().Allocate<SDNode>();
3484       new (N) SDNode(Opcode, VTList, Ops, NumOps);
3485     }
3486   }
3487   AllNodes.push_back(N);
3488   return SDOperand(N, 0);
3489 }
3490
3491 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
3492   return getNode(Opcode, VTList, 0, 0);
3493 }
3494
3495 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3496                                 SDOperand N1) {
3497   SDOperand Ops[] = { N1 };
3498   return getNode(Opcode, VTList, Ops, 1);
3499 }
3500
3501 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3502                                 SDOperand N1, SDOperand N2) {
3503   SDOperand Ops[] = { N1, N2 };
3504   return getNode(Opcode, VTList, Ops, 2);
3505 }
3506
3507 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3508                                 SDOperand N1, SDOperand N2, SDOperand N3) {
3509   SDOperand Ops[] = { N1, N2, N3 };
3510   return getNode(Opcode, VTList, Ops, 3);
3511 }
3512
3513 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3514                                 SDOperand N1, SDOperand N2, SDOperand N3,
3515                                 SDOperand N4) {
3516   SDOperand Ops[] = { N1, N2, N3, N4 };
3517   return getNode(Opcode, VTList, Ops, 4);
3518 }
3519
3520 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3521                                 SDOperand N1, SDOperand N2, SDOperand N3,
3522                                 SDOperand N4, SDOperand N5) {
3523   SDOperand Ops[] = { N1, N2, N3, N4, N5 };
3524   return getNode(Opcode, VTList, Ops, 5);
3525 }
3526
3527 SDVTList SelectionDAG::getVTList(MVT VT) {
3528   return makeVTList(SDNode::getValueTypeList(VT), 1);
3529 }
3530
3531 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) {
3532   for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3533        E = VTList.end(); I != E; ++I) {
3534     if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2)
3535       return makeVTList(&(*I)[0], 2);
3536   }
3537   std::vector<MVT> V;
3538   V.push_back(VT1);
3539   V.push_back(VT2);
3540   VTList.push_front(V);
3541   return makeVTList(&(*VTList.begin())[0], 2);
3542 }
3543 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2,
3544                                  MVT VT3) {
3545   for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3546        E = VTList.end(); I != E; ++I) {
3547     if (I->size() == 3 && (*I)[0] == VT1 && (*I)[1] == VT2 &&
3548         (*I)[2] == VT3)
3549       return makeVTList(&(*I)[0], 3);
3550   }
3551   std::vector<MVT> V;
3552   V.push_back(VT1);
3553   V.push_back(VT2);
3554   V.push_back(VT3);
3555   VTList.push_front(V);
3556   return makeVTList(&(*VTList.begin())[0], 3);
3557 }
3558
3559 SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
3560   switch (NumVTs) {
3561     case 0: assert(0 && "Cannot have nodes without results!");
3562     case 1: return getVTList(VTs[0]);
3563     case 2: return getVTList(VTs[0], VTs[1]);
3564     case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
3565     default: break;
3566   }
3567
3568   for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3569        E = VTList.end(); I != E; ++I) {
3570     if (I->size() != NumVTs || VTs[0] != (*I)[0] || VTs[1] != (*I)[1]) continue;
3571    
3572     bool NoMatch = false;
3573     for (unsigned i = 2; i != NumVTs; ++i)
3574       if (VTs[i] != (*I)[i]) {
3575         NoMatch = true;
3576         break;
3577       }
3578     if (!NoMatch)
3579       return makeVTList(&*I->begin(), NumVTs);
3580   }
3581   
3582   VTList.push_front(std::vector<MVT>(VTs, VTs+NumVTs));
3583   return makeVTList(&*VTList.begin()->begin(), NumVTs);
3584 }
3585
3586
3587 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
3588 /// specified operands.  If the resultant node already exists in the DAG,
3589 /// this does not modify the specified node, instead it returns the node that
3590 /// already exists.  If the resultant node does not exist in the DAG, the
3591 /// input node is returned.  As a degenerate case, if you specify the same
3592 /// input operands as the node already has, the input node is returned.
3593 SDOperand SelectionDAG::
3594 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
3595   SDNode *N = InN.Val;
3596   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
3597   
3598   // Check to see if there is no change.
3599   if (Op == N->getOperand(0)) return InN;
3600   
3601   // See if the modified node already exists.
3602   void *InsertPos = 0;
3603   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
3604     return SDOperand(Existing, InN.ResNo);
3605   
3606   // Nope it doesn't.  Remove the node from it's current place in the maps.
3607   if (InsertPos)
3608     RemoveNodeFromCSEMaps(N);
3609   
3610   // Now we update the operands.
3611   N->OperandList[0].getVal()->removeUser(0, N);
3612   N->OperandList[0] = Op;
3613   N->OperandList[0].setUser(N);
3614   Op.Val->addUser(0, N);
3615   
3616   // If this gets put into a CSE map, add it.
3617   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3618   return InN;
3619 }
3620
3621 SDOperand SelectionDAG::
3622 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
3623   SDNode *N = InN.Val;
3624   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
3625   
3626   // Check to see if there is no change.
3627   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
3628     return InN;   // No operands changed, just return the input node.
3629   
3630   // See if the modified node already exists.
3631   void *InsertPos = 0;
3632   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
3633     return SDOperand(Existing, InN.ResNo);
3634   
3635   // Nope it doesn't.  Remove the node from it's current place in the maps.
3636   if (InsertPos)
3637     RemoveNodeFromCSEMaps(N);
3638   
3639   // Now we update the operands.
3640   if (N->OperandList[0] != Op1) {
3641     N->OperandList[0].getVal()->removeUser(0, N);
3642     N->OperandList[0] = Op1;
3643     N->OperandList[0].setUser(N);
3644     Op1.Val->addUser(0, N);
3645   }
3646   if (N->OperandList[1] != Op2) {
3647     N->OperandList[1].getVal()->removeUser(1, N);
3648     N->OperandList[1] = Op2;
3649     N->OperandList[1].setUser(N);
3650     Op2.Val->addUser(1, N);
3651   }
3652   
3653   // If this gets put into a CSE map, add it.
3654   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3655   return InN;
3656 }
3657
3658 SDOperand SelectionDAG::
3659 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
3660   SDOperand Ops[] = { Op1, Op2, Op3 };
3661   return UpdateNodeOperands(N, Ops, 3);
3662 }
3663
3664 SDOperand SelectionDAG::
3665 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, 
3666                    SDOperand Op3, SDOperand Op4) {
3667   SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
3668   return UpdateNodeOperands(N, Ops, 4);
3669 }
3670
3671 SDOperand SelectionDAG::
3672 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3673                    SDOperand Op3, SDOperand Op4, SDOperand Op5) {
3674   SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
3675   return UpdateNodeOperands(N, Ops, 5);
3676 }
3677
3678 SDOperand SelectionDAG::
3679 UpdateNodeOperands(SDOperand InN, const SDOperand *Ops, unsigned NumOps) {
3680   SDNode *N = InN.Val;
3681   assert(N->getNumOperands() == NumOps &&
3682          "Update with wrong number of operands");
3683   
3684   // Check to see if there is no change.
3685   bool AnyChange = false;
3686   for (unsigned i = 0; i != NumOps; ++i) {
3687     if (Ops[i] != N->getOperand(i)) {
3688       AnyChange = true;
3689       break;
3690     }
3691   }
3692   
3693   // No operands changed, just return the input node.
3694   if (!AnyChange) return InN;
3695   
3696   // See if the modified node already exists.
3697   void *InsertPos = 0;
3698   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
3699     return SDOperand(Existing, InN.ResNo);
3700   
3701   // Nope it doesn't.  Remove the node from its current place in the maps.
3702   if (InsertPos)
3703     RemoveNodeFromCSEMaps(N);
3704   
3705   // Now we update the operands.
3706   for (unsigned i = 0; i != NumOps; ++i) {
3707     if (N->OperandList[i] != Ops[i]) {
3708       N->OperandList[i].getVal()->removeUser(i, N);
3709       N->OperandList[i] = Ops[i];
3710       N->OperandList[i].setUser(N);
3711       Ops[i].Val->addUser(i, N);
3712     }
3713   }
3714
3715   // If this gets put into a CSE map, add it.
3716   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3717   return InN;
3718 }
3719
3720 /// MorphNodeTo - This frees the operands of the current node, resets the
3721 /// opcode, types, and operands to the specified value.  This should only be
3722 /// used by the SelectionDAG class.
3723 void SDNode::MorphNodeTo(unsigned Opc, SDVTList L,
3724                          const SDOperand *Ops, unsigned NumOps,
3725                          SmallVectorImpl<SDNode *> &DeadNodes) {
3726   NodeType = Opc;
3727   ValueList = L.VTs;
3728   NumValues = L.NumVTs;
3729   
3730   // Clear the operands list, updating used nodes to remove this from their
3731   // use list.  Keep track of any operands that become dead as a result.
3732   SmallPtrSet<SDNode*, 16> DeadNodeSet;
3733   for (op_iterator I = op_begin(), E = op_end(); I != E; ++I) {
3734     SDNode *N = I->getVal();
3735     N->removeUser(std::distance(op_begin(), I), this);
3736     if (N->use_empty())
3737       DeadNodeSet.insert(N);
3738   }
3739
3740   // If NumOps is larger than the # of operands we currently have, reallocate
3741   // the operand list.
3742   if (NumOps > NumOperands) {
3743     if (OperandsNeedDelete) {
3744       delete [] OperandList;
3745     }
3746     OperandList = new SDUse[NumOps];
3747     OperandsNeedDelete = true;
3748   }
3749   
3750   // Assign the new operands.
3751   NumOperands = NumOps;
3752   
3753   for (unsigned i = 0, e = NumOps; i != e; ++i) {
3754     OperandList[i] = Ops[i];
3755     OperandList[i].setUser(this);
3756     SDNode *N = OperandList[i].getVal();
3757     N->addUser(i, this);
3758     ++N->UsesSize;
3759     DeadNodeSet.erase(N);
3760   }
3761
3762   // Clean up any nodes that are still dead after adding the uses for the
3763   // new operands.
3764   for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
3765        E = DeadNodeSet.end(); I != E; ++I)
3766     DeadNodes.push_back(*I);
3767 }
3768
3769 /// DropOperands - Release the operands and set this node to have
3770 /// zero operands.  This should only be used by HandleSDNode to clear
3771 /// its operand list.
3772 void SDNode::DropOperands() {
3773   assert(NodeType == ISD::HANDLENODE &&
3774          "DropOperands is for HANDLENODE only!");
3775
3776   // Unlike the code in MorphNodeTo that does this, we don't need to
3777   // watch for dead nodes here.
3778   for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
3779     I->getVal()->removeUser(std::distance(op_begin(), I), this);
3780
3781   NumOperands = 0;
3782 }
3783
3784 /// SelectNodeTo - These are used for target selectors to *mutate* the
3785 /// specified node to have the specified return type, Target opcode, and
3786 /// operands.  Note that target opcodes are stored as
3787 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
3788 ///
3789 /// Note that SelectNodeTo returns the resultant node.  If there is already a
3790 /// node of the specified opcode and operands, it returns that node instead of
3791 /// the current one.
3792 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3793                                    MVT VT) {
3794   SDVTList VTs = getVTList(VT);
3795   return SelectNodeTo(N, TargetOpc, VTs, 0, 0);
3796 }
3797
3798 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3799                                    MVT VT, SDOperand Op1) {
3800   SDVTList VTs = getVTList(VT);
3801   SDOperand Ops[] = { Op1 };
3802   return SelectNodeTo(N, TargetOpc, VTs, Ops, 1);
3803 }
3804
3805 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3806                                    MVT VT, SDOperand Op1,
3807                                    SDOperand Op2) {
3808   SDVTList VTs = getVTList(VT);
3809   SDOperand Ops[] = { Op1, Op2 };
3810   return SelectNodeTo(N, TargetOpc, VTs, Ops, 2);
3811 }
3812
3813 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3814                                    MVT VT, SDOperand Op1,
3815                                    SDOperand Op2, SDOperand Op3) {
3816   SDVTList VTs = getVTList(VT);
3817   SDOperand Ops[] = { Op1, Op2, Op3 };
3818   return SelectNodeTo(N, TargetOpc, VTs, Ops, 3);
3819 }
3820
3821 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3822                                    MVT VT, const SDOperand *Ops,
3823                                    unsigned NumOps) {
3824   SDVTList VTs = getVTList(VT);
3825   return SelectNodeTo(N, TargetOpc, VTs, Ops, NumOps);
3826 }
3827
3828 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3829                                    MVT VT1, MVT VT2, const SDOperand *Ops,
3830                                    unsigned NumOps) {
3831   SDVTList VTs = getVTList(VT1, VT2);
3832   return SelectNodeTo(N, TargetOpc, VTs, Ops, NumOps);
3833 }
3834
3835 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3836                                    MVT VT1, MVT VT2) {
3837   SDVTList VTs = getVTList(VT1, VT2);
3838   return SelectNodeTo(N, TargetOpc, VTs, (SDOperand *)0, 0);
3839 }
3840
3841 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3842                                    MVT VT1, MVT VT2, MVT VT3,
3843                                    const SDOperand *Ops, unsigned NumOps) {
3844   SDVTList VTs = getVTList(VT1, VT2, VT3);
3845   return SelectNodeTo(N, TargetOpc, VTs, Ops, NumOps);
3846 }
3847
3848 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc, 
3849                                    MVT VT1, MVT VT2,
3850                                    SDOperand Op1) {
3851   SDVTList VTs = getVTList(VT1, VT2);
3852   SDOperand Ops[] = { Op1 };
3853   return SelectNodeTo(N, TargetOpc, VTs, Ops, 1);
3854 }
3855
3856 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc, 
3857                                    MVT VT1, MVT VT2,
3858                                    SDOperand Op1, SDOperand Op2) {
3859   SDVTList VTs = getVTList(VT1, VT2);
3860   SDOperand Ops[] = { Op1, Op2 };
3861   return SelectNodeTo(N, TargetOpc, VTs, Ops, 2);
3862 }
3863
3864 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3865                                    MVT VT1, MVT VT2,
3866                                    SDOperand Op1, SDOperand Op2, 
3867                                    SDOperand Op3) {
3868   SDVTList VTs = getVTList(VT1, VT2);
3869   SDOperand Ops[] = { Op1, Op2, Op3 };
3870   return SelectNodeTo(N, TargetOpc, VTs, Ops, 3);
3871 }
3872
3873 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3874                                    SDVTList VTs, const SDOperand *Ops,
3875                                    unsigned NumOps) {
3876   // If an identical node already exists, use it.
3877   FoldingSetNodeID ID;
3878   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3879   void *IP = 0;
3880   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3881     return ON;
3882
3883   RemoveNodeFromCSEMaps(N);
3884
3885   SmallVector<SDNode *, 16> DeadNodes;
3886   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps, DeadNodes);
3887   RemoveDeadNodes(DeadNodes);
3888
3889   CSEMap.InsertNode(N, IP);   // Memoize the new node.
3890   return N;
3891 }
3892
3893
3894 /// getTargetNode - These are used for target selectors to create a new node
3895 /// with specified return type(s), target opcode, and operands.
3896 ///
3897 /// Note that getTargetNode returns the resultant node.  If there is already a
3898 /// node of the specified opcode and operands, it returns that node instead of
3899 /// the current one.
3900 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT) {
3901   return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
3902 }
3903 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT, SDOperand Op1) {
3904   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
3905 }
3906 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3907                                     SDOperand Op1, SDOperand Op2) {
3908   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
3909 }
3910 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3911                                     SDOperand Op1, SDOperand Op2,
3912                                     SDOperand Op3) {
3913   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
3914 }
3915 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3916                                     const SDOperand *Ops, unsigned NumOps) {
3917   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val;
3918 }
3919 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2) {
3920   const MVT *VTs = getNodeValueTypes(VT1, VT2);
3921   SDOperand Op;
3922   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op, 0).Val;
3923 }
3924 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3925                                     MVT VT2, SDOperand Op1) {
3926   const MVT *VTs = getNodeValueTypes(VT1, VT2);
3927   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op1, 1).Val;
3928 }
3929 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3930                                     MVT VT2, SDOperand Op1,
3931                                     SDOperand Op2) {
3932   const MVT *VTs = getNodeValueTypes(VT1, VT2);
3933   SDOperand Ops[] = { Op1, Op2 };
3934   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 2).Val;
3935 }
3936 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3937                                     MVT VT2, SDOperand Op1,
3938                                     SDOperand Op2, SDOperand Op3) {
3939   const MVT *VTs = getNodeValueTypes(VT1, VT2);
3940   SDOperand Ops[] = { Op1, Op2, Op3 };
3941   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 3).Val;
3942 }
3943 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2,
3944                                     const SDOperand *Ops, unsigned NumOps) {
3945   const MVT *VTs = getNodeValueTypes(VT1, VT2);
3946   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, NumOps).Val;
3947 }
3948 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3949                                     SDOperand Op1, SDOperand Op2) {
3950   const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3951   SDOperand Ops[] = { Op1, Op2 };
3952   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 2).Val;
3953 }
3954 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3955                                     SDOperand Op1, SDOperand Op2,
3956                                     SDOperand Op3) {
3957   const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3958   SDOperand Ops[] = { Op1, Op2, Op3 };
3959   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 3).Val;
3960 }
3961 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3962                                     const SDOperand *Ops, unsigned NumOps) {
3963   const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3964   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, NumOps).Val;
3965 }
3966 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3967                                     MVT VT2, MVT VT3, MVT VT4,
3968                                     const SDOperand *Ops, unsigned NumOps) {
3969   std::vector<MVT> VTList;
3970   VTList.push_back(VT1);
3971   VTList.push_back(VT2);
3972   VTList.push_back(VT3);
3973   VTList.push_back(VT4);
3974   const MVT *VTs = getNodeValueTypes(VTList);
3975   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 4, Ops, NumOps).Val;
3976 }
3977 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
3978                                     std::vector<MVT> &ResultTys,
3979                                     const SDOperand *Ops, unsigned NumOps) {
3980   const MVT *VTs = getNodeValueTypes(ResultTys);
3981   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, ResultTys.size(),
3982                  Ops, NumOps).Val;
3983 }
3984
3985 /// getNodeIfExists - Get the specified node if it's already available, or
3986 /// else return NULL.
3987 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
3988                                       const SDOperand *Ops, unsigned NumOps) {
3989   if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3990     FoldingSetNodeID ID;
3991     AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3992     void *IP = 0;
3993     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3994       return E;
3995   }
3996   return NULL;
3997 }
3998
3999
4000 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4001 /// This can cause recursive merging of nodes in the DAG.
4002 ///
4003 /// This version assumes From has a single result value.
4004 ///
4005 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand To,
4006                                       DAGUpdateListener *UpdateListener) {
4007   SDNode *From = FromN.Val;
4008   assert(From->getNumValues() == 1 && FromN.ResNo == 0 && 
4009          "Cannot replace with this method!");
4010   assert(From != To.Val && "Cannot replace uses of with self");
4011
4012   while (!From->use_empty()) {
4013     SDNode::use_iterator UI = From->use_begin();
4014     SDNode *U = UI->getUser();
4015
4016     // This node is about to morph, remove its old self from the CSE maps.
4017     RemoveNodeFromCSEMaps(U);
4018     int operandNum = 0;
4019     for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4020          I != E; ++I, ++operandNum)
4021       if (I->getVal() == From) {
4022         From->removeUser(operandNum, U);
4023         *I = To;
4024         I->setUser(U);
4025         To.Val->addUser(operandNum, U);
4026       }    
4027
4028     // Now that we have modified U, add it back to the CSE maps.  If it already
4029     // exists there, recursively merge the results together.
4030     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4031       ReplaceAllUsesWith(U, Existing, UpdateListener);
4032       // U is now dead.  Inform the listener if it exists and delete it.
4033       if (UpdateListener) 
4034         UpdateListener->NodeDeleted(U, Existing);
4035       DeleteNodeNotInCSEMaps(U);
4036     } else {
4037       // If the node doesn't already exist, we updated it.  Inform a listener if
4038       // it exists.
4039       if (UpdateListener) 
4040         UpdateListener->NodeUpdated(U);
4041     }
4042   }
4043 }
4044
4045 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4046 /// This can cause recursive merging of nodes in the DAG.
4047 ///
4048 /// This version assumes From/To have matching types and numbers of result
4049 /// values.
4050 ///
4051 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
4052                                       DAGUpdateListener *UpdateListener) {
4053   assert(From != To && "Cannot replace uses of with self");
4054   assert(From->getNumValues() == To->getNumValues() &&
4055          "Cannot use this version of ReplaceAllUsesWith!");
4056   if (From->getNumValues() == 1)   // If possible, use the faster version.
4057     return ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0),
4058                               UpdateListener);
4059   
4060   while (!From->use_empty()) {
4061     SDNode::use_iterator UI = From->use_begin();
4062     SDNode *U = UI->getUser();
4063
4064     // This node is about to morph, remove its old self from the CSE maps.
4065     RemoveNodeFromCSEMaps(U);
4066     int operandNum = 0;
4067     for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4068          I != E; ++I, ++operandNum)
4069       if (I->getVal() == From) {
4070         From->removeUser(operandNum, U);
4071         I->getVal() = To;
4072         To->addUser(operandNum, U);
4073       }
4074
4075     // Now that we have modified U, add it back to the CSE maps.  If it already
4076     // exists there, recursively merge the results together.
4077     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4078       ReplaceAllUsesWith(U, Existing, UpdateListener);
4079       // U is now dead.  Inform the listener if it exists and delete it.
4080       if (UpdateListener) 
4081         UpdateListener->NodeDeleted(U, Existing);
4082       DeleteNodeNotInCSEMaps(U);
4083     } else {
4084       // If the node doesn't already exist, we updated it.  Inform a listener if
4085       // it exists.
4086       if (UpdateListener) 
4087         UpdateListener->NodeUpdated(U);
4088     }
4089   }
4090 }
4091
4092 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4093 /// This can cause recursive merging of nodes in the DAG.
4094 ///
4095 /// This version can replace From with any result values.  To must match the
4096 /// number and types of values returned by From.
4097 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
4098                                       const SDOperand *To,
4099                                       DAGUpdateListener *UpdateListener) {
4100   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
4101     return ReplaceAllUsesWith(SDOperand(From, 0), To[0], UpdateListener);
4102
4103   while (!From->use_empty()) {
4104     SDNode::use_iterator UI = From->use_begin();
4105     SDNode *U = UI->getUser();
4106
4107     // This node is about to morph, remove its old self from the CSE maps.
4108     RemoveNodeFromCSEMaps(U);
4109     int operandNum = 0;
4110     for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4111          I != E; ++I, ++operandNum)
4112       if (I->getVal() == From) {
4113         const SDOperand &ToOp = To[I->getSDOperand().ResNo];
4114         From->removeUser(operandNum, U);
4115         *I = ToOp;
4116         I->setUser(U);
4117         ToOp.Val->addUser(operandNum, U);
4118       }
4119
4120     // Now that we have modified U, add it back to the CSE maps.  If it already
4121     // exists there, recursively merge the results together.
4122     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4123       ReplaceAllUsesWith(U, Existing, UpdateListener);
4124       // U is now dead.  Inform the listener if it exists and delete it.
4125       if (UpdateListener) 
4126         UpdateListener->NodeDeleted(U, Existing);
4127       DeleteNodeNotInCSEMaps(U);
4128     } else {
4129       // If the node doesn't already exist, we updated it.  Inform a listener if
4130       // it exists.
4131       if (UpdateListener) 
4132         UpdateListener->NodeUpdated(U);
4133     }
4134   }
4135 }
4136
4137 namespace {
4138   /// ChainedSetUpdaterListener - This class is a DAGUpdateListener that removes
4139   /// any deleted nodes from the set passed into its constructor and recursively
4140   /// notifies another update listener if specified.
4141   class ChainedSetUpdaterListener : 
4142   public SelectionDAG::DAGUpdateListener {
4143     SmallSetVector<SDNode*, 16> &Set;
4144     SelectionDAG::DAGUpdateListener *Chain;
4145   public:
4146     ChainedSetUpdaterListener(SmallSetVector<SDNode*, 16> &set,
4147                               SelectionDAG::DAGUpdateListener *chain)
4148       : Set(set), Chain(chain) {}
4149  
4150     virtual void NodeDeleted(SDNode *N, SDNode *E) {
4151       Set.remove(N);
4152       if (Chain) Chain->NodeDeleted(N, E);
4153     }
4154     virtual void NodeUpdated(SDNode *N) {
4155       if (Chain) Chain->NodeUpdated(N);
4156     }
4157   };
4158 }
4159
4160 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4161 /// uses of other values produced by From.Val alone.  The Deleted vector is
4162 /// handled the same way as for ReplaceAllUsesWith.
4163 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
4164                                              DAGUpdateListener *UpdateListener){
4165   assert(From != To && "Cannot replace a value with itself");
4166   
4167   // Handle the simple, trivial, case efficiently.
4168   if (From.Val->getNumValues() == 1) {
4169     ReplaceAllUsesWith(From, To, UpdateListener);
4170     return;
4171   }
4172
4173   if (From.use_empty()) return;
4174
4175   // Get all of the users of From.Val.  We want these in a nice,
4176   // deterministically ordered and uniqued set, so we use a SmallSetVector.
4177   SmallSetVector<SDNode*, 16> Users;
4178   for (SDNode::use_iterator UI = From.Val->use_begin(), 
4179       E = From.Val->use_end(); UI != E; ++UI) {
4180     SDNode *User = UI->getUser();
4181     Users.insert(User);
4182   }
4183
4184   // When one of the recursive merges deletes nodes from the graph, we need to
4185   // make sure that UpdateListener is notified *and* that the node is removed
4186   // from Users if present.  CSUL does this.
4187   ChainedSetUpdaterListener CSUL(Users, UpdateListener);
4188   
4189   while (!Users.empty()) {
4190     // We know that this user uses some value of From.  If it is the right
4191     // value, update it.
4192     SDNode *User = Users.back();
4193     Users.pop_back();
4194     
4195     // Scan for an operand that matches From.
4196     SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4197     for (; Op != E; ++Op)
4198       if (*Op == From) break;
4199     
4200     // If there are no matches, the user must use some other result of From.
4201     if (Op == E) continue;
4202       
4203     // Okay, we know this user needs to be updated.  Remove its old self
4204     // from the CSE maps.
4205     RemoveNodeFromCSEMaps(User);
4206     
4207     // Update all operands that match "From" in case there are multiple uses.
4208     for (; Op != E; ++Op) {
4209       if (*Op == From) {
4210         From.Val->removeUser(Op-User->op_begin(), User);
4211         *Op = To;
4212         Op->setUser(User);
4213         To.Val->addUser(Op-User->op_begin(), User);
4214       }
4215     }
4216                
4217     // Now that we have modified User, add it back to the CSE maps.  If it
4218     // already exists there, recursively merge the results together.
4219     SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4220     if (!Existing) {
4221       if (UpdateListener) UpdateListener->NodeUpdated(User);
4222       continue;  // Continue on to next user.
4223     }
4224     
4225     // If there was already an existing matching node, use ReplaceAllUsesWith
4226     // to replace the dead one with the existing one.  This can cause
4227     // recursive merging of other unrelated nodes down the line.  The merging
4228     // can cause deletion of nodes that used the old value.  To handle this, we
4229     // use CSUL to remove them from the Users set.
4230     ReplaceAllUsesWith(User, Existing, &CSUL);
4231     
4232     // User is now dead.  Notify a listener if present.
4233     if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4234     DeleteNodeNotInCSEMaps(User);
4235   }
4236 }
4237
4238 /// AssignNodeIds - Assign a unique node id for each node in the DAG based on
4239 /// their allnodes order. It returns the maximum id.
4240 unsigned SelectionDAG::AssignNodeIds() {
4241   unsigned Id = 0;
4242   for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I){
4243     SDNode *N = I;
4244     N->setNodeId(Id++);
4245   }
4246   return Id;
4247 }
4248
4249 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
4250 /// based on their topological order. It returns the maximum id and a vector
4251 /// of the SDNodes* in assigned order by reference.
4252 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
4253   unsigned DAGSize = AllNodes.size();
4254   std::vector<unsigned> InDegree(DAGSize);
4255   std::vector<SDNode*> Sources;
4256
4257   // Use a two pass approach to avoid using a std::map which is slow.
4258   unsigned Id = 0;
4259   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
4260     SDNode *N = I;
4261     N->setNodeId(Id++);
4262     unsigned Degree = N->use_size();
4263     InDegree[N->getNodeId()] = Degree;
4264     if (Degree == 0)
4265       Sources.push_back(N);
4266   }
4267
4268   TopOrder.clear();
4269   TopOrder.reserve(DAGSize);
4270   while (!Sources.empty()) {
4271     SDNode *N = Sources.back();
4272     Sources.pop_back();
4273     TopOrder.push_back(N);
4274     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
4275       SDNode *P = I->getVal();
4276       unsigned Degree = --InDegree[P->getNodeId()];
4277       if (Degree == 0)
4278         Sources.push_back(P);
4279     }
4280   }
4281
4282   // Second pass, assign the actual topological order as node ids.
4283   Id = 0;
4284   for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
4285        TI != TE; ++TI)
4286     (*TI)->setNodeId(Id++);
4287
4288   return Id;
4289 }
4290
4291
4292
4293 //===----------------------------------------------------------------------===//
4294 //                              SDNode Class
4295 //===----------------------------------------------------------------------===//
4296
4297 // Out-of-line virtual method to give class a home.
4298 void SDNode::ANCHOR() {}
4299 void UnarySDNode::ANCHOR() {}
4300 void BinarySDNode::ANCHOR() {}
4301 void TernarySDNode::ANCHOR() {}
4302 void HandleSDNode::ANCHOR() {}
4303 void ConstantSDNode::ANCHOR() {}
4304 void ConstantFPSDNode::ANCHOR() {}
4305 void GlobalAddressSDNode::ANCHOR() {}
4306 void FrameIndexSDNode::ANCHOR() {}
4307 void JumpTableSDNode::ANCHOR() {}
4308 void ConstantPoolSDNode::ANCHOR() {}
4309 void BasicBlockSDNode::ANCHOR() {}
4310 void SrcValueSDNode::ANCHOR() {}
4311 void MemOperandSDNode::ANCHOR() {}
4312 void RegisterSDNode::ANCHOR() {}
4313 void DbgStopPointSDNode::ANCHOR() {}
4314 void LabelSDNode::ANCHOR() {}
4315 void ExternalSymbolSDNode::ANCHOR() {}
4316 void CondCodeSDNode::ANCHOR() {}
4317 void ARG_FLAGSSDNode::ANCHOR() {}
4318 void VTSDNode::ANCHOR() {}
4319 void MemSDNode::ANCHOR() {}
4320 void LoadSDNode::ANCHOR() {}
4321 void StoreSDNode::ANCHOR() {}
4322 void AtomicSDNode::ANCHOR() {}
4323
4324 HandleSDNode::~HandleSDNode() {
4325   DropOperands();
4326 }
4327
4328 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
4329                                          MVT VT, int o)
4330   : SDNode(isa<GlobalVariable>(GA) &&
4331            cast<GlobalVariable>(GA)->isThreadLocal() ?
4332            // Thread Local
4333            (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
4334            // Non Thread Local
4335            (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
4336            getSDVTList(VT)), Offset(o) {
4337   TheGlobal = const_cast<GlobalValue*>(GA);
4338 }
4339
4340 /// getMemOperand - Return a MachineMemOperand object describing the memory
4341 /// reference performed by this atomic.
4342 MachineMemOperand AtomicSDNode::getMemOperand() const {
4343   int Size = (getValueType(0).getSizeInBits() + 7) >> 3;
4344   int Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4345   if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4346   
4347   // Check if the atomic references a frame index
4348   const FrameIndexSDNode *FI = 
4349   dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4350   if (!getSrcValue() && FI)
4351     return MachineMemOperand(PseudoSourceValue::getFixedStack(), Flags,
4352                              FI->getIndex(), Size, getAlignment());
4353   else
4354     return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(),
4355                              Size, getAlignment());
4356 }
4357
4358 /// getMemOperand - Return a MachineMemOperand object describing the memory
4359 /// reference performed by this load or store.
4360 MachineMemOperand LSBaseSDNode::getMemOperand() const {
4361   int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
4362   int Flags =
4363     getOpcode() == ISD::LOAD ? MachineMemOperand::MOLoad :
4364                                MachineMemOperand::MOStore;
4365   if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4366
4367   // Check if the load references a frame index, and does not have
4368   // an SV attached.
4369   const FrameIndexSDNode *FI =
4370     dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4371   if (!getSrcValue() && FI)
4372     return MachineMemOperand(PseudoSourceValue::getFixedStack(), Flags,
4373                              FI->getIndex(), Size, getAlignment());
4374   else
4375     return MachineMemOperand(getSrcValue(), Flags,
4376                              getSrcValueOffset(), Size, getAlignment());
4377 }
4378
4379 /// Profile - Gather unique data for the node.
4380 ///
4381 void SDNode::Profile(FoldingSetNodeID &ID) {
4382   AddNodeIDNode(ID, this);
4383 }
4384
4385 /// getValueTypeList - Return a pointer to the specified value type.
4386 ///
4387 const MVT *SDNode::getValueTypeList(MVT VT) {
4388   if (VT.isExtended()) {
4389     static std::set<MVT, MVT::compareRawBits> EVTs;
4390     return &(*EVTs.insert(VT).first);
4391   } else {
4392     static MVT VTs[MVT::LAST_VALUETYPE];
4393     VTs[VT.getSimpleVT()] = VT;
4394     return &VTs[VT.getSimpleVT()];
4395   }
4396 }
4397
4398 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
4399 /// indicated value.  This method ignores uses of other values defined by this
4400 /// operation.
4401 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
4402   assert(Value < getNumValues() && "Bad value!");
4403
4404   // If there is only one value, this is easy.
4405   if (getNumValues() == 1)
4406     return use_size() == NUses;
4407   if (use_size() < NUses) return false;
4408
4409   SDOperand TheValue(const_cast<SDNode *>(this), Value);
4410
4411   SmallPtrSet<SDNode*, 32> UsersHandled;
4412
4413   // TODO: Only iterate over uses of a given value of the node
4414   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4415     if (*UI == TheValue) {
4416       if (NUses == 0)
4417         return false;
4418       --NUses;
4419     }
4420   }
4421
4422   // Found exactly the right number of uses?
4423   return NUses == 0;
4424 }
4425
4426
4427 /// hasAnyUseOfValue - Return true if there are any use of the indicated
4428 /// value. This method ignores uses of other values defined by this operation.
4429 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
4430   assert(Value < getNumValues() && "Bad value!");
4431
4432   if (use_empty()) return false;
4433
4434   SDOperand TheValue(const_cast<SDNode *>(this), Value);
4435
4436   SmallPtrSet<SDNode*, 32> UsersHandled;
4437
4438   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4439     SDNode *User = UI->getUser();
4440     if (User->getNumOperands() == 1 ||
4441         UsersHandled.insert(User))     // First time we've seen this?
4442       for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
4443         if (User->getOperand(i) == TheValue) {
4444           return true;
4445         }
4446   }
4447
4448   return false;
4449 }
4450
4451
4452 /// isOnlyUseOf - Return true if this node is the only use of N.
4453 ///
4454 bool SDNode::isOnlyUseOf(SDNode *N) const {
4455   bool Seen = false;
4456   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
4457     SDNode *User = I->getUser();
4458     if (User == this)
4459       Seen = true;
4460     else
4461       return false;
4462   }
4463
4464   return Seen;
4465 }
4466
4467 /// isOperand - Return true if this node is an operand of N.
4468 ///
4469 bool SDOperand::isOperandOf(SDNode *N) const {
4470   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4471     if (*this == N->getOperand(i))
4472       return true;
4473   return false;
4474 }
4475
4476 bool SDNode::isOperandOf(SDNode *N) const {
4477   for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
4478     if (this == N->OperandList[i].getVal())
4479       return true;
4480   return false;
4481 }
4482
4483 /// reachesChainWithoutSideEffects - Return true if this operand (which must
4484 /// be a chain) reaches the specified operand without crossing any 
4485 /// side-effecting instructions.  In practice, this looks through token
4486 /// factors and non-volatile loads.  In order to remain efficient, this only
4487 /// looks a couple of nodes in, it does not do an exhaustive search.
4488 bool SDOperand::reachesChainWithoutSideEffects(SDOperand Dest, 
4489                                                unsigned Depth) const {
4490   if (*this == Dest) return true;
4491   
4492   // Don't search too deeply, we just want to be able to see through
4493   // TokenFactor's etc.
4494   if (Depth == 0) return false;
4495   
4496   // If this is a token factor, all inputs to the TF happen in parallel.  If any
4497   // of the operands of the TF reach dest, then we can do the xform.
4498   if (getOpcode() == ISD::TokenFactor) {
4499     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4500       if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
4501         return true;
4502     return false;
4503   }
4504   
4505   // Loads don't have side effects, look through them.
4506   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
4507     if (!Ld->isVolatile())
4508       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
4509   }
4510   return false;
4511 }
4512
4513
4514 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
4515                             SmallPtrSet<SDNode *, 32> &Visited) {
4516   if (found || !Visited.insert(N))
4517     return;
4518
4519   for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
4520     SDNode *Op = N->getOperand(i).Val;
4521     if (Op == P) {
4522       found = true;
4523       return;
4524     }
4525     findPredecessor(Op, P, found, Visited);
4526   }
4527 }
4528
4529 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
4530 /// is either an operand of N or it can be reached by recursively traversing
4531 /// up the operands.
4532 /// NOTE: this is an expensive method. Use it carefully.
4533 bool SDNode::isPredecessorOf(SDNode *N) const {
4534   SmallPtrSet<SDNode *, 32> Visited;
4535   bool found = false;
4536   findPredecessor(N, this, found, Visited);
4537   return found;
4538 }
4539
4540 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
4541   assert(Num < NumOperands && "Invalid child # of SDNode!");
4542   return cast<ConstantSDNode>(OperandList[Num])->getValue();
4543 }
4544
4545 std::string SDNode::getOperationName(const SelectionDAG *G) const {
4546   switch (getOpcode()) {
4547   default:
4548     if (getOpcode() < ISD::BUILTIN_OP_END)
4549       return "<<Unknown DAG Node>>";
4550     else {
4551       if (G) {
4552         if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
4553           if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
4554             return TII->get(getOpcode()-ISD::BUILTIN_OP_END).getName();
4555
4556         TargetLowering &TLI = G->getTargetLoweringInfo();
4557         const char *Name =
4558           TLI.getTargetNodeName(getOpcode());
4559         if (Name) return Name;
4560       }
4561
4562       return "<<Unknown Target Node>>";
4563     }
4564    
4565   case ISD::PREFETCH:      return "Prefetch";
4566   case ISD::MEMBARRIER:    return "MemBarrier";
4567   case ISD::ATOMIC_CMP_SWAP:  return "AtomicCmpSwap";
4568   case ISD::ATOMIC_LOAD_ADD:  return "AtomicLoadAdd";
4569   case ISD::ATOMIC_LOAD_SUB:  return "AtomicLoadSub";
4570   case ISD::ATOMIC_LOAD_AND:  return "AtomicLoadAnd";
4571   case ISD::ATOMIC_LOAD_OR:   return "AtomicLoadOr";
4572   case ISD::ATOMIC_LOAD_XOR:  return "AtomicLoadXor";
4573   case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
4574   case ISD::ATOMIC_LOAD_MIN:  return "AtomicLoadMin";
4575   case ISD::ATOMIC_LOAD_MAX:  return "AtomicLoadMax";
4576   case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
4577   case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
4578   case ISD::ATOMIC_SWAP:   return "AtomicSWAP";
4579   case ISD::PCMARKER:      return "PCMarker";
4580   case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
4581   case ISD::SRCVALUE:      return "SrcValue";
4582   case ISD::MEMOPERAND:    return "MemOperand";
4583   case ISD::EntryToken:    return "EntryToken";
4584   case ISD::TokenFactor:   return "TokenFactor";
4585   case ISD::AssertSext:    return "AssertSext";
4586   case ISD::AssertZext:    return "AssertZext";
4587
4588   case ISD::BasicBlock:    return "BasicBlock";
4589   case ISD::ARG_FLAGS:     return "ArgFlags";
4590   case ISD::VALUETYPE:     return "ValueType";
4591   case ISD::Register:      return "Register";
4592
4593   case ISD::Constant:      return "Constant";
4594   case ISD::ConstantFP:    return "ConstantFP";
4595   case ISD::GlobalAddress: return "GlobalAddress";
4596   case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
4597   case ISD::FrameIndex:    return "FrameIndex";
4598   case ISD::JumpTable:     return "JumpTable";
4599   case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
4600   case ISD::RETURNADDR: return "RETURNADDR";
4601   case ISD::FRAMEADDR: return "FRAMEADDR";
4602   case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
4603   case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
4604   case ISD::EHSELECTION: return "EHSELECTION";
4605   case ISD::EH_RETURN: return "EH_RETURN";
4606   case ISD::ConstantPool:  return "ConstantPool";
4607   case ISD::ExternalSymbol: return "ExternalSymbol";
4608   case ISD::INTRINSIC_WO_CHAIN: {
4609     unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
4610     return Intrinsic::getName((Intrinsic::ID)IID);
4611   }
4612   case ISD::INTRINSIC_VOID:
4613   case ISD::INTRINSIC_W_CHAIN: {
4614     unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
4615     return Intrinsic::getName((Intrinsic::ID)IID);
4616   }
4617
4618   case ISD::BUILD_VECTOR:   return "BUILD_VECTOR";
4619   case ISD::TargetConstant: return "TargetConstant";
4620   case ISD::TargetConstantFP:return "TargetConstantFP";
4621   case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
4622   case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
4623   case ISD::TargetFrameIndex: return "TargetFrameIndex";
4624   case ISD::TargetJumpTable:  return "TargetJumpTable";
4625   case ISD::TargetConstantPool:  return "TargetConstantPool";
4626   case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
4627
4628   case ISD::CopyToReg:     return "CopyToReg";
4629   case ISD::CopyFromReg:   return "CopyFromReg";
4630   case ISD::UNDEF:         return "undef";
4631   case ISD::MERGE_VALUES:  return "merge_values";
4632   case ISD::INLINEASM:     return "inlineasm";
4633   case ISD::DBG_LABEL:     return "dbg_label";
4634   case ISD::EH_LABEL:      return "eh_label";
4635   case ISD::DECLARE:       return "declare";
4636   case ISD::HANDLENODE:    return "handlenode";
4637   case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
4638   case ISD::CALL:          return "call";
4639     
4640   // Unary operators
4641   case ISD::FABS:   return "fabs";
4642   case ISD::FNEG:   return "fneg";
4643   case ISD::FSQRT:  return "fsqrt";
4644   case ISD::FSIN:   return "fsin";
4645   case ISD::FCOS:   return "fcos";
4646   case ISD::FPOWI:  return "fpowi";
4647   case ISD::FPOW:   return "fpow";
4648
4649   // Binary operators
4650   case ISD::ADD:    return "add";
4651   case ISD::SUB:    return "sub";
4652   case ISD::MUL:    return "mul";
4653   case ISD::MULHU:  return "mulhu";
4654   case ISD::MULHS:  return "mulhs";
4655   case ISD::SDIV:   return "sdiv";
4656   case ISD::UDIV:   return "udiv";
4657   case ISD::SREM:   return "srem";
4658   case ISD::UREM:   return "urem";
4659   case ISD::SMUL_LOHI:  return "smul_lohi";
4660   case ISD::UMUL_LOHI:  return "umul_lohi";
4661   case ISD::SDIVREM:    return "sdivrem";
4662   case ISD::UDIVREM:    return "divrem";
4663   case ISD::AND:    return "and";
4664   case ISD::OR:     return "or";
4665   case ISD::XOR:    return "xor";
4666   case ISD::SHL:    return "shl";
4667   case ISD::SRA:    return "sra";
4668   case ISD::SRL:    return "srl";
4669   case ISD::ROTL:   return "rotl";
4670   case ISD::ROTR:   return "rotr";
4671   case ISD::FADD:   return "fadd";
4672   case ISD::FSUB:   return "fsub";
4673   case ISD::FMUL:   return "fmul";
4674   case ISD::FDIV:   return "fdiv";
4675   case ISD::FREM:   return "frem";
4676   case ISD::FCOPYSIGN: return "fcopysign";
4677   case ISD::FGETSIGN:  return "fgetsign";
4678
4679   case ISD::SETCC:       return "setcc";
4680   case ISD::VSETCC:      return "vsetcc";
4681   case ISD::SELECT:      return "select";
4682   case ISD::SELECT_CC:   return "select_cc";
4683   case ISD::INSERT_VECTOR_ELT:   return "insert_vector_elt";
4684   case ISD::EXTRACT_VECTOR_ELT:  return "extract_vector_elt";
4685   case ISD::CONCAT_VECTORS:      return "concat_vectors";
4686   case ISD::EXTRACT_SUBVECTOR:   return "extract_subvector";
4687   case ISD::SCALAR_TO_VECTOR:    return "scalar_to_vector";
4688   case ISD::VECTOR_SHUFFLE:      return "vector_shuffle";
4689   case ISD::CARRY_FALSE:         return "carry_false";
4690   case ISD::ADDC:        return "addc";
4691   case ISD::ADDE:        return "adde";
4692   case ISD::SUBC:        return "subc";
4693   case ISD::SUBE:        return "sube";
4694   case ISD::SHL_PARTS:   return "shl_parts";
4695   case ISD::SRA_PARTS:   return "sra_parts";
4696   case ISD::SRL_PARTS:   return "srl_parts";
4697   
4698   case ISD::EXTRACT_SUBREG:     return "extract_subreg";
4699   case ISD::INSERT_SUBREG:      return "insert_subreg";
4700   
4701   // Conversion operators.
4702   case ISD::SIGN_EXTEND: return "sign_extend";
4703   case ISD::ZERO_EXTEND: return "zero_extend";
4704   case ISD::ANY_EXTEND:  return "any_extend";
4705   case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
4706   case ISD::TRUNCATE:    return "truncate";
4707   case ISD::FP_ROUND:    return "fp_round";
4708   case ISD::FLT_ROUNDS_: return "flt_rounds";
4709   case ISD::FP_ROUND_INREG: return "fp_round_inreg";
4710   case ISD::FP_EXTEND:   return "fp_extend";
4711
4712   case ISD::SINT_TO_FP:  return "sint_to_fp";
4713   case ISD::UINT_TO_FP:  return "uint_to_fp";
4714   case ISD::FP_TO_SINT:  return "fp_to_sint";
4715   case ISD::FP_TO_UINT:  return "fp_to_uint";
4716   case ISD::BIT_CONVERT: return "bit_convert";
4717
4718     // Control flow instructions
4719   case ISD::BR:      return "br";
4720   case ISD::BRIND:   return "brind";
4721   case ISD::BR_JT:   return "br_jt";
4722   case ISD::BRCOND:  return "brcond";
4723   case ISD::BR_CC:   return "br_cc";
4724   case ISD::RET:     return "ret";
4725   case ISD::CALLSEQ_START:  return "callseq_start";
4726   case ISD::CALLSEQ_END:    return "callseq_end";
4727
4728     // Other operators
4729   case ISD::LOAD:               return "load";
4730   case ISD::STORE:              return "store";
4731   case ISD::VAARG:              return "vaarg";
4732   case ISD::VACOPY:             return "vacopy";
4733   case ISD::VAEND:              return "vaend";
4734   case ISD::VASTART:            return "vastart";
4735   case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
4736   case ISD::EXTRACT_ELEMENT:    return "extract_element";
4737   case ISD::BUILD_PAIR:         return "build_pair";
4738   case ISD::STACKSAVE:          return "stacksave";
4739   case ISD::STACKRESTORE:       return "stackrestore";
4740   case ISD::TRAP:               return "trap";
4741
4742   // Bit manipulation
4743   case ISD::BSWAP:   return "bswap";
4744   case ISD::CTPOP:   return "ctpop";
4745   case ISD::CTTZ:    return "cttz";
4746   case ISD::CTLZ:    return "ctlz";
4747
4748   // Debug info
4749   case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
4750   case ISD::DEBUG_LOC: return "debug_loc";
4751
4752   // Trampolines
4753   case ISD::TRAMPOLINE: return "trampoline";
4754
4755   case ISD::CONDCODE:
4756     switch (cast<CondCodeSDNode>(this)->get()) {
4757     default: assert(0 && "Unknown setcc condition!");
4758     case ISD::SETOEQ:  return "setoeq";
4759     case ISD::SETOGT:  return "setogt";
4760     case ISD::SETOGE:  return "setoge";
4761     case ISD::SETOLT:  return "setolt";
4762     case ISD::SETOLE:  return "setole";
4763     case ISD::SETONE:  return "setone";
4764
4765     case ISD::SETO:    return "seto";
4766     case ISD::SETUO:   return "setuo";
4767     case ISD::SETUEQ:  return "setue";
4768     case ISD::SETUGT:  return "setugt";
4769     case ISD::SETUGE:  return "setuge";
4770     case ISD::SETULT:  return "setult";
4771     case ISD::SETULE:  return "setule";
4772     case ISD::SETUNE:  return "setune";
4773
4774     case ISD::SETEQ:   return "seteq";
4775     case ISD::SETGT:   return "setgt";
4776     case ISD::SETGE:   return "setge";
4777     case ISD::SETLT:   return "setlt";
4778     case ISD::SETLE:   return "setle";
4779     case ISD::SETNE:   return "setne";
4780     }
4781   }
4782 }
4783
4784 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
4785   switch (AM) {
4786   default:
4787     return "";
4788   case ISD::PRE_INC:
4789     return "<pre-inc>";
4790   case ISD::PRE_DEC:
4791     return "<pre-dec>";
4792   case ISD::POST_INC:
4793     return "<post-inc>";
4794   case ISD::POST_DEC:
4795     return "<post-dec>";
4796   }
4797 }
4798
4799 std::string ISD::ArgFlagsTy::getArgFlagsString() {
4800   std::string S = "< ";
4801
4802   if (isZExt())
4803     S += "zext ";
4804   if (isSExt())
4805     S += "sext ";
4806   if (isInReg())
4807     S += "inreg ";
4808   if (isSRet())
4809     S += "sret ";
4810   if (isByVal())
4811     S += "byval ";
4812   if (isNest())
4813     S += "nest ";
4814   if (getByValAlign())
4815     S += "byval-align:" + utostr(getByValAlign()) + " ";
4816   if (getOrigAlign())
4817     S += "orig-align:" + utostr(getOrigAlign()) + " ";
4818   if (getByValSize())
4819     S += "byval-size:" + utostr(getByValSize()) + " ";
4820   return S + ">";
4821 }
4822
4823 void SDNode::dump() const { dump(0); }
4824 void SDNode::dump(const SelectionDAG *G) const {
4825   cerr << (void*)this << ": ";
4826
4827   for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
4828     if (i) cerr << ",";
4829     if (getValueType(i) == MVT::Other)
4830       cerr << "ch";
4831     else
4832       cerr << getValueType(i).getMVTString();
4833   }
4834   cerr << " = " << getOperationName(G);
4835
4836   cerr << " ";
4837   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
4838     if (i) cerr << ", ";
4839     cerr << (void*)getOperand(i).Val;
4840     if (unsigned RN = getOperand(i).ResNo)
4841       cerr << ":" << RN;
4842   }
4843
4844   if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
4845     SDNode *Mask = getOperand(2).Val;
4846     cerr << "<";
4847     for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
4848       if (i) cerr << ",";
4849       if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
4850         cerr << "u";
4851       else
4852         cerr << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
4853     }
4854     cerr << ">";
4855   }
4856
4857   if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
4858     cerr << "<" << CSDN->getValue() << ">";
4859   } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
4860     if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
4861       cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
4862     else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
4863       cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
4864     else {
4865       cerr << "<APFloat(";
4866       CSDN->getValueAPF().convertToAPInt().dump();
4867       cerr << ")>";
4868     }
4869   } else if (const GlobalAddressSDNode *GADN =
4870              dyn_cast<GlobalAddressSDNode>(this)) {
4871     int offset = GADN->getOffset();
4872     cerr << "<";
4873     WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
4874     if (offset > 0)
4875       cerr << " + " << offset;
4876     else
4877       cerr << " " << offset;
4878   } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
4879     cerr << "<" << FIDN->getIndex() << ">";
4880   } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
4881     cerr << "<" << JTDN->getIndex() << ">";
4882   } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
4883     int offset = CP->getOffset();
4884     if (CP->isMachineConstantPoolEntry())
4885       cerr << "<" << *CP->getMachineCPVal() << ">";
4886     else
4887       cerr << "<" << *CP->getConstVal() << ">";
4888     if (offset > 0)
4889       cerr << " + " << offset;
4890     else
4891       cerr << " " << offset;
4892   } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
4893     cerr << "<";
4894     const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
4895     if (LBB)
4896       cerr << LBB->getName() << " ";
4897     cerr << (const void*)BBDN->getBasicBlock() << ">";
4898   } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
4899     if (G && R->getReg() &&
4900         TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
4901       cerr << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
4902     } else {
4903       cerr << " #" << R->getReg();
4904     }
4905   } else if (const ExternalSymbolSDNode *ES =
4906              dyn_cast<ExternalSymbolSDNode>(this)) {
4907     cerr << "'" << ES->getSymbol() << "'";
4908   } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
4909     if (M->getValue())
4910       cerr << "<" << M->getValue() << ">";
4911     else
4912       cerr << "<null>";
4913   } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
4914     if (M->MO.getValue())
4915       cerr << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
4916     else
4917       cerr << "<null:" << M->MO.getOffset() << ">";
4918   } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
4919     cerr << N->getArgFlags().getArgFlagsString();
4920   } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
4921     cerr << ":" << N->getVT().getMVTString();
4922   }
4923   else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
4924     const Value *SrcValue = LD->getSrcValue();
4925     int SrcOffset = LD->getSrcValueOffset();
4926     cerr << " <";
4927     if (SrcValue)
4928       cerr << SrcValue;
4929     else
4930       cerr << "null";
4931     cerr << ":" << SrcOffset << ">";
4932
4933     bool doExt = true;
4934     switch (LD->getExtensionType()) {
4935     default: doExt = false; break;
4936     case ISD::EXTLOAD:
4937       cerr << " <anyext ";
4938       break;
4939     case ISD::SEXTLOAD:
4940       cerr << " <sext ";
4941       break;
4942     case ISD::ZEXTLOAD:
4943       cerr << " <zext ";
4944       break;
4945     }
4946     if (doExt)
4947       cerr << LD->getMemoryVT().getMVTString() << ">";
4948
4949     const char *AM = getIndexedModeName(LD->getAddressingMode());
4950     if (*AM)
4951       cerr << " " << AM;
4952     if (LD->isVolatile())
4953       cerr << " <volatile>";
4954     cerr << " alignment=" << LD->getAlignment();
4955   } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
4956     const Value *SrcValue = ST->getSrcValue();
4957     int SrcOffset = ST->getSrcValueOffset();
4958     cerr << " <";
4959     if (SrcValue)
4960       cerr << SrcValue;
4961     else
4962       cerr << "null";
4963     cerr << ":" << SrcOffset << ">";
4964
4965     if (ST->isTruncatingStore())
4966       cerr << " <trunc "
4967            << ST->getMemoryVT().getMVTString() << ">";
4968
4969     const char *AM = getIndexedModeName(ST->getAddressingMode());
4970     if (*AM)
4971       cerr << " " << AM;
4972     if (ST->isVolatile())
4973       cerr << " <volatile>";
4974     cerr << " alignment=" << ST->getAlignment();
4975   } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
4976     const Value *SrcValue = AT->getSrcValue();
4977     int SrcOffset = AT->getSrcValueOffset();
4978     cerr << " <";
4979     if (SrcValue)
4980       cerr << SrcValue;
4981     else
4982       cerr << "null";
4983     cerr << ":" << SrcOffset << ">";
4984     if (AT->isVolatile())
4985       cerr << " <volatile>";
4986     cerr << " alignment=" << AT->getAlignment();
4987   }
4988 }
4989
4990 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
4991   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4992     if (N->getOperand(i).Val->hasOneUse())
4993       DumpNodes(N->getOperand(i).Val, indent+2, G);
4994     else
4995       cerr << "\n" << std::string(indent+2, ' ')
4996            << (void*)N->getOperand(i).Val << ": <multiple use>";
4997
4998
4999   cerr << "\n" << std::string(indent, ' ');
5000   N->dump(G);
5001 }
5002
5003 void SelectionDAG::dump() const {
5004   cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
5005   std::vector<const SDNode*> Nodes;
5006   for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
5007        I != E; ++I)
5008     Nodes.push_back(I);
5009   
5010   std::sort(Nodes.begin(), Nodes.end());
5011
5012   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
5013     if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
5014       DumpNodes(Nodes[i], 2, this);
5015   }
5016
5017   if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
5018
5019   cerr << "\n\n";
5020 }
5021
5022 const Type *ConstantPoolSDNode::getType() const {
5023   if (isMachineConstantPoolEntry())
5024     return Val.MachineCPVal->getType();
5025   return Val.ConstVal->getType();
5026 }