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