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