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