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